@rollrook-ai/cookbooks 0.0.0-stage → 0.6.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/dist/cli.js ADDED
@@ -0,0 +1,792 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { parseArgs } from "node:util";
4
+ import { RunaCcCliChecker } from "./checker.js";
5
+ import { CookbookSkills } from "./cookbook_skills.js";
6
+ import { CookbooksError, ManifestError, NotFoundError, UsageError } from "./errors.js";
7
+ import { Git } from "./git.js";
8
+ import { GitHubAuthFinder, GitHubClient, Publisher } from "./github.js";
9
+ import { Installer } from "./installer.js";
10
+ import { LockFile } from "./lock.js";
11
+ import { Manifest } from "./manifest.js";
12
+ import { Scaffold } from "./scaffold.js";
13
+ import { Scope } from "./scope.js";
14
+ import { NpxSkillsRunner } from "./skills_runner.js";
15
+ import { SourceParser } from "./source.js";
16
+ import { Templates } from "./template.js";
17
+ /** The `cookbooks` command line. */
18
+ export class Cli {
19
+ /** The package this command line is published as. */
20
+ static PACKAGE_NAME = "@rollrook-ai/cookbooks";
21
+ /** Where package.json lies from this file, in both dist/ and build/src/. */
22
+ static LIST_PACKAGE_PATHS = ["../package.json", "../../package.json"];
23
+ /** This package's version, as its package.json gives it, so a release never reports another. */
24
+ static VERSION = Cli._package_version();
25
+ /** Exit code of a command that succeeded. */
26
+ static EXIT_OK = 0;
27
+ /** Exit code of a command that failed, or of a check that refused the cookbook. */
28
+ static EXIT_FAILED = 1;
29
+ /** Exit code of a check no compiler could run. */
30
+ static EXIT_CHECKER_UNAVAILABLE = 2;
31
+ /** The environment variable that points `owner/repo` sources at another GitHub, for mirrors and tests. */
32
+ static ENV_GITHUB_BASE = "COOKBOOKS_GITHUB_BASE";
33
+ /** The environment variable that points publishing at another GitHub API, for tests and GitHub Enterprise. */
34
+ static ENV_GITHUB_API = "COOKBOOKS_GITHUB_API";
35
+ static _HELP = [
36
+ "Usage: cookbooks <command> [options]",
37
+ "",
38
+ "Manage Cookbooks:",
39
+ " add <source> Install a cookbook with its dependencies and skills (alias: a)",
40
+ " e.g. rollrook-ai/gwatch-cookbook",
41
+ " rollrook-ai/cookbooks/gwatch@v0.1.0",
42
+ " https://github.com/rollrook-ai/gwatch-cookbook.git@v0.1.0",
43
+ " ./my-cookbook",
44
+ " A repository root from git is installed as a git clone;",
45
+ " a folder inside a repository, or a local directory, as a copy",
46
+ " remove <names...> Remove installed cookbooks (alias: rm)",
47
+ " list, ls List installed cookbooks",
48
+ " update [name[@ref]] Update cookbooks to the newest commit of their ref (alias: upgrade)",
49
+ " info <name> Show one installed cookbook",
50
+ "",
51
+ "Author:",
52
+ " init [dir] Create a cookbook: cookbook.toml, main.runa, skills/, README.md",
53
+ " init <dir> --template <template>",
54
+ " Create a cookbook from a template, in a new git repository",
55
+ " templates List the templates that come with cookbooks",
56
+ " owners List the GitHub user and organizations a cookbook can be published under",
57
+ " publish [dir] Make the cookbook's GitHub repository if needed, point origin at it and push",
58
+ " skill add <source> Pin a skill's repository as a submodule under skills/",
59
+ " skill remove <repo> Remove a skill submodule no module declares (alias: skill rm)",
60
+ " check [dir] Check a cookbook's manifest and compile it with runa-cc",
61
+ "",
62
+ "Add Options:",
63
+ " -g, --global Install globally (~/.cookbooks) instead of in the project (./.cookbooks)",
64
+ " -y, --yes Accepted for symmetry with skills; cookbooks never prompts",
65
+ " --link Link a local directory into place instead of copying it",
66
+ " --force Replace an installed clone that has local changes or commits",
67
+ "",
68
+ "List, Update and Info Options:",
69
+ " -g, --global Global cookbooks only",
70
+ " -p, --project Project cookbooks only",
71
+ " --force Update: discard a clone's uncommitted changes and diverged commits",
72
+ "",
73
+ "Remove Options:",
74
+ " -g, --global Remove from global scope",
75
+ " --force Remove a cookbook others depend on, or a clone with local work",
76
+ "",
77
+ "Init Options:",
78
+ " --name <name> The cookbook's name (default: the directory's name)",
79
+ " --template <t> A built-in template's name, owner/repo, a git url or a directory",
80
+ " --description <d> What the cookbook is for, written to cookbook.toml",
81
+ "",
82
+ "Publish Options:",
83
+ " --owner <login> The user or organization to publish under (default: the signed-in user)",
84
+ " --repo <name> The repository's name (default: the cookbook's name)",
85
+ " --private Make a new repository private",
86
+ " --force Point an origin that names another repository at this one",
87
+ "",
88
+ "Skill Options:",
89
+ " --path <folder> The skill's folder inside its repository (default: the root)",
90
+ " --dir <cookbook> The cookbook to change (default: the current directory)",
91
+ "",
92
+ "Options:",
93
+ " --json Output results as JSON (machine-readable)",
94
+ " --help, -h Show this help message",
95
+ " --version, -v Show version number",
96
+ "",
97
+ "Examples:",
98
+ " $ cookbooks add rollrook-ai/gwatch-cookbook",
99
+ " $ cookbooks add rollrook-ai/gwatch-cookbook@v0.2.0 -g",
100
+ " $ cookbooks add ~/src/my-cookbook --link",
101
+ " $ cookbooks ls --json",
102
+ " $ cookbooks update gwatch-cuda-auto-optimization",
103
+ " $ cookbooks rm gwatch-cuda-auto-optimization",
104
+ " $ cookbooks init my-cookbook",
105
+ " $ cookbooks init my-cookbook --template bye-world --description \"Tidy a repository's issues.\"",
106
+ " $ cookbooks publish my-cookbook --owner rollrook-ai --private",
107
+ " $ cookbooks skill add rollrook-ai/G-Watch@v1.0 --path skills/gwatch-cuda-pc-sampling",
108
+ " $ cookbooks check",
109
+ "",
110
+ ].join("\n");
111
+ _options;
112
+ _git;
113
+ _parser;
114
+ _skills_runner;
115
+ _checker;
116
+ /** @param options - the arguments, directories, environment, streams and injectable runners */
117
+ constructor(options) {
118
+ this._options = options;
119
+ this._git = new Git(options.env);
120
+ this._parser = new SourceParser({
121
+ cwd: options.cwd,
122
+ home: options.home,
123
+ github_base: options.env[Cli.ENV_GITHUB_BASE],
124
+ });
125
+ this._skills_runner = options.skills_runner ?? new NpxSkillsRunner(options.env);
126
+ this._checker = options.checker ?? new RunaCcCliChecker(options.env);
127
+ }
128
+ /**
129
+ * Run the command line.
130
+ *
131
+ * @returns the process exit code
132
+ */
133
+ async run() {
134
+ const is_json = this._options.list_argv.includes("--json");
135
+ const command = this._options.list_argv.find((arg) => !arg.startsWith("-")) ?? "";
136
+ try {
137
+ const result = await this._dispatch();
138
+ if (is_json) {
139
+ this._options.stdout.write(`${JSON.stringify({ ok: result.exit_code === Cli.EXIT_OK, ...result.map_json }, null, 2)}\n`);
140
+ }
141
+ else if (result.list_lines.length > 0) {
142
+ this._options.stdout.write(`${result.list_lines.join("\n")}\n`);
143
+ }
144
+ return result.exit_code;
145
+ }
146
+ catch (err) {
147
+ if (!(err instanceof CookbooksError)) {
148
+ throw err;
149
+ }
150
+ if (is_json) {
151
+ this._options.stdout.write(`${JSON.stringify({
152
+ ok: false,
153
+ command,
154
+ error: { code: err.code, message: err.message },
155
+ }, null, 2)}\n`);
156
+ }
157
+ else {
158
+ this._options.stderr.write(`error: ${err.message}\n`);
159
+ if (err instanceof UsageError) {
160
+ this._options.stderr.write("Run cookbooks --help for usage.\n");
161
+ }
162
+ }
163
+ return Cli.EXIT_FAILED;
164
+ }
165
+ }
166
+ async _dispatch() {
167
+ let parsed = undefined;
168
+ try {
169
+ parsed = Cli._parse(this._options.list_argv);
170
+ }
171
+ catch (err) {
172
+ if (err instanceof TypeError) {
173
+ throw new UsageError(err.message);
174
+ }
175
+ throw err;
176
+ }
177
+ const list_positionals = parsed.list_positionals;
178
+ const flags = parsed.flags;
179
+ if (parsed.is_version) {
180
+ return Cli._text({ list_lines: [Cli.VERSION], map_json: { command: "version", version: Cli.VERSION } });
181
+ }
182
+ const command = list_positionals[0];
183
+ if (parsed.is_help || command === undefined) {
184
+ return Cli._text({ list_lines: [Cli._HELP.trimEnd()], map_json: { command: "help", help: Cli._HELP } });
185
+ }
186
+ const list_args = list_positionals.slice(1);
187
+ switch (command) {
188
+ case "add":
189
+ case "a":
190
+ return this._add({ list_args, flags });
191
+ case "list":
192
+ case "ls":
193
+ return this._list(flags);
194
+ case "remove":
195
+ case "rm":
196
+ return this._remove({ list_args, flags });
197
+ case "update":
198
+ case "upgrade":
199
+ return this._update({ list_args, flags });
200
+ case "info":
201
+ return this._info({ list_args, flags });
202
+ case "init":
203
+ return flags.template === undefined
204
+ ? this._init({ list_args, flags })
205
+ : this._init_from_template({ list_args, flags, template: flags.template });
206
+ case "templates":
207
+ return Cli._templates();
208
+ case "owners":
209
+ return this._owners();
210
+ case "publish":
211
+ return this._publish({ list_args, flags });
212
+ case "check":
213
+ return this._check({ list_args, flags });
214
+ case "skill":
215
+ case "skills":
216
+ return this._skill({ list_args, flags });
217
+ default:
218
+ throw new UsageError(`unknown command: ${command}`);
219
+ }
220
+ }
221
+ static _parse(list_argv) {
222
+ const parsed = parseArgs({
223
+ args: [...list_argv],
224
+ allowPositionals: true,
225
+ strict: true,
226
+ options: {
227
+ json: { type: "boolean" },
228
+ global: { type: "boolean", short: "g" },
229
+ project: { type: "boolean", short: "p" },
230
+ yes: { type: "boolean", short: "y" },
231
+ force: { type: "boolean" },
232
+ link: { type: "boolean" },
233
+ name: { type: "string" },
234
+ path: { type: "string" },
235
+ dir: { type: "string" },
236
+ template: { type: "string" },
237
+ description: { type: "string" },
238
+ owner: { type: "string" },
239
+ repo: { type: "string" },
240
+ private: { type: "boolean" },
241
+ help: { type: "boolean", short: "h" },
242
+ version: { type: "boolean", short: "v" },
243
+ },
244
+ });
245
+ if (parsed.values.global === true && parsed.values.project === true) {
246
+ throw new UsageError("--global and --project cannot be combined");
247
+ }
248
+ return {
249
+ list_positionals: parsed.positionals,
250
+ flags: {
251
+ is_json: parsed.values.json === true,
252
+ is_global: parsed.values.global === true,
253
+ is_project: parsed.values.project === true,
254
+ is_forced: parsed.values.force === true,
255
+ is_linked: parsed.values.link === true,
256
+ name: parsed.values.name,
257
+ folder: parsed.values.path,
258
+ dir: parsed.values.dir,
259
+ template: parsed.values.template,
260
+ description: parsed.values.description,
261
+ owner: parsed.values.owner,
262
+ repo: parsed.values.repo,
263
+ is_private: parsed.values.private === true,
264
+ },
265
+ is_help: parsed.values.help === true,
266
+ is_version: parsed.values.version === true,
267
+ };
268
+ }
269
+ _scope(kind) {
270
+ return new Scope({
271
+ kind,
272
+ root: kind === "global" ? this._options.home : this._options.cwd,
273
+ });
274
+ }
275
+ _list_scope_kinds(flags) {
276
+ if (flags.is_global) {
277
+ return ["global"];
278
+ }
279
+ return flags.is_project ? ["project"] : ["project", "global"];
280
+ }
281
+ _installer(options) {
282
+ const sink = options.flags.is_json ? this._options.stderr : this._options.stdout;
283
+ return new Installer({
284
+ scope: this._scope(options.kind),
285
+ git: this._git,
286
+ skills_runner: this._skills_runner,
287
+ checker: this._checker,
288
+ parser: this._parser,
289
+ on_progress: (message) => sink.write(`${message}\n`),
290
+ });
291
+ }
292
+ async _add(options) {
293
+ const source_text = Cli._exactly_one({ list_args: options.list_args, what: "add <source>" });
294
+ const source = this._parser.parse(source_text);
295
+ if (options.flags.is_linked && source.type !== "local") {
296
+ throw new UsageError(`--link takes a directory on this machine, not ${source_text}`);
297
+ }
298
+ const kind = options.flags.is_global ? "global" : "project";
299
+ const list_outcomes = await this._installer({ kind, flags: options.flags }).add({
300
+ source,
301
+ is_linked: options.flags.is_linked,
302
+ is_forced: options.flags.is_forced,
303
+ });
304
+ const requested = list_outcomes[0];
305
+ if (requested === undefined) {
306
+ throw new ManifestError(`${source_text} is a cookbook already being installed`);
307
+ }
308
+ const list_skills = list_outcomes.flatMap((outcome) => outcome.list_skills_installed);
309
+ return Cli._text({
310
+ list_lines: [
311
+ `Done: ${requested.entry.name} ${requested.entry.version} in ${requested.entry.path} (${requested.entry.install})`,
312
+ ...(list_outcomes.length > 1
313
+ ? [`Dependencies: ${list_outcomes.slice(1).map((outcome) => `${outcome.entry.name} (${outcome.status})`).join(", ")}`]
314
+ : []),
315
+ ...(list_skills.length > 0 ? [`Skills: ${list_skills.join(", ")}`] : []),
316
+ ],
317
+ map_json: {
318
+ command: "add",
319
+ scope: kind,
320
+ cookbook: Cli._outcome_json(requested),
321
+ dependencies: list_outcomes.slice(1).map((outcome) => Cli._outcome_json(outcome)),
322
+ skills_installed: list_skills,
323
+ },
324
+ });
325
+ }
326
+ async _list(flags) {
327
+ const list_entries = [];
328
+ for (const kind of this._list_scope_kinds(flags)) {
329
+ const lock = LockFile.read(this._scope(kind).lock_path);
330
+ list_entries.push(...[...lock.map_entries.values()].sort((a, b) => a.name.localeCompare(b.name)));
331
+ }
332
+ const map_dirty = new Map();
333
+ for (const entry of list_entries) {
334
+ map_dirty.set(entry, await Installer.is_dirty({ entry, git: this._git }));
335
+ }
336
+ const list_lines = [];
337
+ if (list_entries.length === 0) {
338
+ list_lines.push("No cookbooks installed.");
339
+ }
340
+ for (const kind of this._list_scope_kinds(flags)) {
341
+ const list_scoped = list_entries.filter((entry) => entry.scope === kind);
342
+ if (list_scoped.length === 0) {
343
+ continue;
344
+ }
345
+ list_lines.push(kind === "global" ? "Global cookbooks" : "Project cookbooks");
346
+ for (const entry of list_scoped) {
347
+ const ref = entry.ref === undefined ? "" : `@${entry.ref}`;
348
+ const dependency = entry.is_direct ? "" : ` (dependency of ${entry.list_required_by.join(", ")})`;
349
+ list_lines.push(` ${entry.name} ${entry.version} ${entry.source}${ref} ${Installer.short_commit(entry.commit)}`
350
+ + ` ${Cli._install_text({ entry, is_dirty: map_dirty.get(entry) })}${dependency}`);
351
+ }
352
+ list_lines.push("");
353
+ }
354
+ return Cli._text({
355
+ list_lines: list_lines.length > 0 && list_lines[list_lines.length - 1] === "" ? list_lines.slice(0, -1) : list_lines,
356
+ map_json: {
357
+ command: "list",
358
+ cookbooks: list_entries.map((entry) => ({
359
+ ...LockFile.entry_to_wire(entry),
360
+ dirty: map_dirty.get(entry) ?? null,
361
+ })),
362
+ },
363
+ });
364
+ }
365
+ async _remove(options) {
366
+ if (options.list_args.length === 0) {
367
+ throw new UsageError("remove needs at least one cookbook name");
368
+ }
369
+ const kind = options.flags.is_global ? "global" : "project";
370
+ const installer = this._installer({ kind, flags: options.flags });
371
+ const list_removed = [];
372
+ const list_skills_removed = [];
373
+ for (const name of options.list_args) {
374
+ if (!installer.map_entries.has(name) && kind === "project") {
375
+ const global_lock = LockFile.read(this._scope("global").lock_path);
376
+ if (global_lock.map_entries.has(name)) {
377
+ throw new NotFoundError(`${name} is not installed in this project; it is global, remove it with -g`);
378
+ }
379
+ }
380
+ const outcome = await installer.remove({ name, is_forced: options.flags.is_forced });
381
+ list_removed.push(...outcome.list_removed);
382
+ list_skills_removed.push(...outcome.list_skills_removed);
383
+ }
384
+ return Cli._text({
385
+ list_lines: [
386
+ `Removed ${list_removed.map((entry) => entry.name).join(", ")}`,
387
+ ...(list_skills_removed.length > 0 ? [`Skills removed: ${list_skills_removed.join(", ")}`] : []),
388
+ ],
389
+ map_json: {
390
+ command: "remove",
391
+ scope: kind,
392
+ removed: list_removed.map((entry) => ({ name: entry.name, scope: entry.scope, path: entry.path })),
393
+ skills_removed: list_skills_removed,
394
+ },
395
+ });
396
+ }
397
+ async _update(options) {
398
+ if (options.list_args.length > 1) {
399
+ throw new UsageError("update takes at most one cookbook name");
400
+ }
401
+ const target = options.list_args[0];
402
+ const split = target === undefined ? { spec: undefined, ref: undefined } : SourceParser.split_ref(target);
403
+ const list_kinds = split.spec === undefined
404
+ ? this._list_scope_kinds(options.flags)
405
+ : [this._find_scope({ name: split.spec, flags: options.flags })];
406
+ const list_outcomes = [];
407
+ for (const kind of list_kinds) {
408
+ const installer = this._installer({ kind, flags: options.flags });
409
+ list_outcomes.push(...await installer.update({
410
+ name: split.spec,
411
+ ref: split.ref,
412
+ is_forced: options.flags.is_forced,
413
+ }));
414
+ }
415
+ const list_changed = list_outcomes.filter((outcome) => outcome.status !== "unchanged");
416
+ return Cli._text({
417
+ list_lines: list_outcomes.length === 0
418
+ ? ["No cookbooks installed."]
419
+ : [
420
+ list_changed.length === 0
421
+ ? "All cookbooks are up to date."
422
+ : `Updated ${list_changed.map((outcome) => outcome.entry.name).join(", ")}`,
423
+ ],
424
+ map_json: {
425
+ command: "update",
426
+ updates: list_outcomes.map((outcome) => ({
427
+ name: outcome.entry.name,
428
+ scope: outcome.entry.scope,
429
+ status: outcome.status,
430
+ install: outcome.entry.install,
431
+ ref: outcome.entry.ref ?? null,
432
+ from: outcome.previous_commit ?? null,
433
+ to: outcome.entry.commit ?? null,
434
+ skills_installed: outcome.list_skills_installed,
435
+ skills_removed: outcome.list_skills_removed,
436
+ })),
437
+ },
438
+ });
439
+ }
440
+ _find_scope(options) {
441
+ for (const kind of this._list_scope_kinds(options.flags)) {
442
+ if (LockFile.read(this._scope(kind).lock_path).map_entries.has(options.name)) {
443
+ return kind;
444
+ }
445
+ }
446
+ throw new NotFoundError(`${options.name} is not installed`);
447
+ }
448
+ async _info(options) {
449
+ const name = Cli._exactly_one({ list_args: options.list_args, what: "info <name>" });
450
+ const kind = this._find_scope({ name, flags: options.flags });
451
+ const entry = LockFile.read(this._scope(kind).lock_path).map_entries.get(name);
452
+ if (entry === undefined) {
453
+ throw new NotFoundError(`${name} is not installed`);
454
+ }
455
+ let manifest = undefined;
456
+ if (fs.existsSync(path.join(entry.path, Manifest.MANIFEST_FILE))) {
457
+ manifest = Manifest.read(entry.path);
458
+ }
459
+ const list_dependencies = manifest === undefined ? [] : [...manifest.map_dependencies.keys()];
460
+ const is_dirty = await Installer.is_dirty({ entry, git: this._git });
461
+ const list_lines = [
462
+ `${entry.name} ${entry.version}`,
463
+ ...(entry.description === "" ? [] : [` ${entry.description}`]),
464
+ ` Source: ${entry.source}${entry.ref === undefined ? "" : `@${entry.ref}`} (${entry.source_type})`,
465
+ ` Commit: ${entry.commit ?? "none"}`,
466
+ ` Install: ${Cli._install_text({ entry, is_dirty })}`,
467
+ ` Scope: ${entry.scope}`,
468
+ ` Path: ${entry.path}`,
469
+ ` Entry: ${manifest?.entry ?? Manifest.ENTRY_DEFAULT}${manifest === undefined ? " (directory missing)" : ""}`,
470
+ ` Dependencies: ${list_dependencies.length === 0 ? "none" : list_dependencies.join(", ")}`,
471
+ ...(entry.is_direct ? [] : [` Required by: ${entry.list_required_by.join(", ")}`]),
472
+ ` Skills: ${entry.list_skills.length === 0 ? "none" : ""}`,
473
+ ...entry.list_skills.map((skill) => ` ${skill.installed_name} ${skill.folder} ${Installer.short_commit(skill.commit)}`),
474
+ ` Installed: ${entry.installed_at}`,
475
+ ` Updated: ${entry.updated_at}`,
476
+ ];
477
+ return Cli._text({
478
+ list_lines: list_lines.map((line) => line.trimEnd()),
479
+ map_json: {
480
+ command: "info",
481
+ cookbook: {
482
+ ...LockFile.entry_to_wire(entry),
483
+ dirty: is_dirty ?? null,
484
+ entry: manifest?.entry ?? null,
485
+ dependencies: list_dependencies,
486
+ is_present: manifest !== undefined,
487
+ },
488
+ },
489
+ });
490
+ }
491
+ _init(options) {
492
+ if (options.list_args.length > 1) {
493
+ throw new UsageError("init takes at most one directory");
494
+ }
495
+ const dir = path.resolve(this._options.cwd, options.list_args[0] ?? ".");
496
+ const outcome = Scaffold.init({
497
+ dir,
498
+ name: options.flags.name,
499
+ description: options.flags.description,
500
+ });
501
+ return Cli._text({
502
+ list_lines: [
503
+ `Created cookbook ${outcome.name} in ${outcome.dir}`,
504
+ ...outcome.list_files.map((file) => ` ${file}`),
505
+ ],
506
+ map_json: {
507
+ command: "init",
508
+ name: outcome.name,
509
+ dir: outcome.dir,
510
+ files: outcome.list_files,
511
+ },
512
+ });
513
+ }
514
+ async _init_from_template(options) {
515
+ const dir_arg = Cli._exactly_one({ list_args: options.list_args, what: "init <dir> --template <template>" });
516
+ const outcome = await new Templates({ git: this._git, parser: this._parser }).init({
517
+ dir: path.resolve(this._options.cwd, dir_arg),
518
+ name: options.flags.name,
519
+ description: options.flags.description ?? "",
520
+ template: options.template,
521
+ });
522
+ return Cli._text({
523
+ list_lines: [
524
+ `Created cookbook ${outcome.name} in ${outcome.dir} from ${outcome.template_name ?? outcome.template_source ?? options.template}`,
525
+ ...outcome.list_files.map((file) => ` ${file}`),
526
+ ...outcome.list_submodules.map((submodule) => ` ${submodule.path} at ${Installer.short_commit(submodule.commit)}`),
527
+ ` Committed ${Installer.short_commit(outcome.commit)} on ${Templates.BRANCH_INITIAL}`,
528
+ ],
529
+ map_json: {
530
+ command: "init",
531
+ name: outcome.name,
532
+ dir: outcome.dir,
533
+ description: outcome.description,
534
+ files: outcome.list_files,
535
+ template: {
536
+ name: outcome.template_name ?? null,
537
+ source: outcome.template_source ?? null,
538
+ commit: outcome.template_commit ?? null,
539
+ },
540
+ submodules: outcome.list_submodules,
541
+ branch: Templates.BRANCH_INITIAL,
542
+ commit: outcome.commit,
543
+ },
544
+ });
545
+ }
546
+ static _templates() {
547
+ return Cli._text({
548
+ list_lines: Templates.LIST_BUILT_IN.map((template) => (` ${template.name}${template.source === undefined ? "" : ` (${template.source})`}\n ${template.description}`)),
549
+ map_json: {
550
+ command: "templates",
551
+ templates: Templates.LIST_BUILT_IN.map((template) => ({
552
+ name: template.name,
553
+ title: template.title,
554
+ description: template.description,
555
+ source: template.source ?? null,
556
+ })),
557
+ },
558
+ });
559
+ }
560
+ async _github() {
561
+ const auth = await new GitHubAuthFinder({ env: this._options.env, home: this._options.home }).find();
562
+ return {
563
+ auth,
564
+ client: new GitHubClient({ auth, api_base: this._options.env[Cli.ENV_GITHUB_API] }),
565
+ };
566
+ }
567
+ async _owners() {
568
+ const github = await this._github();
569
+ const list_owners = await github.client.owners();
570
+ const login = list_owners[0]?.login ?? "";
571
+ return Cli._text({
572
+ list_lines: [
573
+ `Signed in to GitHub as ${login}, through ${GitHubClient.source_text(github.auth.source)}`,
574
+ ...list_owners.map((owner) => (` ${owner.login} ${owner.kind === "user" ? "you" : "organization"}${owner.name === undefined ? "" : ` ${owner.name}`}`)),
575
+ ],
576
+ map_json: {
577
+ command: "owners",
578
+ auth: { source: github.auth.source, login },
579
+ owners: list_owners.map((owner) => ({
580
+ login: owner.login,
581
+ kind: owner.kind,
582
+ name: owner.name ?? null,
583
+ avatar_url: owner.avatar_url ?? null,
584
+ })),
585
+ },
586
+ });
587
+ }
588
+ async _publish(options) {
589
+ if (options.list_args.length > 1) {
590
+ throw new UsageError("publish takes at most one directory");
591
+ }
592
+ const dir = path.resolve(this._options.cwd, options.list_args[0] ?? ".");
593
+ Manifest.read(dir);
594
+ const github = await this._github();
595
+ const outcome = await new Publisher({ git: this._git, client: github.client, auth: github.auth }).publish({
596
+ dir,
597
+ owner: options.flags.owner,
598
+ name: options.flags.repo,
599
+ is_private: options.flags.is_private,
600
+ is_forced: options.flags.is_forced,
601
+ });
602
+ const visibility = outcome.repository.is_private ? " (private)" : "";
603
+ return Cli._text({
604
+ list_lines: [
605
+ `${outcome.is_created ? "Created" : "Pushed to"} ${outcome.repository.full_name}${visibility}: ${outcome.repository.html_url}`,
606
+ ` Pushed ${outcome.branch} at ${Installer.short_commit(outcome.commit)}${outcome.is_origin_set ? "; origin points there" : ""}`,
607
+ ...(outcome.is_dirty ? [" warning: uncommitted changes were not pushed"] : []),
608
+ ],
609
+ map_json: {
610
+ command: "publish",
611
+ dir,
612
+ auth: { source: github.auth.source, login: outcome.login },
613
+ repository: {
614
+ owner: outcome.repository.owner,
615
+ name: outcome.repository.name,
616
+ full_name: outcome.repository.full_name,
617
+ html_url: outcome.repository.html_url,
618
+ clone_url: outcome.repository.clone_url,
619
+ private: outcome.repository.is_private,
620
+ created: outcome.is_created,
621
+ },
622
+ origin_set: outcome.is_origin_set,
623
+ branch: outcome.branch,
624
+ commit: outcome.commit,
625
+ dirty: outcome.is_dirty,
626
+ },
627
+ });
628
+ }
629
+ async _skill(options) {
630
+ const action = options.list_args[0];
631
+ const list_rest = options.list_args.slice(1);
632
+ const cookbook_dir = path.resolve(this._options.cwd, options.flags.dir ?? ".");
633
+ const cookbook_skills = new CookbookSkills({ git: this._git, checker: this._checker });
634
+ if (action === "add") {
635
+ const source = this._parser.parse(Cli._exactly_one({ list_args: list_rest, what: "skill add <source>" }));
636
+ const outcome = await cookbook_skills.add({
637
+ cookbook_dir,
638
+ source,
639
+ folder: options.flags.folder,
640
+ });
641
+ return Cli._text({
642
+ list_lines: [
643
+ `Added skill ${outcome.name} in ${outcome.folder}`,
644
+ ` Submodule ${outcome.submodule} at ${Installer.short_commit(outcome.commit)}${outcome.ref === undefined ? "" : ` (${outcome.ref})`}`,
645
+ ` Declare it in a module at the cookbook's root: ${CookbookSkills.declaration(outcome)}`,
646
+ ],
647
+ map_json: {
648
+ command: "skill add",
649
+ skill: {
650
+ name: outcome.name,
651
+ folder: outcome.folder,
652
+ submodule: outcome.submodule,
653
+ url: outcome.url,
654
+ ref: outcome.ref ?? null,
655
+ commit: outcome.commit,
656
+ },
657
+ },
658
+ });
659
+ }
660
+ if (action === "remove" || action === "rm") {
661
+ const submodule = Cli._exactly_one({ list_args: list_rest, what: "skill remove <skills/repo>" });
662
+ const outcome = await cookbook_skills.remove({ cookbook_dir, submodule });
663
+ const list_warnings = outcome.unchecked_reason === undefined
664
+ ? []
665
+ : [`did not check that no module declares a skill in ${outcome.submodule}: ${outcome.unchecked_reason}`];
666
+ return Cli._text({
667
+ list_lines: [
668
+ `Removed submodule ${outcome.submodule}`,
669
+ ...list_warnings.map((warning) => `warning: ${warning}`),
670
+ ],
671
+ map_json: {
672
+ command: "skill remove",
673
+ skill: { submodule: outcome.submodule },
674
+ warnings: list_warnings,
675
+ },
676
+ });
677
+ }
678
+ throw new UsageError("skill takes add <source> or remove <skills/repo>");
679
+ }
680
+ async _check(options) {
681
+ if (options.list_args.length > 1) {
682
+ throw new UsageError("check takes at most one directory");
683
+ }
684
+ const dir = path.resolve(this._options.cwd, options.list_args[0] ?? ".");
685
+ const manifest = Manifest.read(dir);
686
+ const list_problems = this._manifest_problems({ dir, manifest });
687
+ const result = await this._checker.check(dir);
688
+ const has_errors = list_problems.some((problem) => problem.severity === "error");
689
+ let status = result.status;
690
+ if (has_errors) {
691
+ status = "refused";
692
+ }
693
+ const exit_code = status === "ok"
694
+ ? Cli.EXIT_OK
695
+ : status === "refused" ? Cli.EXIT_FAILED : Cli.EXIT_CHECKER_UNAVAILABLE;
696
+ return {
697
+ exit_code,
698
+ list_lines: [
699
+ ...list_problems.map((problem) => `${problem.severity}: ${problem.message}`),
700
+ ...Cli._check_lines(result),
701
+ status === "ok"
702
+ ? `${manifest.name} checks clean`
703
+ : status === "refused"
704
+ ? `${manifest.name} is refused`
705
+ : `${manifest.name}: manifest checked; not compiled (checker unavailable)`,
706
+ ],
707
+ map_json: {
708
+ command: "check",
709
+ status,
710
+ dir,
711
+ cookbook: { name: manifest.name, version: manifest.version, entry: manifest.entry },
712
+ manifest_problems: list_problems,
713
+ compiler: result.status === "unavailable"
714
+ ? { status: result.status, checker: result.checker, reason: result.reason }
715
+ : { status: result.status, checker: result.checker, diagnostics: result.list_diagnostics },
716
+ },
717
+ };
718
+ }
719
+ _manifest_problems(options) {
720
+ const list_problems = options.manifest.list_warnings
721
+ .map((message) => ({ severity: "warning", message }));
722
+ if (!fs.existsSync(path.join(options.dir, options.manifest.entry))) {
723
+ list_problems.push({ severity: "error", message: `entry ${options.manifest.entry} does not exist` });
724
+ }
725
+ for (const dependency_name of options.manifest.map_dependencies.keys()) {
726
+ const list_candidates = [
727
+ path.join(options.dir, Scope.COOKBOOKS_DIR, dependency_name),
728
+ path.join(this._options.home, Scope.COOKBOOKS_DIR, dependency_name),
729
+ ];
730
+ if (!list_candidates.some((candidate) => fs.existsSync(path.join(candidate, Manifest.MANIFEST_FILE)))) {
731
+ list_problems.push({
732
+ severity: "warning",
733
+ message: `dependency ${dependency_name} is not installed in .cookbooks or ~/.cookbooks`,
734
+ });
735
+ }
736
+ }
737
+ return list_problems;
738
+ }
739
+ static _check_lines(result) {
740
+ if (result.status === "unavailable") {
741
+ return [`warning: cannot compile-check: ${result.reason}`];
742
+ }
743
+ return result.list_diagnostics.map((diagnostic) => {
744
+ const location = diagnostic.file === undefined
745
+ ? ""
746
+ : `${diagnostic.file}${diagnostic.line === undefined ? "" : `:${diagnostic.line}:${diagnostic.column ?? 1}`}: `;
747
+ return `${location}${diagnostic.severity} ${diagnostic.code}: ${diagnostic.message}`;
748
+ });
749
+ }
750
+ static _install_text(options) {
751
+ if (options.entry.install === "link") {
752
+ return `link to ${options.entry.url}`;
753
+ }
754
+ return options.is_dirty === true ? `${options.entry.install}, uncommitted changes` : options.entry.install;
755
+ }
756
+ static _outcome_json(outcome) {
757
+ return {
758
+ ...LockFile.entry_to_wire(outcome.entry),
759
+ status: outcome.status,
760
+ skills_installed: outcome.list_skills_installed,
761
+ };
762
+ }
763
+ static _exactly_one(options) {
764
+ const first = options.list_args[0];
765
+ if (first === undefined || options.list_args.length > 1) {
766
+ throw new UsageError(`usage: cookbooks ${options.what}`);
767
+ }
768
+ return first;
769
+ }
770
+ static _text(options) {
771
+ return {
772
+ map_json: options.map_json,
773
+ list_lines: options.list_lines,
774
+ exit_code: Cli.EXIT_OK,
775
+ };
776
+ }
777
+ /** Read this package's version from its package.json. */
778
+ static _package_version() {
779
+ const here = path.dirname(new URL(import.meta.url).pathname);
780
+ for (const relative of Cli.LIST_PACKAGE_PATHS) {
781
+ const candidate = path.join(here, relative);
782
+ if (!fs.existsSync(candidate)) {
783
+ continue;
784
+ }
785
+ const parsed = JSON.parse(fs.readFileSync(candidate, "utf8"));
786
+ if (typeof parsed === "object" && parsed !== null && "name" in parsed && "version" in parsed && parsed.name === Cli.PACKAGE_NAME && typeof parsed.version === "string") {
787
+ return parsed.version;
788
+ }
789
+ }
790
+ return "unknown";
791
+ }
792
+ }