@wirecat/cli-core 0.429.0 → 0.431.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
@@ -7,6 +7,25 @@ shape of this file.
7
7
 
8
8
  ## Unreleased
9
9
 
10
+ ## 0.431.0 — 25.10.2026
11
+
12
+ ### Added
13
+
14
+ - **`readConfigText(path)`, `readConfigFile(path)`, `withoutSetting(raw, setting)` and `settingPathOf(setting)` from `/cli`**, for a tool with its own config file and `config unset`. `readConfigText` gives the text, `undefined` for no file, or an issue for a folder at the path or a file that cannot be read. `readConfigFile` adds the JSON parse. `withoutSetting` removes one setting at any depth, list items included (`mail.accounts.0.colour`, `permissions.messages.send`), and any object the removal leaves empty, but keeps a list item so the items after it keep their numbers.
15
+
16
+ ### Fixed
17
+
18
+ - **A bad setting inside a list item is removed alone.** Before, `checkConfigText` could not reach into a list. It reported `mail.accounts.0.colour`, then loaded the rest of the file as empty, and missed issues elsewhere (an unknown permission key) until the next run. Now everything else loads, and every issue is found in one pass, in nested lists too. An item of the wrong type is dropped, and the items after it are still named by their place in the file. `config unset` with no profile reaches a path through a list.
19
+ - **A config file that cannot be read is reported, not taken for no file.** A folder at the path gives `invalid_value` "the path is a folder, not a file"; a file this user may not read gives "the file could not be read". Neither has a `fix`. `loadSnakeCaseConfig` refuses both instead of using its fallback.
20
+ - **A file holding a list, a string, a number or `null` is refused as a whole**: `invalid_value` "the file must hold a JSON object", with no `key` and no `fix`. Before, valibot read `[]` as `{}`.
21
+ - **`privateFiles` suggests no file mode for a folder where a file should be**, or for a file where a folder should be: the config issue says what is wrong.
22
+
23
+ ## 0.430.0 — 25.10.2026
24
+
25
+ ### Added
26
+
27
+ - **Run records for a CLI with its own commander program** (`/cli`). `recordRuns(program, options)` gives a `startCli` tool WC-LIFE-15 in one call: `--record` and `--no-record`, a failed run for every failed command — a usage error before any action included, named by its command words and never an argument — and a run of every command when the flag or the saved `record` asks. `providerEvent(event)` and `providerRequest(operation)` put a provider call's operation, status and duration into the current command's run from anywhere in the program. `commandRuns(options)` keeps one command's run from a tool's own hooks under `run()`, and `runSettings(flag, saved)` is the rule both follow. zoom-cli, drive-cli and cli-memo replace their own copies with it. A run with no profile now leaves `profile` out rather than writing `""`.
28
+
10
29
  ## 0.429.0 — 25.10.2026
11
30
 
12
31
  ### Added
@@ -0,0 +1,64 @@
1
+ import { type RenderFormat, type Streams } from "@wirecat/cli-base";
2
+ import type { Command } from "commander";
3
+ import type { AppIdentity } from "../ports/app.js";
4
+ import type { RequestEvent } from "../runs/events.js";
5
+ /** What the owner saved: `record` and `keep_runs_for_days`, read from the CLI's own config. */
6
+ export interface SavedRunSettings {
7
+ record?: boolean | undefined;
8
+ keepRunsForDays?: number | undefined;
9
+ }
10
+ export interface RunSettings {
11
+ record: boolean;
12
+ keepFailedRuns: boolean;
13
+ keepRunsForDays: number;
14
+ }
15
+ /** `--record`/`--no-record` first, then the config; a failure is kept unless either says no (WC-LIFE-15). */
16
+ export declare const runSettings: (flag: boolean | undefined, saved?: SavedRunSettings) => RunSettings;
17
+ export interface CommandRunOptions {
18
+ app: AppIdentity;
19
+ /** The owner's saved choice. One that throws — a config that will not load — leaves the defaults. */
20
+ settings: () => SavedRunSettings;
21
+ /**
22
+ * The profile the command runs for; one that throws or is empty leaves the run without one. Given only by a CLI
23
+ * whose first word may be a profile, so a failure before any command skips that word when naming the run.
24
+ */
25
+ profile?: () => string | undefined;
26
+ /** An agent's run is named `mcp <command>`. Read from the program's environment when left out. */
27
+ agent?: boolean;
28
+ /** The data stream's format, which the warning about an unwritable run follows; `--json`/`--jsonl` when left out. */
29
+ format?: () => RenderFormat;
30
+ /** What a failed run keeps of the error: cli-memo turns a Commander or Valibot error into a CLI error first. */
31
+ recognise?: (error: unknown) => unknown;
32
+ env?: NodeJS.ProcessEnv;
33
+ streams?: Streams;
34
+ }
35
+ /** One command's run at a time, for a CLI that starts and ends it from its own hooks (zoom-cli under `run()`). */
36
+ export interface CommandRuns {
37
+ start(action: Command): void;
38
+ succeed(): Promise<void>;
39
+ fail(error: unknown): Promise<void>;
40
+ /** The id the command's run has, kept or not, so its answer can name it. */
41
+ runId(): string | undefined;
42
+ events(event: RequestEvent): void;
43
+ }
44
+ export declare const commandRuns: (options: CommandRunOptions) => CommandRuns;
45
+ /** For a provider client far from the program: the event lands in the current command's run, or nowhere. */
46
+ export declare const providerEvent: (event: RequestEvent) => void;
47
+ /**
48
+ * Times one provider call under a fixed operation name — nothing the call carries goes into the run. The returned
49
+ * function ends it; an `error` or an `errorCode` makes it a failed one.
50
+ */
51
+ export declare const providerRequest: (operation: string, sink?: (event: RequestEvent) => void) => ({ status, error, errorCode }?: {
52
+ status?: number;
53
+ error?: unknown;
54
+ errorCode?: string;
55
+ }) => void;
56
+ /**
57
+ * WC-LIFE-15 for a CLI with its own commander program (`startCli`, not `run()`): adds `--record` and `--no-record`,
58
+ * keeps every failed command as a run — a usage error before any action too — and every command when recording is
59
+ * on. Call it after the program's other `parseAsync` wrappers, so its own is the outermost and sees how the parse
60
+ * really ended; a refusal in an earlier `preAction` hook is then kept under the words read from the line.
61
+ */
62
+ export declare const recordRuns: (program: Command, options: CommandRunOptions & {
63
+ content: string;
64
+ }) => void;
@@ -0,0 +1,171 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { isCliError } from "@wirecat/cli-base";
3
+ import { startRecording, wasSettled } from "../runs/recording.js";
4
+ import { KEEP_RUNS_FOR_DAYS } from "../runs/run.js";
5
+ import { environmentOf } from "./context.js";
6
+ /** `--record`/`--no-record` first, then the config; a failure is kept unless either says no (WC-LIFE-15). */
7
+ export const runSettings = (flag, saved = {}) => {
8
+ const record = flag ?? saved.record ?? false;
9
+ return {
10
+ record,
11
+ keepFailedRuns: record || (flag !== false && saved.record !== false),
12
+ keepRunsForDays: saved.keepRunsForDays ?? KEEP_RUNS_FOR_DAYS,
13
+ };
14
+ };
15
+ const SKIPPED = new Set(["runs", "help"]);
16
+ const pathOf = (command) => {
17
+ const words = [];
18
+ for (let at = command; at?.parent; at = at.parent)
19
+ words.unshift(at.name());
20
+ return words;
21
+ };
22
+ const tracker = (options) => {
23
+ let recording;
24
+ const open = (program, words, flag, format) => {
25
+ recording = undefined;
26
+ // Reading the log is not worth a run of its own.
27
+ if (SKIPPED.has(words[0] ?? ""))
28
+ return;
29
+ const environment = environmentOf(program);
30
+ let saved = {};
31
+ try {
32
+ saved = options.settings();
33
+ }
34
+ catch { }
35
+ let profile;
36
+ try {
37
+ profile = options.profile?.() || undefined;
38
+ }
39
+ catch { }
40
+ const settings = runSettings(flag, saved);
41
+ const agent = options.agent ?? environment.agent !== undefined;
42
+ const streams = options.streams ?? environment.streams;
43
+ const env = options.env ?? environment.env;
44
+ recording = startRecording({
45
+ app: options.app,
46
+ command: `${agent ? "mcp " : ""}${words.join(" ") || options.app.command}`,
47
+ ...(profile === undefined ? {} : { profile }),
48
+ record: settings.record,
49
+ keepFailed: settings.keepFailedRuns,
50
+ keepDays: settings.keepRunsForDays,
51
+ trace: false,
52
+ format,
53
+ ...(streams ? { streams } : {}),
54
+ ...(env ? { env } : {}),
55
+ });
56
+ };
57
+ const finish = () => {
58
+ const done = recording;
59
+ recording = undefined;
60
+ return done;
61
+ };
62
+ return {
63
+ start(action) {
64
+ const flags = action.optsWithGlobals();
65
+ const json = (flags.json !== undefined && flags.json !== false) || Boolean(flags.jsonl);
66
+ open(action, pathOf(action), flags.record, options.format?.() ?? (json ? "json" : "pretty"));
67
+ },
68
+ async succeed() {
69
+ await finish()?.succeed();
70
+ },
71
+ async fail(error) {
72
+ await finish()?.fail(options.recognise ? options.recognise(error) : error);
73
+ },
74
+ runId: () => recording?.runId,
75
+ events: (event) => recording?.events(event),
76
+ open,
77
+ };
78
+ };
79
+ export const commandRuns = (options) => tracker(options);
80
+ const parses = new AsyncLocalStorage();
81
+ /** For a provider client far from the program: the event lands in the current command's run, or nowhere. */
82
+ export const providerEvent = (event) => parses.getStore()?.runs.events(event);
83
+ /**
84
+ * Times one provider call under a fixed operation name — nothing the call carries goes into the run. The returned
85
+ * function ends it; an `error` or an `errorCode` makes it a failed one.
86
+ */
87
+ export const providerRequest = (operation, sink = providerEvent) => {
88
+ sink({ event: "request", operation });
89
+ const started = performance.now();
90
+ return ({ status, error, errorCode } = {}) => {
91
+ const failed = error !== undefined || errorCode !== undefined;
92
+ sink({
93
+ event: "response",
94
+ operation,
95
+ ...(status === undefined ? {} : { status }),
96
+ durationMs: Math.round(performance.now() - started),
97
+ outcome: failed ? "error" : "ok",
98
+ ...(failed ? { errorCode: errorCode ?? (isCliError(error) ? error.code : "provider_error") } : {}),
99
+ });
100
+ };
101
+ };
102
+ /** `files list` from `files list abc --limit 5`: command words only, never an argument. */
103
+ const pathFromArgs = (program, args, profileWord) => {
104
+ const words = [];
105
+ let at = program;
106
+ let skipped = !profileWord;
107
+ for (const arg of args) {
108
+ if (arg.startsWith("-"))
109
+ continue;
110
+ const next = at.commands.find((one) => one.name() === arg || one.aliases().includes(arg));
111
+ if (next) {
112
+ words.push(arg);
113
+ at = next;
114
+ }
115
+ else if (words.length === 0 && !skipped)
116
+ skipped = true;
117
+ else
118
+ break;
119
+ }
120
+ return words;
121
+ };
122
+ const isHelpExit = (error) => {
123
+ const { code, exitCode } = (error ?? {});
124
+ return typeof code === "string" && code.startsWith("commander.") && (exitCode === 0 || code === "commander.help");
125
+ };
126
+ /**
127
+ * WC-LIFE-15 for a CLI with its own commander program (`startCli`, not `run()`): adds `--record` and `--no-record`,
128
+ * keeps every failed command as a run — a usage error before any action too — and every command when recording is
129
+ * on. Call it after the program's other `parseAsync` wrappers, so its own is the outermost and sees how the parse
130
+ * really ended; a refusal in an earlier `preAction` hook is then kept under the words read from the line.
131
+ */
132
+ export const recordRuns = (program, options) => {
133
+ program
134
+ .option("--record", `keep this run — ids and timings, never ${options.content}`)
135
+ .option("--no-record", "do not keep this run, even if it fails");
136
+ program.hook("preAction", (_root, action) => {
137
+ const parse = parses.getStore();
138
+ if (!parse)
139
+ return;
140
+ parse.started = true;
141
+ parse.runs.start(action);
142
+ });
143
+ const parseAsync = program.parseAsync.bind(program);
144
+ program.parseAsync = (argv, settings) => {
145
+ const parse = { runs: tracker(options), started: false };
146
+ return parses.run(parse, async () => {
147
+ try {
148
+ const parsed = await parseAsync(argv, settings);
149
+ await parse.runs.succeed();
150
+ return parsed;
151
+ }
152
+ catch (error) {
153
+ if (!isHelpExit(error) && !wasSettled(error)) {
154
+ try {
155
+ if (!parse.started) {
156
+ const args = settings?.from === "user" ? (argv ?? []) : (argv ?? process.argv).slice(2);
157
+ const flag = args.includes("--no-record") ? false : args.includes("--record") ? true : undefined;
158
+ const json = args.some((arg) => arg === "--json" || arg.startsWith("--json=") || arg === "--jsonl");
159
+ const words = pathFromArgs(program, args, options.profile !== undefined);
160
+ const format = options.format?.() ?? (json ? "json" : "pretty");
161
+ parse.runs.open(program, words, flag, format);
162
+ }
163
+ await parse.runs.fail(error);
164
+ }
165
+ catch { }
166
+ }
167
+ throw error;
168
+ }
169
+ });
170
+ };
171
+ };
@@ -46,6 +46,21 @@ export declare const permissionIssues: (saved: readonly {
46
46
  }) => LocatedIssue[];
47
47
  /** The file without the settings the issues name: what still loads, and what `config unset` would leave. */
48
48
  export declare const withoutIssues: (raw: unknown, issues: readonly LocatedIssue[]) => unknown;
49
+ /** The path `config unset <setting>` names: a permission key keeps its dots; a number is a list item. */
50
+ export declare const settingPathOf: (setting: string) => string[];
51
+ /**
52
+ * The file without one setting, at any depth and inside list items, and without any object the removal left empty
53
+ * — a list item stays, so the items after it keep their numbers. `removed` is false when nothing was there.
54
+ */
55
+ export declare const withoutPath: (raw: unknown, at: readonly string[]) => {
56
+ config: unknown;
57
+ removed: boolean;
58
+ };
59
+ /** `withoutPath` for a setting as `config unset` takes it: `mail.accounts.0.colour`, `permissions.messages.send`. */
60
+ export declare const withoutSetting: (raw: unknown, setting: string) => {
61
+ config: unknown;
62
+ removed: boolean;
63
+ };
49
64
  /** The public shape: where in the file is the loader's own business. */
50
65
  export declare const publicIssue: ({ at: _, ...issue }: LocatedIssue) => ConfigIssue;
51
66
  /**
@@ -68,3 +83,18 @@ export declare const checkConfigText: <T extends v.GenericSchema>(text: string,
68
83
  issues: ConfigIssue[];
69
84
  config: v.InferOutput<T> | undefined;
70
85
  };
86
+ /**
87
+ * A config file's text, `undefined` when there is no file, or the issue when one is there and cannot be read: a
88
+ * folder at the path, or a file this user may not read. Neither has a fix `config` could run.
89
+ */
90
+ export declare const readConfigText: (path: string) => {
91
+ text: string | undefined;
92
+ } | {
93
+ issue: ConfigIssue;
94
+ };
95
+ /** A config file as written, `raw: undefined` when there is none, or the one issue that stops it being read. */
96
+ export declare const readConfigFile: (path: string) => {
97
+ raw: unknown;
98
+ } | {
99
+ issue: ConfigIssue;
100
+ };
@@ -1,3 +1,4 @@
1
+ import { readFileSync } from "node:fs";
1
2
  import * as v from "valibot";
2
3
  const isNode = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3
4
  const SECTIONS = ["personal", "bot"];
@@ -171,12 +172,12 @@ const ruleOf = (issue) => {
171
172
  return issue.expected === null ? "has a value it does not take" : `has to be ${issue.expected}`;
172
173
  };
173
174
  /** One pass of the schema: valibot names only the first unknown key of each object. */
174
- const onePass = (raw, schema, context) => {
175
+ const onePass = (raw, schema, context, original) => {
175
176
  const result = v.safeParse(schema, raw);
176
177
  if (result.success)
177
178
  return [];
178
179
  return result.issues.map((issue) => {
179
- const at = keyOfPath(issue);
180
+ const at = original(keyOfPath(issue));
180
181
  const located = isPermissionKey(issue, at)
181
182
  ? locate("unknown_permission", at, context, (key) => `${key} names no command`)
182
183
  : isUnknownKey(issue)
@@ -186,6 +187,8 @@ const onePass = (raw, schema, context) => {
186
187
  : locate("invalid_value", at, context, (key) => at.length === 0 ? "the file has to be an object, in braces" : `setting ${key} ${ruleOf(issue)}`);
187
188
  if (located.kind === "missing_setting" || at.length === 0)
188
189
  delete located.fix;
190
+ if (at.length === 0)
191
+ delete located.key;
189
192
  return located;
190
193
  });
191
194
  };
@@ -193,7 +196,8 @@ const onePass = (raw, schema, context) => {
193
196
  export const schemaIssues = (raw, schema, context) => {
194
197
  const found = new Map();
195
198
  for (;;) {
196
- const fresh = onePass(withoutIssues(raw, [...found.values()]), schema, context).filter((issue) => !found.has(issue.at.join("\u0000")));
199
+ const { pruned, original } = prune(raw, [...found.values()].map(({ at }) => at));
200
+ const fresh = onePass(pruned, schema, context, original).filter((issue) => !found.has(issue.at.join("\u0000")));
197
201
  if (fresh.length === 0)
198
202
  return [...found.values()];
199
203
  for (const issue of fresh)
@@ -235,18 +239,60 @@ export const savedPermissionKeys = (raw) => scopes(raw).flatMap(([path, scope])
235
239
  export const permissionIssues = (saved, known, context) => saved
236
240
  .filter(({ key }) => !known.has(key))
237
241
  .map(({ at }) => locate("unknown_permission", at, context, (key) => `${key} names no command`));
242
+ const pathId = (path) => path.join("\u0000");
243
+ /**
244
+ * The file without the parts at `paths`, through objects and lists alike, and a map from a path in what is left
245
+ * back to the file: a list that lost an item numbers the rest differently.
246
+ */
247
+ const prune = (raw, paths) => {
248
+ const drop = new Set(paths.map(pathId));
249
+ const kept = new Map();
250
+ const walk = (node, at) => {
251
+ if (Array.isArray(node)) {
252
+ const indices = node.flatMap((_, index) => (drop.has(pathId([...at, String(index)])) ? [] : [index]));
253
+ kept.set(pathId(at), indices);
254
+ return indices.map((index) => walk(node[index], [...at, String(index)]));
255
+ }
256
+ if (!isNode(node))
257
+ return node;
258
+ return Object.fromEntries(Object.entries(node).flatMap(([key, item]) => drop.has(pathId([...at, key])) ? [] : [[key, walk(item, [...at, key])]]));
259
+ };
260
+ const pruned = drop.has("") ? {} : walk(raw, []);
261
+ const original = (path) => {
262
+ const at = [];
263
+ for (const part of path) {
264
+ const indices = kept.get(pathId(at));
265
+ at.push(indices ? String(indices[Number(part)] ?? part) : part);
266
+ }
267
+ return at;
268
+ };
269
+ return { pruned, original };
270
+ };
238
271
  /** The file without the settings the issues name: what still loads, and what `config unset` would leave. */
239
- export const withoutIssues = (raw, issues) => {
240
- if (issues.some((issue) => issue.at.length === 0))
241
- return {};
242
- const copy = structuredClone(raw);
243
- for (const { at } of issues) {
244
- const parent = at.slice(0, -1).reduce((node, key) => (isNode(node) ? node[key] : undefined), copy);
245
- if (isNode(parent))
246
- delete parent[at.at(-1)];
272
+ export const withoutIssues = (raw, issues) => prune(raw, issues.map(({ at }) => at)).pruned;
273
+ /** The path `config unset <setting>` names: a permission key keeps its dots; a number is a list item. */
274
+ export const settingPathOf = (setting) => setting.startsWith("permissions.") ? ["permissions", setting.slice("permissions.".length)] : setting.split(".");
275
+ /**
276
+ * The file without one setting, at any depth and inside list items, and without any object the removal left empty
277
+ * — a list item stays, so the items after it keep their numbers. `removed` is false when nothing was there.
278
+ */
279
+ export const withoutPath = (raw, at) => {
280
+ const valueAt = (path) => path.reduce((node, key) => (isNode(node) || Array.isArray(node) ? node[key] : undefined), raw);
281
+ if (at.length === 0 || valueAt(at) === undefined)
282
+ return { config: raw, removed: false };
283
+ let gone = [...at];
284
+ for (let parent = at.slice(0, -1); parent.length > 0; parent = parent.slice(0, -1)) {
285
+ if (Array.isArray(valueAt(parent.slice(0, -1))))
286
+ break;
287
+ const node = valueAt(parent);
288
+ if (!isNode(node) || Object.keys(node).some((key) => pathId([...parent, key]) !== pathId(gone)))
289
+ break;
290
+ gone = parent;
247
291
  }
248
- return copy;
292
+ return { config: prune(raw, [gone]).pruned, removed: true };
249
293
  };
294
+ /** `withoutPath` for a setting as `config unset` takes it: `mail.accounts.0.colour`, `permissions.messages.send`. */
295
+ export const withoutSetting = (raw, setting) => withoutPath(raw, settingPathOf(setting));
250
296
  /** The public shape: where in the file is the loader's own business. */
251
297
  export const publicIssue = ({ at: _, ...issue }) => issue;
252
298
  /**
@@ -272,6 +318,9 @@ export const checkConfigText = (text, { file, tool, schema, knownPermissions, })
272
318
  const parsed = parseConfigText(text, file);
273
319
  if ("issue" in parsed)
274
320
  return { issues: [publicIssue(parsed.issue)], config: undefined };
321
+ // valibot reads a list as an object, so `[]` would pass for `{}`.
322
+ if (!isNode(parsed.raw))
323
+ return { issues: [wholeFile(file, "the file must hold a JSON object")], config: undefined };
275
324
  const context = { file, tool };
276
325
  const located = schemaIssues(parsed.raw, schema, context);
277
326
  const loaded = v.safeParse(schema, withoutIssues(parsed.raw, located));
@@ -279,3 +328,32 @@ export const checkConfigText = (text, { file, tool, schema, knownPermissions, })
279
328
  const unknown = knownPermissions ? permissionIssues(savedPermissionKeys(config), knownPermissions, context) : [];
280
329
  return { issues: [...located, ...unknown].map(publicIssue), config };
281
330
  };
331
+ /** A problem with the file as a whole: no setting to name, and no `config unset` to remove it. */
332
+ const wholeFile = (file, what) => ({ kind: "invalid_value", file, what });
333
+ /**
334
+ * A config file's text, `undefined` when there is no file, or the issue when one is there and cannot be read: a
335
+ * folder at the path, or a file this user may not read. Neither has a fix `config` could run.
336
+ */
337
+ export const readConfigText = (path) => {
338
+ try {
339
+ return { text: readFileSync(path, "utf8") };
340
+ }
341
+ catch (error) {
342
+ const code = error.code;
343
+ if (code === "ENOENT")
344
+ return { text: undefined };
345
+ return {
346
+ issue: wholeFile(path, code === "EISDIR" ? "the path is a folder, not a file" : "the file could not be read"),
347
+ };
348
+ }
349
+ };
350
+ /** A config file as written, `raw: undefined` when there is none, or the one issue that stops it being read. */
351
+ export const readConfigFile = (path) => {
352
+ const read = readConfigText(path);
353
+ if ("issue" in read)
354
+ return read;
355
+ if (read.text === undefined)
356
+ return { raw: undefined };
357
+ const parsed = parseConfigText(read.text, path);
358
+ return "issue" in parsed ? { issue: publicIssue(parsed.issue) } : parsed;
359
+ };
@@ -1,6 +1,6 @@
1
- import { readFileSync } from "node:fs";
2
1
  import { CliError } from "@wirecat/cli-base";
3
2
  import * as v from "valibot";
3
+ import { readConfigText } from "./config-issues.js";
4
4
  const reasonOf = (issue) => {
5
5
  if (issue.expected === "never")
6
6
  return "is an unknown setting";
@@ -23,13 +23,12 @@ const problemOf = (issues) => {
23
23
  };
24
24
  /** Reads and checks a config file; a missing one is the fallback, a broken one an error naming its first problem. */
25
25
  export const loadSnakeCaseConfig = (path, schema, fallback) => {
26
- let text;
27
- try {
28
- text = readFileSync(path, "utf8");
29
- }
30
- catch {
26
+ const read = readConfigText(path);
27
+ if ("issue" in read)
28
+ throw new CliError("configuration_error", `${path}: ${read.issue.what}`);
29
+ if (read.text === undefined)
31
30
  return fallback();
32
- }
31
+ const text = read.text;
33
32
  let parsed;
34
33
  try {
35
34
  parsed = JSON.parse(text);
@@ -50,9 +50,10 @@ export { BotTokenStore, type BotTokenStoreOptions } from "./bot/token.js";
50
50
  export { PressLog, UpdatesCursor } from "./bot/updates.js";
51
51
  export type { CommandAvailability, DiscoveredCommand } from "./command-availability.js";
52
52
  export { commandContract, type JsonSchema, SCHEMA_DIALECT } from "./command-contract.js";
53
+ export { type CommandRunOptions, type CommandRuns, commandRuns, providerEvent, providerRequest, type RunSettings, recordRuns, runSettings, type SavedRunSettings, } from "./command-runs.js";
53
54
  export { CONTRACT } from "./commands-command.js";
54
55
  export { refuseUnknownKey } from "./config-command.js";
55
- export { type ConfigIssue, type ConfigIssueKind, checkConfigText, issueMessage } from "./config-issues.js";
56
+ export { type ConfigIssue, type ConfigIssueKind, checkConfigText, issueMessage, readConfigFile, readConfigText, settingPathOf, withoutSetting, } from "./config-issues.js";
56
57
  export { loadSnakeCaseConfig } from "./config-keys.js";
57
58
  export { type AgentRun, type BaseContext, type BaseEnvironment, baseContext, environmentOf, outputFor, provide, secretInputOf, } from "./context.js";
58
59
  export { addContractInfo, type ContractEvidenceOptions, contractEvidence } from "./contract-evidence.js";
package/dist/cli/index.js CHANGED
@@ -43,9 +43,10 @@ export { botFiles, botsDirectory, ChatRegistry, registryProfiles } from "./bot/r
43
43
  export { BotTokenStore } from "./bot/token.js";
44
44
  export { PressLog, UpdatesCursor } from "./bot/updates.js";
45
45
  export { commandContract, SCHEMA_DIALECT } from "./command-contract.js";
46
+ export { commandRuns, providerEvent, providerRequest, recordRuns, runSettings, } from "./command-runs.js";
46
47
  export { CONTRACT } from "./commands-command.js";
47
48
  export { refuseUnknownKey } from "./config-command.js";
48
- export { checkConfigText, issueMessage } from "./config-issues.js";
49
+ export { checkConfigText, issueMessage, readConfigFile, readConfigText, settingPathOf, withoutSetting, } from "./config-issues.js";
49
50
  export { loadSnakeCaseConfig } from "./config-keys.js";
50
51
  export { baseContext, environmentOf, outputFor, provide, secretInputOf, } from "./context.js";
51
52
  export { addContractInfo, contractEvidence } from "./contract-evidence.js";
@@ -8,19 +8,23 @@ export const privateFiles = ({ files, dirs }, platform = process.platform) => {
8
8
  if (platform === "win32")
9
9
  return { checked: false, reason: "Windows has no Unix file modes" };
10
10
  const problems = [];
11
- const check = (path, want) => {
11
+ // A folder where a file should be, or the reverse, is a problem of its own; a mode is no fix for it.
12
+ const check = (path, want, folder) => {
12
13
  if (!existsSync(path))
13
14
  return;
14
- const mode = statSync(path).mode & 0o777;
15
+ const stat = statSync(path);
16
+ if (stat.isDirectory() !== folder)
17
+ return;
18
+ const mode = stat.mode & 0o777;
15
19
  if ((mode & 0o077) === 0)
16
20
  return;
17
21
  const octal = (value) => `0${value.toString(8)}`;
18
22
  problems.push({ path, mode: octal(mode), want: octal(want), fix: `chmod ${want.toString(8)} ${shellQuoted(path)}` });
19
23
  };
20
24
  for (const file of files)
21
- check(file, 0o600);
25
+ check(file, 0o600, false);
22
26
  for (const dir of dirs)
23
- check(dir, 0o700);
27
+ check(dir, 0o700, true);
24
28
  return { checked: true, ok: problems.length === 0, problems };
25
29
  };
26
30
  /** A SQLite database in write-ahead mode keeps its newest pages beside it. */
@@ -1,4 +1,4 @@
1
- import { existsSync, readFileSync } from "node:fs";
1
+ import { existsSync } from "node:fs";
2
2
  import { CliError, configFilePath, resolvePaths, saveConfigFile } from "@wirecat/cli-base";
3
3
  import * as v from "valibot";
4
4
  import { AI_ENTRIES, resolveAISettings } from "../analysis/settings.js";
@@ -7,7 +7,7 @@ import { envName, readOnlyLockOf } from "../ports/app.js";
7
7
  import { assertOverridesTighten, CEILING_KEY, LEVELS, layerPermissions, permissionOverrides, RESOURCES, } from "../sends/permissions.js";
8
8
  import { storePath } from "../store/path.js";
9
9
  import { sharedConfigPath } from "../store/shared-config.js";
10
- import { checkConfigText, issueMessage, parseConfigText, publicIssue, savedPermissionKeys, schemaIssues, } from "./config-issues.js";
10
+ import { checkConfigText, issueMessage, readConfigFile, readConfigText, savedPermissionKeys, schemaIssues, settingPathOf, withoutPath, } from "./config-issues.js";
11
11
  import { DEFAULT_CONFIG, ensureDefaultConfig } from "./default-config.js";
12
12
  import { profilesHere } from "./messenger/accounts.js";
13
13
  import { usableProfileName } from "./profile.js";
@@ -144,27 +144,14 @@ export const settingsFor = (app, extension = {}) => {
144
144
  const configPathFor = ({ env = process.env, configDir }) => configFilePath(configDir ?? resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).config);
145
145
  const readSchema = extension.schema ?? schema;
146
146
  const context = (file) => ({ file, tool: app.command });
147
- /** The file as written, `undefined` when there is none, or the issue that says it is not JSON. */
148
- const readRaw = (path) => {
149
- let text;
150
- try {
151
- text = readFileSync(path, "utf8");
152
- }
153
- catch {
154
- return { raw: undefined };
155
- }
156
- return parseConfigText(text, path);
157
- };
158
147
  /** The file with every problem found; what loads is the file without the settings they name. */
159
148
  const loadConfig = (path) => {
160
- let text;
161
- try {
162
- text = readFileSync(path, "utf8");
163
- }
164
- catch {
149
+ const read = readConfigText(path);
150
+ if ("issue" in read)
151
+ return { config: { profiles: {} }, issues: [read.issue] };
152
+ if (read.text === undefined)
165
153
  return { config: { profiles: {} }, issues: [] };
166
- }
167
- const { config, issues } = checkConfigText(text, { file: path, tool: app.command, schema: readSchema });
154
+ const { config, issues } = checkConfigText(read.text, { file: path, tool: app.command, schema: readSchema });
168
155
  return { config: (config ?? { profiles: {} }), issues };
169
156
  };
170
157
  /**
@@ -365,9 +352,9 @@ export const settingsFor = (app, extension = {}) => {
365
352
  const level = name === "permissions" && rest.length > 0 ? rest.join(".") : undefined;
366
353
  const modelField = /^models\.([a-z][a-z0-9-]*)\.(provider|model|base_url)$/.exec(setting);
367
354
  const known = allSettings.includes(setting) || level !== undefined || modelField !== null;
368
- const read = readRaw(path);
355
+ const read = readConfigFile(path);
369
356
  if ("issue" in read)
370
- throw new CliError("configuration_error", issueMessage([publicIssue(read.issue)]));
357
+ throw new CliError("configuration_error", issueMessage([read.issue]));
371
358
  const raw = read.raw === undefined ? {} : read.raw;
372
359
  if (!isScope(raw))
373
360
  throw new CliError("configuration_error", `${path}: the file has to be an object, in braces`);
@@ -375,7 +362,7 @@ export const settingsFor = (app, extension = {}) => {
375
362
  ? []
376
363
  : [...(kind === undefined ? [] : [kind]), ...(profile === undefined ? ["defaults"] : ["profiles", profile])];
377
364
  const keyPath = root
378
- ? setting.split(".")
365
+ ? settingPathOf(setting)
379
366
  : level !== undefined
380
367
  ? ["permissions", level]
381
368
  : modelField
@@ -388,9 +375,7 @@ export const settingsFor = (app, extension = {}) => {
388
375
  throw new CliError("validation_error", `${setting} has no problem to remove — name the profile, or add --defaults, to unset a setting`);
389
376
  if (!known && valueAt(raw, at) === undefined)
390
377
  throw new CliError("validation_error", `no setting called "${setting}" — one of: ${allSettings.join(", ")}`);
391
- const changed = structuredClone(raw);
392
- removeAt(changed, at);
393
- saveConfigFile(path, changed);
378
+ saveConfigFile(path, withoutPath(raw, at).config);
394
379
  return null;
395
380
  }
396
381
  if (!known)
@@ -417,7 +402,7 @@ export const settingsFor = (app, extension = {}) => {
417
402
  return { resolveSettings, configuredProfiles, changeSetting, allSettings, defaultsOnlyKeys, schema };
418
403
  };
419
404
  const isScope = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
420
- const valueAt = (node, path) => path.reduce((at, key) => (isScope(at) ? at[key] : undefined), node);
405
+ const valueAt = (node, path) => path.reduce((at, key) => (isScope(at) || Array.isArray(at) ? at[key] : undefined), node);
421
406
  const setAt = (node, path, value) => {
422
407
  let at = node;
423
408
  for (const key of path.slice(0, -1)) {
@@ -427,22 +412,6 @@ const setAt = (node, path, value) => {
427
412
  }
428
413
  at[path.at(-1)] = value;
429
414
  };
430
- /** Removes the value and every section it leaves empty, so an unset leaves no `{}` behind. */
431
- const removeAt = (node, path) => {
432
- const [key, ...rest] = path;
433
- if (key === undefined)
434
- return;
435
- if (rest.length === 0) {
436
- delete node[key];
437
- return;
438
- }
439
- const child = node[key];
440
- if (!isScope(child))
441
- return;
442
- removeAt(child, rest);
443
- if (Object.keys(child).length === 0)
444
- delete node[key];
445
- };
446
415
  /** Every profile the file names, in any section. */
447
416
  const namedProfiles = (config) => [
448
417
  ...new Set([
@@ -38,7 +38,6 @@ export declare const meetingTools: ({
38
38
  max_read_bytes?: undefined;
39
39
  cursor?: undefined;
40
40
  } | {
41
- limit?: undefined;
42
41
  event_id?: undefined;
43
42
  series_id?: undefined;
44
43
  page?: undefined;
@@ -54,11 +53,11 @@ export declare const meetingTools: ({
54
53
  format?: undefined;
55
54
  transcript_id?: undefined;
56
55
  query?: undefined;
56
+ limit?: undefined;
57
57
  scan_limit?: undefined;
58
58
  max_read_bytes?: undefined;
59
59
  cursor?: undefined;
60
60
  } | {
61
- limit?: undefined;
62
61
  event_id?: undefined;
63
62
  series_id?: undefined;
64
63
  page?: undefined;
@@ -76,11 +75,11 @@ export declare const meetingTools: ({
76
75
  format?: undefined;
77
76
  transcript_id?: undefined;
78
77
  query?: undefined;
78
+ limit?: undefined;
79
79
  scan_limit?: undefined;
80
80
  max_read_bytes?: undefined;
81
81
  cursor?: undefined;
82
82
  } | {
83
- limit?: undefined;
84
83
  event_id?: undefined;
85
84
  series_id?: undefined;
86
85
  page?: undefined;
@@ -102,6 +101,7 @@ export declare const meetingTools: ({
102
101
  minimum: number;
103
102
  };
104
103
  query?: undefined;
104
+ limit?: undefined;
105
105
  scan_limit?: undefined;
106
106
  max_read_bytes?: undefined;
107
107
  cursor?: undefined;
@@ -188,7 +188,6 @@ export declare const meetingTools: ({
188
188
  max_read_bytes?: undefined;
189
189
  cursor?: undefined;
190
190
  } | {
191
- limit?: undefined;
192
191
  event_id?: undefined;
193
192
  series_id?: undefined;
194
193
  page?: undefined;
@@ -204,11 +203,11 @@ export declare const meetingTools: ({
204
203
  format?: undefined;
205
204
  transcript_id?: undefined;
206
205
  query?: undefined;
206
+ limit?: undefined;
207
207
  scan_limit?: undefined;
208
208
  max_read_bytes?: undefined;
209
209
  cursor?: undefined;
210
210
  } | {
211
- limit?: undefined;
212
211
  event_id?: undefined;
213
212
  series_id?: undefined;
214
213
  page?: undefined;
@@ -226,11 +225,11 @@ export declare const meetingTools: ({
226
225
  format?: undefined;
227
226
  transcript_id?: undefined;
228
227
  query?: undefined;
228
+ limit?: undefined;
229
229
  scan_limit?: undefined;
230
230
  max_read_bytes?: undefined;
231
231
  cursor?: undefined;
232
232
  } | {
233
- limit?: undefined;
234
233
  event_id?: undefined;
235
234
  series_id?: undefined;
236
235
  page?: undefined;
@@ -252,6 +251,7 @@ export declare const meetingTools: ({
252
251
  minimum: number;
253
252
  };
254
253
  query?: undefined;
254
+ limit?: undefined;
255
255
  scan_limit?: undefined;
256
256
  max_read_bytes?: undefined;
257
257
  cursor?: undefined;
@@ -338,7 +338,6 @@ export declare const meetingTools: ({
338
338
  max_read_bytes?: undefined;
339
339
  cursor?: undefined;
340
340
  } | {
341
- limit?: undefined;
342
341
  event_id?: undefined;
343
342
  series_id?: undefined;
344
343
  page?: undefined;
@@ -354,11 +353,11 @@ export declare const meetingTools: ({
354
353
  format?: undefined;
355
354
  transcript_id?: undefined;
356
355
  query?: undefined;
356
+ limit?: undefined;
357
357
  scan_limit?: undefined;
358
358
  max_read_bytes?: undefined;
359
359
  cursor?: undefined;
360
360
  } | {
361
- limit?: undefined;
362
361
  event_id?: undefined;
363
362
  series_id?: undefined;
364
363
  page?: undefined;
@@ -376,11 +375,11 @@ export declare const meetingTools: ({
376
375
  format?: undefined;
377
376
  transcript_id?: undefined;
378
377
  query?: undefined;
378
+ limit?: undefined;
379
379
  scan_limit?: undefined;
380
380
  max_read_bytes?: undefined;
381
381
  cursor?: undefined;
382
382
  } | {
383
- limit?: undefined;
384
383
  event_id?: undefined;
385
384
  series_id?: undefined;
386
385
  page?: undefined;
@@ -402,6 +401,7 @@ export declare const meetingTools: ({
402
401
  minimum: number;
403
402
  };
404
403
  query?: undefined;
404
+ limit?: undefined;
405
405
  scan_limit?: undefined;
406
406
  max_read_bytes?: undefined;
407
407
  cursor?: undefined;
@@ -488,7 +488,6 @@ export declare const meetingTools: ({
488
488
  max_read_bytes?: undefined;
489
489
  cursor?: undefined;
490
490
  } | {
491
- limit?: undefined;
492
491
  event_id?: undefined;
493
492
  series_id?: undefined;
494
493
  page?: undefined;
@@ -504,11 +503,11 @@ export declare const meetingTools: ({
504
503
  format?: undefined;
505
504
  transcript_id?: undefined;
506
505
  query?: undefined;
506
+ limit?: undefined;
507
507
  scan_limit?: undefined;
508
508
  max_read_bytes?: undefined;
509
509
  cursor?: undefined;
510
510
  } | {
511
- limit?: undefined;
512
511
  event_id?: undefined;
513
512
  series_id?: undefined;
514
513
  page?: undefined;
@@ -526,11 +525,11 @@ export declare const meetingTools: ({
526
525
  format?: undefined;
527
526
  transcript_id?: undefined;
528
527
  query?: undefined;
528
+ limit?: undefined;
529
529
  scan_limit?: undefined;
530
530
  max_read_bytes?: undefined;
531
531
  cursor?: undefined;
532
532
  } | {
533
- limit?: undefined;
534
533
  event_id?: undefined;
535
534
  series_id?: undefined;
536
535
  page?: undefined;
@@ -552,6 +551,7 @@ export declare const meetingTools: ({
552
551
  minimum: number;
553
552
  };
554
553
  query?: undefined;
554
+ limit?: undefined;
555
555
  scan_limit?: undefined;
556
556
  max_read_bytes?: undefined;
557
557
  cursor?: undefined;
@@ -638,7 +638,6 @@ export declare const meetingTools: ({
638
638
  max_read_bytes?: undefined;
639
639
  cursor?: undefined;
640
640
  } | {
641
- limit?: undefined;
642
641
  event_id?: undefined;
643
642
  series_id?: undefined;
644
643
  page?: undefined;
@@ -654,11 +653,11 @@ export declare const meetingTools: ({
654
653
  format?: undefined;
655
654
  transcript_id?: undefined;
656
655
  query?: undefined;
656
+ limit?: undefined;
657
657
  scan_limit?: undefined;
658
658
  max_read_bytes?: undefined;
659
659
  cursor?: undefined;
660
660
  } | {
661
- limit?: undefined;
662
661
  event_id?: undefined;
663
662
  series_id?: undefined;
664
663
  page?: undefined;
@@ -676,11 +675,11 @@ export declare const meetingTools: ({
676
675
  format?: undefined;
677
676
  transcript_id?: undefined;
678
677
  query?: undefined;
678
+ limit?: undefined;
679
679
  scan_limit?: undefined;
680
680
  max_read_bytes?: undefined;
681
681
  cursor?: undefined;
682
682
  } | {
683
- limit?: undefined;
684
683
  event_id?: undefined;
685
684
  series_id?: undefined;
686
685
  page?: undefined;
@@ -702,6 +701,7 @@ export declare const meetingTools: ({
702
701
  minimum: number;
703
702
  };
704
703
  query?: undefined;
704
+ limit?: undefined;
705
705
  scan_limit?: undefined;
706
706
  max_read_bytes?: undefined;
707
707
  cursor?: undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.429.0",
3
+ "version": "0.431.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",