@wirecat/cli-core 0.621.0 → 0.622.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
@@ -5,6 +5,23 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
+ ## 0.622.0 — 09.11.2026
9
+
10
+ ### Added
11
+
12
+ - `<cli> commands --serve`, in every CLI that starts through `startCli`: one long-running process that runs command
13
+ after command, so WireCat Desktop no longer starts Node for each read on a page. One JSON request per line on stdin
14
+ (`{"id","argv"}`), one answer per line on stdout (`{"id","code","stdout","stderr"}`, what a spawned run would have
15
+ printed). Requests run one at a time; each is recorded as its own run, reads settings and keys again and leaves the
16
+ store closed. A command that runs until stopped, waits on a person or reads stdin is refused with code 2. The
17
+ server ends when stdin closes or after 10 minutes without a request. It is in no help, `commands --json` or MCP.
18
+
19
+ ### Fixed
20
+
21
+ - The store's write-ahead file (`wirecat.db-wal`) no longer stays at the size of the biggest write it ever held: every
22
+ connection sets a 64 MiB journal size limit, so SQLite cuts the file back after a checkpoint. One large CRM sync had
23
+ left a 2.2 GB file behind.
24
+
8
25
  ## 0.621.0 — 09.11.2026
9
26
 
10
27
  ### Added
@@ -0,0 +1,7 @@
1
+ /**
2
+ * `<cli> commands --serve`: one process that runs command after command for WireCat Desktop, which otherwise pays a
3
+ * whole Node start for each read on a page. Matched before the program loads, so it is in no help, no `commands`
4
+ * document and no MCP catalogue — and a flag, because `commands <path>` already describes every top-level word.
5
+ */
6
+ export declare const COMMAND_SERVER_ARGV: readonly string[];
7
+ export declare const isCommandServer: (args: readonly string[]) => boolean;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * `<cli> commands --serve`: one process that runs command after command for WireCat Desktop, which otherwise pays a
3
+ * whole Node start for each read on a page. Matched before the program loads, so it is in no help, no `commands`
4
+ * document and no MCP catalogue — and a flag, because `commands <path>` already describes every top-level word.
5
+ */
6
+ export const COMMAND_SERVER_ARGV = ["commands", "--serve"];
7
+ export const isCommandServer = (args) => args.length === COMMAND_SERVER_ARGV.length && COMMAND_SERVER_ARGV.every((word, at) => args[at] === word);
@@ -0,0 +1,12 @@
1
+ import type { CliEntry, EntryIo, firstRunAt } from "./entry.js";
2
+ /** What `startCli` already has, handed in so the two modules do not import each other. */
3
+ export interface EntryParts {
4
+ firstRunAt: typeof firstRunAt;
5
+ commanderExit: (error: unknown) => number | undefined;
6
+ }
7
+ /**
8
+ * `startCli` for `<cli> commands --serve`: each request runs the CLI's own `run` as a spawned process would, and its
9
+ * output, which the process's streams would have carried, comes back in the answer. Between requests nothing reaches
10
+ * stdout but the protocol; a late write goes to stderr.
11
+ */
12
+ export declare const serveEntry: (entry: CliEntry, io: EntryIo, { firstRunAt, commanderExit }: EntryParts) => Promise<void>;
@@ -0,0 +1,122 @@
1
+ import { PassThrough } from "node:stream";
2
+ import { CliError, catchCrashes } from "@wirecat/cli-base";
3
+ import { useAsProcessRun } from "../runs/scope.js";
4
+ import { ensureSqlite } from "../sqlite-runtime.js";
5
+ import { inCommandServerRequest, refuseInCommandServer, serveCommands } from "./command-server.js";
6
+ /**
7
+ * Every write to the process's stream goes to `sink()`. The stream's `write` is replaced, not the stream: the global
8
+ * console keeps the stream it first wrote to, and `complete` prints through it.
9
+ */
10
+ const route = (stream, sink) => {
11
+ const original = stream.write;
12
+ stream.write = ((chunk, encoding, callback) => {
13
+ sink()(typeof chunk === "string"
14
+ ? Buffer.from(chunk, typeof encoding === "string" ? encoding : "utf8")
15
+ : Buffer.from(chunk));
16
+ const done = typeof encoding === "function" ? encoding : callback;
17
+ if (done)
18
+ process.nextTick(done);
19
+ return true;
20
+ });
21
+ return () => {
22
+ stream.write = original;
23
+ };
24
+ };
25
+ // As a spawned run that Desktop gave no input: anything that reads stdin sees it end at once.
26
+ const closedStdin = () => {
27
+ const stdin = new PassThrough();
28
+ stdin.end();
29
+ return stdin;
30
+ };
31
+ const useStdin = (stdin) => Object.defineProperty(process, "stdin", { value: stdin, configurable: true, enumerable: true, writable: true });
32
+ /**
33
+ * `startCli` for `<cli> commands --serve`: each request runs the CLI's own `run` as a spawned process would, and its
34
+ * output, which the process's streams would have carried, comes back in the answer. Between requests nothing reaches
35
+ * stdout but the protocol; a late write goes to stderr.
36
+ */
37
+ export const serveEntry = async (entry, io, { firstRunAt, commanderExit }) => {
38
+ const release = catchCrashes({
39
+ cli: entry.app.command,
40
+ interactive: false,
41
+ ...(entry.reasons ? { reasons: entry.reasons } : {}),
42
+ target: io.signals,
43
+ });
44
+ const stopper = new AbortController();
45
+ const stop = () => stopper.abort(new CliError("cancelled", "the command server was stopped", { retryable: false }));
46
+ const protocol = io.stdout.write.bind(io.stdout);
47
+ const ownStderr = io.stderr.write.bind(io.stderr);
48
+ const toStderr = (chunk) => {
49
+ ownStderr(chunk);
50
+ };
51
+ let current;
52
+ const unrouteOut = route(process.stdout, () => (current ? (chunk) => current?.stdout.push(chunk) : toStderr));
53
+ const unrouteErr = route(process.stderr, () => (current ? (chunk) => current?.stderr.push(chunk) : toStderr));
54
+ const stdin = Object.getOwnPropertyDescriptor(process, "stdin");
55
+ const requests = io.stdin;
56
+ useStdin(closedStdin());
57
+ io.signals.on("SIGINT", stop).on("SIGTERM", stop);
58
+ io.stdout.on("error", stop);
59
+ const run = async (argv) => {
60
+ const stdout = [];
61
+ const stderr = [];
62
+ current = { stdout, stderr };
63
+ process.exitCode = undefined;
64
+ // Lines written outside a run name the process's run; each request is a process of its own.
65
+ useAsProcessRun(undefined);
66
+ const input = closedStdin();
67
+ useStdin(input);
68
+ const requestIo = { ...io, argv: [...io.argv.slice(0, 2), ...argv], stdin: input };
69
+ const context = {
70
+ args: argv,
71
+ env: io.env,
72
+ tty: false,
73
+ signal: stopper.signal,
74
+ atStart: async (command) => {
75
+ refuseInCommandServer(command, entry.app.command);
76
+ await firstRunAt(entry, requestIo, () => true)(command);
77
+ },
78
+ ask: async () => false,
79
+ openBrowser: async () => undefined,
80
+ outputClosed: () => false,
81
+ };
82
+ let code;
83
+ try {
84
+ code = await inCommandServerRequest(async () => {
85
+ try {
86
+ const returned = await entry.run(context);
87
+ return typeof returned === "number" ? returned : Number(process.exitCode ?? 0);
88
+ }
89
+ catch (error) {
90
+ return commanderExit(error) ?? entry.fail(error, context);
91
+ }
92
+ });
93
+ }
94
+ finally {
95
+ current = undefined;
96
+ process.exitCode = undefined;
97
+ }
98
+ return { code, stdout: Buffer.concat(stdout).toString("utf8"), stderr: Buffer.concat(stderr).toString("utf8") };
99
+ };
100
+ try {
101
+ if (entry.sqlite)
102
+ await ensureSqlite();
103
+ await serveCommands({
104
+ input: requests,
105
+ write: (line) => new Promise((resolve) => (protocol(line) ? resolve() : io.stdout.once("drain", resolve))),
106
+ run,
107
+ cli: entry.app.command,
108
+ version: entry.app.version,
109
+ signal: stopper.signal,
110
+ });
111
+ io.setExitCode(0);
112
+ }
113
+ finally {
114
+ io.signals.off("SIGINT", stop).off("SIGTERM", stop);
115
+ unrouteOut();
116
+ unrouteErr();
117
+ if (stdin)
118
+ Object.defineProperty(process, "stdin", stdin);
119
+ requests.destroy?.();
120
+ release();
121
+ }
122
+ };
@@ -0,0 +1,29 @@
1
+ import type { Command } from "commander";
2
+ export declare const COMMAND_SERVER_PROTOCOL = 1;
3
+ /** An updated tool's old code must not answer for long. */
4
+ export declare const COMMAND_SERVER_IDLE_MS: number;
5
+ export declare const inCommandServerRequest: <T>(work: () => T) => T;
6
+ /** A command the server cannot answer like a spawned run: one that never returns, waits on a person, or reads stdin. */
7
+ export declare const refuseInCommandServer: (command: Command, cli: string) => void;
8
+ export interface CommandAnswer {
9
+ code: number;
10
+ stdout: string;
11
+ stderr: string;
12
+ }
13
+ export interface ServeOptions {
14
+ input: NodeJS.ReadableStream;
15
+ /** One protocol line, the newline included; resolves once it may be written again. */
16
+ write: (line: string) => Promise<void>;
17
+ run: (argv: string[]) => Promise<CommandAnswer>;
18
+ cli: string;
19
+ version: string;
20
+ idleMs?: number;
21
+ /** Ends the server after the request under way. */
22
+ signal?: AbortSignal;
23
+ }
24
+ /**
25
+ * Says it is ready, then answers each line of `input` in order, one at a time: two runs at once in one process would
26
+ * open the store twice, and closing either descriptor drops the other's locks (BUG-557). Resolves with 0 when the
27
+ * input ends or nothing came for `idleMs`.
28
+ */
29
+ export declare const serveCommands: ({ input, write, run, cli, version, idleMs, signal, }: ServeOptions) => Promise<number>;
@@ -0,0 +1,100 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { createInterface } from "node:readline";
3
+ import { CliError, errorObjectOf, renderError } from "@wirecat/cli-base";
4
+ import { metaOf } from "@wirecat/cli-base/commands";
5
+ import { commandPathOf } from "./command-contract.js";
6
+ import { isCommandServer } from "./command-server-argv.js";
7
+ import { stdinFieldOf } from "./stdin-field.js";
8
+ export const COMMAND_SERVER_PROTOCOL = 1;
9
+ /** An updated tool's old code must not answer for long. */
10
+ export const COMMAND_SERVER_IDLE_MS = 10 * 60_000;
11
+ const requests = new AsyncLocalStorage();
12
+ export const inCommandServerRequest = (work) => requests.run(true, work);
13
+ /** A command the server cannot answer like a spawned run: one that never returns, waits on a person, or reads stdin. */
14
+ export const refuseInCommandServer = (command, cli) => {
15
+ if (requests.getStore() !== true)
16
+ return;
17
+ const typed = [cli, ...commandPathOf(command)].join(" ");
18
+ const { lifetime } = metaOf(command);
19
+ if (lifetime)
20
+ throw new CliError("validation_error", `\`${typed}\` ${lifetime === "persistent" ? "runs until it is stopped" : "waits on a person"}; ` +
21
+ "the command server runs only commands that return — start it as a process of its own");
22
+ if (stdinFieldOf(command))
23
+ throw new CliError("validation_error", `\`${typed}\` reads its input on stdin, which the command server does not pass on — start it as a process of its own`);
24
+ };
25
+ const refusal = (cli, message) => `${renderError(errorObjectOf(new CliError("validation_error", message)), { cli, interactive: false })}\n`;
26
+ const requestOf = (line, cli) => {
27
+ let parsed;
28
+ try {
29
+ parsed = JSON.parse(line);
30
+ }
31
+ catch {
32
+ return { id: null, error: "a request is one JSON object per line" };
33
+ }
34
+ const { id, argv } = (parsed ?? {});
35
+ // A request whose id is readable is answered under it, so the client never waits on it.
36
+ const known = typeof id === "number" && Number.isFinite(id) ? id : null;
37
+ if (known === null)
38
+ return { id: null, error: 'a request needs a numeric "id"' };
39
+ if (!Array.isArray(argv) || !argv.every((word) => typeof word === "string"))
40
+ return { id: known, error: '"argv" is a list of strings' };
41
+ if (isCommandServer(argv))
42
+ return { id: known, error: `\`${cli} commands --serve\` cannot run inside itself` };
43
+ return { id: known, argv };
44
+ };
45
+ /**
46
+ * Says it is ready, then answers each line of `input` in order, one at a time: two runs at once in one process would
47
+ * open the store twice, and closing either descriptor drops the other's locks (BUG-557). Resolves with 0 when the
48
+ * input ends or nothing came for `idleMs`.
49
+ */
50
+ export const serveCommands = async ({ input, write, run, cli, version, idleMs = COMMAND_SERVER_IDLE_MS, signal, }) => {
51
+ const send = (value) => write(`${JSON.stringify(value)}\n`);
52
+ await send({ ready: true, protocol: COMMAND_SERVER_PROTOCOL, version });
53
+ const lines = createInterface({ input, crlfDelay: Number.POSITIVE_INFINITY });
54
+ return new Promise((resolve) => {
55
+ let queue = Promise.resolve();
56
+ let waiting = 0;
57
+ let timer;
58
+ let done = false;
59
+ const finish = () => {
60
+ if (done)
61
+ return;
62
+ done = true;
63
+ clearTimeout(timer);
64
+ lines.close();
65
+ resolve(0);
66
+ };
67
+ const idle = () => {
68
+ clearTimeout(timer);
69
+ timer = setTimeout(finish, idleMs);
70
+ };
71
+ const answer = async (line) => {
72
+ const request = requestOf(line, cli);
73
+ if ("error" in request)
74
+ return send({ id: request.id, code: 2, stdout: "", stderr: refusal(cli, request.error) });
75
+ const answered = await run(request.argv);
76
+ return send({ id: request.id, ...answered });
77
+ };
78
+ lines.on("line", (line) => {
79
+ if (done || line.trim() === "")
80
+ return;
81
+ waiting += 1;
82
+ clearTimeout(timer);
83
+ queue = queue
84
+ .then(() => answer(line))
85
+ .catch(finish)
86
+ .then(() => {
87
+ waiting -= 1;
88
+ if (waiting === 0 && !done)
89
+ idle();
90
+ });
91
+ });
92
+ lines.on("close", () => {
93
+ queue = queue.then(finish);
94
+ });
95
+ if (signal?.aborted)
96
+ finish();
97
+ signal?.addEventListener("abort", () => (queue = queue.then(finish)), { once: true });
98
+ idle();
99
+ });
100
+ };
@@ -62,5 +62,7 @@ export interface CliEntry {
62
62
  * output still flushes.
63
63
  */
64
64
  export declare const startCli: (entry: CliEntry) => Promise<void>;
65
+ /** The first-run questions, before the command acts. A dry run writes nothing, and these write the shared config. */
66
+ export declare const firstRunAt: (entry: CliEntry, io: EntryIo, headless: (command: Command) => boolean) => (command: Command) => Promise<void>;
65
67
  /** Opens `url` in the system browser, or in `browser` when given; resolves once the browser has started. */
66
68
  export declare const openBrowser: (url: string, browser?: string, io?: Pick<EntryIo, "platform" | "spawn">) => Promise<void>;
package/dist/cli/entry.js CHANGED
@@ -3,6 +3,7 @@ import { CliError, catchCrashes } from "@wirecat/cli-base";
3
3
  import { envName, readOnlyLockOf } from "../ports/app.js";
4
4
  import { ensureSqlite } from "../sqlite-runtime.js";
5
5
  import { logVersion } from "./argv-log.js";
6
+ import { isCommandServer } from "./command-server-argv.js";
6
7
  const processIo = () => ({
7
8
  argv: process.argv,
8
9
  env: process.env,
@@ -26,6 +27,10 @@ export const startCli = async (entry) => {
26
27
  const args = io.argv.slice(2);
27
28
  if (args.length === 1 && (args[0] === "--version" || args[0] === "-V"))
28
29
  return printVersion(entry.app, io);
30
+ if (isCommandServer(args)) {
31
+ const { serveEntry } = await import("./command-server-entry.js");
32
+ return serveEntry(entry, io, { firstRunAt, commanderExit });
33
+ }
29
34
  const tty = io.stdout.isTTY === true;
30
35
  const release = catchCrashes({
31
36
  cli: entry.app.command,
@@ -58,24 +63,7 @@ export const startCli = async (entry) => {
58
63
  env: io.env,
59
64
  tty,
60
65
  signal: controller.signal,
61
- atStart: async (command) => {
62
- // The first-run questions write the shared config; a dry run writes nothing.
63
- if (command.optsWithGlobals().dryRun === true)
64
- return;
65
- const [{ setupAtStart }, { commandPathOf }] = await Promise.all([
66
- import("./first-run.js"),
67
- import("./command-contract.js"),
68
- ]);
69
- await setupAtStart({
70
- command: entry.app.command,
71
- env: io.env,
72
- contentLanguages: entry.app.contentLanguages,
73
- path: commandPathOf(command),
74
- headless: headless(command),
75
- readOnlyLock: readOnlyLockOf(entry.app, io.env),
76
- input: io.stdin,
77
- });
78
- },
66
+ atStart: firstRunAt(entry, io, headless),
79
67
  ask: async (question, command) => {
80
68
  if (headless(command) || io.stdin.isTTY !== true)
81
69
  return false;
@@ -120,6 +108,24 @@ export const startCli = async (entry) => {
120
108
  else if (code !== undefined)
121
109
  io.setExitCode(code);
122
110
  };
111
+ /** The first-run questions, before the command acts. A dry run writes nothing, and these write the shared config. */
112
+ export const firstRunAt = (entry, io, headless) => async (command) => {
113
+ if (command.optsWithGlobals().dryRun === true)
114
+ return;
115
+ const [{ setupAtStart }, { commandPathOf }] = await Promise.all([
116
+ import("./first-run.js"),
117
+ import("./command-contract.js"),
118
+ ]);
119
+ await setupAtStart({
120
+ command: entry.app.command,
121
+ env: io.env,
122
+ contentLanguages: entry.app.contentLanguages,
123
+ path: commandPathOf(command),
124
+ headless: headless(command),
125
+ readOnlyLock: readOnlyLockOf(entry.app, io.env),
126
+ input: io.stdin,
127
+ });
128
+ };
123
129
  /**
124
130
  * Answered before the program loads, which is most of a start: an agent asks for the version to learn whether the
125
131
  * tool is there at all. Only the bare flag — anything else on the line goes through the program as before.
@@ -18,6 +18,7 @@ import { liftOptionsAfterDashes } from "./after-dashes.js";
18
18
  import { logParsedArgv, logVersion } from "./argv-log.js";
19
19
  import { commandAvailability } from "./command-availability.js";
20
20
  import { commandPathOf } from "./command-contract.js";
21
+ import { refuseInCommandServer } from "./command-server.js";
21
22
  import { entityRows } from "./compact.js";
22
23
  import { outputFor, provide } from "./context.js";
23
24
  import { refuseByCommandPermissions, refuseOfflineCommand, refuseWriteBeforeConnecting } from "./early-refusal.js";
@@ -308,6 +309,7 @@ const runOnce = async (argv, definition, options) => {
308
309
  action.setOptionValue("dryRun", true);
309
310
  refuseOfflineCommand(action, definition.app, flags.offline === true, flags.dryRun === true && localPreview);
310
311
  const path = commandPathOf(action);
312
+ refuseInCommandServer(action, command);
311
313
  const lock = readOnlyLockOf(definition.app, commandEnv);
312
314
  const input = options.stdin ?? process.stdin;
313
315
  // The first-run questions write the shared config; a dry run writes nothing.
@@ -44,7 +44,11 @@ export type OpenDatabase = (path: string) => CacheDatabase;
44
44
  * a writer that finds the database busy fails immediately instead of waiting the moment out.
45
45
  *
46
46
  * `foreign_keys` is off by default in SQLite, which surprises everyone once.
47
+ *
48
+ * Without `journal_size_limit` the `-wal` file keeps the size of the biggest write it ever held: a 106k-row CRM
49
+ * sync left 2.2 GB behind. With it, SQLite cuts the file back to the limit each time a checkpoint resets it.
47
50
  */
48
- export declare const PRAGMAS = "\n PRAGMA busy_timeout = 5000;\n PRAGMA journal_mode = WAL;\n PRAGMA foreign_keys = ON;\n";
51
+ export declare const JOURNAL_SIZE_LIMIT: number;
52
+ export declare const PRAGMAS = "\n PRAGMA busy_timeout = 5000;\n PRAGMA journal_mode = WAL;\n PRAGMA journal_size_limit = 67108864;\n PRAGMA foreign_keys = ON;\n";
49
53
  /** A read-only open sets `query_only`: a search over it reads what is indexed and leaves building it to a writable open. */
50
54
  export declare const isQueryOnly: (database: CacheDatabase) => boolean;
@@ -30,10 +30,15 @@ export const beforeTimeLimit = (until) => {
30
30
  * a writer that finds the database busy fails immediately instead of waiting the moment out.
31
31
  *
32
32
  * `foreign_keys` is off by default in SQLite, which surprises everyone once.
33
+ *
34
+ * Without `journal_size_limit` the `-wal` file keeps the size of the biggest write it ever held: a 106k-row CRM
35
+ * sync left 2.2 GB behind. With it, SQLite cuts the file back to the limit each time a checkpoint resets it.
33
36
  */
37
+ export const JOURNAL_SIZE_LIMIT = 64 * 1024 * 1024;
34
38
  export const PRAGMAS = `
35
39
  PRAGMA busy_timeout = 5000;
36
40
  PRAGMA journal_mode = WAL;
41
+ PRAGMA journal_size_limit = ${JOURNAL_SIZE_LIMIT};
37
42
  PRAGMA foreign_keys = ON;
38
43
  `;
39
44
  /** A read-only open sets `query_only`: a search over it reads what is indexed and leaves building it to a writable open. */
@@ -15,16 +15,19 @@ const accountKeys = (database, ids) => {
15
15
  ? { provider: "notes", account: String(id) }
16
16
  : { provider: String(provider), account: String(external_id) });
17
17
  };
18
- const hasAccountColumn = new Map();
18
+ // Per connection: a long-lived process (`commands --serve`) outlives a migration another CLI runs on the store.
19
+ const hasAccountColumn = new WeakMap();
19
20
  const accountColumnIn = (database, table) => {
20
- const known = hasAccountColumn.get(table);
21
+ const tables = hasAccountColumn.get(database) ?? new Map();
22
+ hasAccountColumn.set(database, tables);
23
+ const known = tables.get(table);
21
24
  if (known !== undefined)
22
25
  return known;
23
26
  const has = database
24
27
  .prepare(`PRAGMA table_info(${table})`)
25
28
  .all()
26
29
  .some((column) => column.name === "account_id");
27
- hasAccountColumn.set(table, has);
30
+ tables.set(table, has);
28
31
  return has;
29
32
  };
30
33
  const ids = (rows) => rows.flatMap(({ account_id }) => (account_id === null || account_id === undefined ? [] : [Number(account_id)]));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.621.0",
3
+ "version": "0.622.0",
4
4
  "description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",