@wirecat/cli-base 0.125.2 → 0.126.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,34 @@ 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.126.0 — 21.11.2026
12
+
13
+ ### Added
14
+
15
+ - **The shared test setup waits for a machine-wide test slot.** Several agents ran suites on one machine at once, each
16
+ with its own workers, and together they took every core and all the memory until the computer froze. Now a test
17
+ file from `@wirecat/cli-base/testing/setup` starts only when it holds one of 8 slots for the whole machine
18
+ (files in `~/.cache/wirecat-test-slots`) and at least 4 GB of memory is available. It gives the slot back when it
19
+ ends; a run killed before that loses its slot to the next one that looks. After 10 minutes of waiting a file runs
20
+ without a slot, and a wait over 30 seconds prints who holds the slots. CI skips this. Settings:
21
+ `WIRECAT_TEST_SLOTS` (`0` turns it off), `WIRECAT_TEST_MIN_FREE_GB`, `WIRECAT_TEST_MAX_WAIT_S`,
22
+ `WIRECAT_TEST_SLOT_DIR`. A CLI gets it with its next cli-base bump; `maxWorkers` still caps each run.
23
+ - **A sign-in method in `--wcat-describe` can name `site: "--site"` and `login: "--login"`.** WireCat Desktop
24
+ (wirecat-desktop #459) signs in a CLI that uses cli-core's application password sign-in in its own window: it asks
25
+ for the site, the user name and the password, passes the first two as those flags and the password on stdin. Until
26
+ now `buildManifest` refused both keys, so a tool added from its describe signed in at a terminal only. Both go
27
+ together, only with `stdin: true`, and only when the method's command takes both flags; any other flag is refused,
28
+ as Desktop refuses it. See [the reference](docs/REFERENCE.md).
29
+
30
+ ## 0.125.3 — 21.11.2026
31
+
32
+ ### Fixed
33
+
34
+ - **`cli-dev audit --family` installs again when the registry drops the connection.** npm's `--fetch-retries` does
35
+ not cover a download cut off midway (`read ECONNRESET`), and about half the family installs failed that way. A
36
+ network error now tries the install up to three times; any other error, such as a package npm does not have,
37
+ fails at once as before.
38
+
11
39
  ## 0.125.2 — 21.11.2026
12
40
 
13
41
  ### Security
@@ -1,3 +1,4 @@
1
+ import type { SpawnSyncReturns } from "node:child_process";
1
2
  import type { ParityGroup } from "../standards/audit.js";
2
3
  /** Every other CLI of the parity groups that npm has, by name. */
3
4
  export declare const familyPackages: (groups: readonly ParityGroup[], own: string) => Map<string, string>;
@@ -7,4 +8,4 @@ export interface Family {
7
8
  close: () => void;
8
9
  }
9
10
  /** Installs the latest published `packages` into a folder of their own, without their install scripts. */
10
- export declare const installFamily: (packages: ReadonlyMap<string, string>) => Family;
11
+ export declare const installFamily: (packages: ReadonlyMap<string, string>, install?: (args: string[]) => SpawnSyncReturns<string>, wait?: number) => Family;
@@ -18,11 +18,15 @@ export const familyPackages = (groups, own) => new Map([...new Set(groups.flatMa
18
18
  .filter((name) => name !== own && PACKAGES.has(name))
19
19
  .sort()
20
20
  .map((name) => [name, PACKAGES.get(name)]));
21
+ // `--fetch-retries` covers a refused request, not a connection the registry drops mid-download: about half the
22
+ // installs of eight CLIs failed that way on 2026-11-19 and 2026-11-21 (`read ECONNRESET`).
23
+ const NETWORK = /^npm error network |\b(ECONNRESET|ETIMEDOUT|EAI_AGAIN|ECONNREFUSED|EPIPE|ENETUNREACH)\b/m;
24
+ const ATTEMPTS = 3;
21
25
  /** Installs the latest published `packages` into a folder of their own, without their install scripts. */
22
- export const installFamily = (packages) => {
26
+ export const installFamily = (packages, install = (args) => spawn.sync("npm", args, { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 }), wait = 3000) => {
23
27
  const prefix = mkdtempSync(join(tmpdir(), "cli-dev-family-"));
24
28
  const close = () => rmSync(prefix, { recursive: true, force: true });
25
- const run = spawn.sync("npm", [
29
+ const args = [
26
30
  "install",
27
31
  "--global",
28
32
  "--prefix",
@@ -35,7 +39,13 @@ export const installFamily = (packages) => {
35
39
  "--fetch-retries",
36
40
  "6",
37
41
  ...packages.values(),
38
- ], { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 });
42
+ ];
43
+ let run = install(args);
44
+ for (let attempt = 1; attempt < ATTEMPTS && run.status !== 0 && NETWORK.test(String(run.stderr)); attempt++) {
45
+ // A connection the registry dropped under load is often dropped again at once.
46
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, wait);
47
+ run = install(args);
48
+ }
39
49
  if (run.error || run.status !== 0) {
40
50
  close();
41
51
  throw new Error(`npm install of the family failed: ${run.error?.message ?? String(run.stderr).trim()}`);
@@ -0,0 +1,22 @@
1
+ /** Set in a run that holds a slot, so a vitest it starts does not wait on its parent's slots. */
2
+ export declare const SLOT_HELD = "WIRECAT_TEST_SLOT_HELD";
3
+ export interface SlotOptions {
4
+ dir: string;
5
+ slots: number;
6
+ minFreeBytes: number;
7
+ maxWaitMs: number;
8
+ pollMs: number;
9
+ freeBytes: () => number;
10
+ alive: (pid: number) => boolean;
11
+ now: () => number;
12
+ sleep: (ms: number) => Promise<void>;
13
+ log: (line: string) => void;
14
+ }
15
+ /**
16
+ * Several agents run test suites on one machine at once, each with its own workers, and together they took every core
17
+ * and all the memory. A slot is a file in one folder for the whole machine: a test file starts once it holds one and
18
+ * enough memory is available, and gives it back when it ends. CI runs one suite per machine and skips this.
19
+ */
20
+ export declare const slotOptions: (env?: NodeJS.ProcessEnv) => SlotOptions | undefined;
21
+ /** Waits for a slot and enough free memory; the result gives the slot back. Past maxWaitMs it goes ahead without one. */
22
+ export declare const acquireSlot: (options: SlotOptions) => Promise<() => void>;
@@ -0,0 +1,127 @@
1
+ import { linkSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { freemem, homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { threadId } from "node:worker_threads";
5
+ const GB = 1024 ** 3;
6
+ /** Set in a run that holds a slot, so a vitest it starts does not wait on its parent's slots. */
7
+ export const SLOT_HELD = "WIRECAT_TEST_SLOT_HELD";
8
+ const alive = (pid) => {
9
+ try {
10
+ process.kill(pid, 0);
11
+ return true;
12
+ }
13
+ catch (error) {
14
+ return error.code === "EPERM";
15
+ }
16
+ };
17
+ const number = (value, fallback) => {
18
+ const parsed = Number(value);
19
+ return value !== undefined && value !== "" && Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
20
+ };
21
+ /**
22
+ * Several agents run test suites on one machine at once, each with its own workers, and together they took every core
23
+ * and all the memory. A slot is a file in one folder for the whole machine: a test file starts once it holds one and
24
+ * enough memory is available, and gives it back when it ends. CI runs one suite per machine and skips this.
25
+ */
26
+ export const slotOptions = (env = process.env) => {
27
+ if (env.CI || env[SLOT_HELD])
28
+ return undefined;
29
+ const slots = number(env.WIRECAT_TEST_SLOTS, 8);
30
+ if (slots === 0)
31
+ return undefined;
32
+ return {
33
+ dir: env.WIRECAT_TEST_SLOT_DIR ?? join(homedir(), ".cache", "wirecat-test-slots"),
34
+ slots,
35
+ minFreeBytes: number(env.WIRECAT_TEST_MIN_FREE_GB, 4) * GB,
36
+ maxWaitMs: number(env.WIRECAT_TEST_MAX_WAIT_S, 600) * 1000,
37
+ pollMs: 500,
38
+ freeBytes: freemem,
39
+ alive,
40
+ now: Date.now,
41
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
42
+ log: (line) => process.stderr.write(`${line}\n`),
43
+ };
44
+ };
45
+ const holders = (options) => {
46
+ const pids = [];
47
+ for (const name of readdirSync(options.dir)) {
48
+ if (!name.startsWith("slot-") || name.endsWith(".tmp"))
49
+ continue;
50
+ const path = join(options.dir, name);
51
+ let pid;
52
+ try {
53
+ pid = Number.parseInt(readFileSync(path, "utf8"), 10);
54
+ }
55
+ catch {
56
+ continue;
57
+ }
58
+ // A run killed before its afterAll, by Ctrl-C or the OOM killer, leaves its slot behind.
59
+ if (Number.isFinite(pid) && options.alive(pid))
60
+ pids.push(pid);
61
+ else
62
+ rmSync(path, { force: true });
63
+ }
64
+ return pids;
65
+ };
66
+ const OWNER = `${process.pid} ${threadId}\n`;
67
+ const take = (options) => {
68
+ // A slot appears with its owner already written: an empty file read in between would look dead and be taken twice.
69
+ const draft = join(options.dir, `slot-${process.pid}-${threadId}.tmp`);
70
+ writeFileSync(draft, OWNER);
71
+ try {
72
+ for (let index = 0; index < options.slots; index++) {
73
+ const path = join(options.dir, `slot-${index}`);
74
+ try {
75
+ linkSync(draft, path);
76
+ return path;
77
+ }
78
+ catch { }
79
+ }
80
+ return undefined;
81
+ }
82
+ finally {
83
+ rmSync(draft, { force: true });
84
+ }
85
+ };
86
+ const giveBack = (path) => {
87
+ let owner;
88
+ try {
89
+ owner = readFileSync(path, "utf8");
90
+ }
91
+ catch { }
92
+ if (owner === OWNER)
93
+ rmSync(path, { force: true });
94
+ };
95
+ /** Waits for a slot and enough free memory; the result gives the slot back. Past maxWaitMs it goes ahead without one. */
96
+ export const acquireSlot = async (options) => {
97
+ mkdirSync(options.dir, { recursive: true });
98
+ const started = options.now();
99
+ let told = started;
100
+ for (;;) {
101
+ const held = holders(options);
102
+ const free = options.freeBytes();
103
+ if (free >= options.minFreeBytes) {
104
+ const path = take(options);
105
+ if (path) {
106
+ // The worker runs its next test file in the same process, which must ask for a slot again.
107
+ process.env[SLOT_HELD] = "1";
108
+ return () => {
109
+ delete process.env[SLOT_HELD];
110
+ giveBack(path);
111
+ };
112
+ }
113
+ }
114
+ const waited = options.now() - started;
115
+ if (waited >= options.maxWaitMs) {
116
+ options.log(`test slots: waited ${Math.round(waited / 1000)} s, running without a slot`);
117
+ return () => { };
118
+ }
119
+ if (options.now() - told >= 30_000) {
120
+ told = options.now();
121
+ options.log(`test slots: waiting, ${held.length} of ${options.slots} held (pids ${[...new Set(held)].join(", ") || "none"}), ` +
122
+ `${(free / GB).toFixed(1)} GB available of ${(options.minFreeBytes / GB).toFixed(0)} GB wanted; ` +
123
+ "WIRECAT_TEST_SLOTS=0 turns this off");
124
+ }
125
+ await options.sleep(options.pollMs);
126
+ }
127
+ };
@@ -1,11 +1,15 @@
1
1
  import { afterAll, afterEach } from "vitest";
2
+ import { acquireSlot, slotOptions } from "./machine-slot.js";
2
3
  import { installNetworkGuard } from "./network.js";
3
4
  import { enterSandbox, installThrowingKeyring, takeKeyringReach } from "./sandbox.js";
4
5
  /**
5
6
  * One vitest `setupFiles` entry for every WireCat CLI: `setupFiles: ["@wirecat/cli-base/testing/setup"]`.
6
7
  * Each test file gets its own sandbox directory, removed when the file is done; the real keyring and
7
- * the network stay out of reach for the whole worker.
8
+ * the network stay out of reach for the whole worker. Off CI, a file first waits for one of the machine's test slots
9
+ * (machine-slot.ts), so suites that several agents start at once share the cores and memory.
8
10
  */
11
+ const slots = slotOptions();
12
+ const release = slots ? await acquireSlot(slots) : () => { };
9
13
  const sandbox = enterSandbox();
10
14
  installThrowingKeyring();
11
15
  installNetworkGuard();
@@ -14,4 +18,11 @@ afterEach(() => {
14
18
  if (stack)
15
19
  throw new Error(`the test passed only because the keyring fell back to a file:\n${stack}`);
16
20
  });
17
- afterAll(() => sandbox.restore());
21
+ afterAll(() => {
22
+ try {
23
+ sandbox.restore();
24
+ }
25
+ finally {
26
+ release();
27
+ }
28
+ });
@@ -36,11 +36,15 @@ declare const signInSchema: v.StrictObjectSchema<{
36
36
  /** `{profile}` first, then the command: `["{profile}", "session", "start", "--json"]`. */
37
37
  readonly words: v.SchemaWithPipe<readonly [v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MaxLengthAction<string, 100, "a command word is at most 100 characters">, v.RegexAction<string, (issue: v.RegexIssue<string>) => string>]>, undefined>, v.MinLengthAction<string[], 1, undefined>]>;
38
38
  readonly stdin: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
39
+ readonly site: v.OptionalSchema<v.LiteralSchema<"--site", undefined>, undefined>;
40
+ readonly login: v.OptionalSchema<v.LiteralSchema<"--login", undefined>, undefined>;
39
41
  }, undefined>, undefined>, v.MinLengthAction<{
40
42
  id: string;
41
43
  label: string;
42
44
  words: string[];
43
45
  stdin?: boolean | undefined;
46
+ site?: "--site" | undefined;
47
+ login?: "--login" | undefined;
44
48
  }[], 1, undefined>]>, undefined>;
45
49
  }, undefined>;
46
50
  export type SignIn = v.InferOutput<typeof signInSchema>;
@@ -71,11 +75,15 @@ declare const desktopSchema: v.StrictObjectSchema<{
71
75
  /** `{profile}` first, then the command: `["{profile}", "session", "start", "--json"]`. */
72
76
  readonly words: v.SchemaWithPipe<readonly [v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MaxLengthAction<string, 100, "a command word is at most 100 characters">, v.RegexAction<string, (issue: v.RegexIssue<string>) => string>]>, undefined>, v.MinLengthAction<string[], 1, undefined>]>;
73
77
  readonly stdin: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
78
+ readonly site: v.OptionalSchema<v.LiteralSchema<"--site", undefined>, undefined>;
79
+ readonly login: v.OptionalSchema<v.LiteralSchema<"--login", undefined>, undefined>;
74
80
  }, undefined>, undefined>, v.MinLengthAction<{
75
81
  id: string;
76
82
  label: string;
77
83
  words: string[];
78
84
  stdin?: boolean | undefined;
85
+ site?: "--site" | undefined;
86
+ login?: "--login" | undefined;
79
87
  }[], 1, undefined>]>, undefined>;
80
88
  }, undefined>, undefined>;
81
89
  readonly skill: v.NullableSchema<v.StrictObjectSchema<{
@@ -196,11 +204,15 @@ export declare const manifestSchema: v.StrictObjectSchema<{
196
204
  /** `{profile}` first, then the command: `["{profile}", "session", "start", "--json"]`. */
197
205
  readonly words: v.SchemaWithPipe<readonly [v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MaxLengthAction<string, 100, "a command word is at most 100 characters">, v.RegexAction<string, (issue: v.RegexIssue<string>) => string>]>, undefined>, v.MinLengthAction<string[], 1, undefined>]>;
198
206
  readonly stdin: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
207
+ readonly site: v.OptionalSchema<v.LiteralSchema<"--site", undefined>, undefined>;
208
+ readonly login: v.OptionalSchema<v.LiteralSchema<"--login", undefined>, undefined>;
199
209
  }, undefined>, undefined>, v.MinLengthAction<{
200
210
  id: string;
201
211
  label: string;
202
212
  words: string[];
203
213
  stdin?: boolean | undefined;
214
+ site?: "--site" | undefined;
215
+ login?: "--login" | undefined;
204
216
  }[], 1, undefined>]>, undefined>;
205
217
  }, undefined>, undefined>;
206
218
  readonly skill: v.NullableSchema<v.StrictObjectSchema<{
@@ -38,8 +38,9 @@ export const SYNC_QUERY = /^command:"[a-z0-9][a-z0-9-]*(?: [a-z0-9][a-z0-9-]*)+"
38
38
  const lastWords = v.pipe(v.array(v.union([plainWord, v.pipe(v.string(), v.regex(SYNC_QUERY))])), v.minLength(1));
39
39
  const line = (max) => v.pipe(v.string(), v.regex(/^\S(?:[^\n\r]*\S)?$/, "one line of text"), v.maxLength(max));
40
40
  /**
41
- * A sign-in Desktop runs in its own window. Only the parts Desktop accepts from a tool it did not build: the words, and
42
- * whether the secret the person types is the command's whole stdin.
41
+ * A sign-in Desktop runs in its own window. Only the parts Desktop accepts from a tool it did not build: the words,
42
+ * whether the secret the person types is the command's whole stdin, and for cli-core's application password sign-in
43
+ * the flags that take the site and the user name Desktop asks for.
43
44
  */
44
45
  const signInMethodSchema = v.strictObject({
45
46
  id: v.pipe(v.string(), v.regex(/^[a-z][a-z0-9-]{0,31}$/, "a lower-case method id")),
@@ -48,6 +49,8 @@ const signInMethodSchema = v.strictObject({
48
49
  /** `{profile}` first, then the command: `["{profile}", "session", "start", "--json"]`. */
49
50
  words,
50
51
  stdin: v.optional(v.boolean()),
52
+ site: v.optional(v.literal("--site")),
53
+ login: v.optional(v.literal("--login")),
51
54
  });
52
55
  const signInSchema = v.strictObject({
53
56
  /** What signing in lets the agent do, in a sentence: "Lets your agent read your Acme contacts." */
@@ -269,8 +272,17 @@ export const buildManifest = ({ identity, commands, pkg, skills }) => {
269
272
  const command = at.get(rest.slice(0, end + 1).join(" "));
270
273
  return command !== undefined && (command.commands.length === 0 || command.runnable === true);
271
274
  };
272
- if (!rest.some((_, end) => runsAt(end)))
275
+ const end = rest.findLastIndex((_, index) => runsAt(index));
276
+ if (end < 0)
273
277
  throw new ManifestError([`signIn method ${method.id}: \`${rest.join(" ")}\` names no command of this CLI`]);
278
+ if (method.site || method.login) {
279
+ if (!method.site || !method.login || method.stdin !== true)
280
+ throw new ManifestError([`signIn method ${method.id}: site and login go together, with the password on stdin`]);
281
+ const path = rest.slice(0, end + 1).join(" ");
282
+ const lacks = [method.site, method.login].filter((flag) => !takes(path, flag));
283
+ if (lacks.length > 0)
284
+ throw new ManifestError([`signIn method ${method.id}: \`${path}\` takes no ${lacks.join(" or ")}`]);
285
+ }
274
286
  if (rest.some((word) => word.includes("{")))
275
287
  throw new ManifestError([`signIn method ${method.id}: {profile} is the only slot Desktop fills in a sign-in`]);
276
288
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-base",
3
- "version": "0.125.2",
3
+ "version": "0.126.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",