barndog 0.1.1 → 0.2.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.
Files changed (173) hide show
  1. package/README.md +8 -7
  2. package/dist/cli.js +11 -7
  3. package/dist/commands/add.js +33 -21
  4. package/dist/commands/arguments.js +12 -0
  5. package/dist/commands/asset-install.js +160 -0
  6. package/dist/commands/asset-list.js +121 -0
  7. package/dist/commands/asset-share.js +94 -0
  8. package/dist/commands/auth.js +4 -0
  9. package/dist/commands/availability.js +54 -26
  10. package/dist/commands/capabilities.js +71 -415
  11. package/dist/commands/collaboration.js +194 -110
  12. package/dist/commands/environment.js +18 -411
  13. package/dist/commands/github.js +200 -0
  14. package/dist/commands/helpers.js +39 -0
  15. package/dist/commands/hooks.js +87 -0
  16. package/dist/commands/init.js +4 -2
  17. package/dist/commands/knowledge.js +73 -0
  18. package/dist/commands/mcp.js +62 -0
  19. package/dist/commands/origin.js +21 -23
  20. package/dist/commands/people.js +51 -0
  21. package/dist/commands/sets.js +141 -0
  22. package/dist/commands/status.js +34 -24
  23. package/dist/commands/sync.js +11 -4
  24. package/dist/commands/workspace.js +33 -19
  25. package/dist/config/environment.js +13 -27
  26. package/dist/config/paths.js +62 -0
  27. package/dist/config/selection.js +30 -0
  28. package/dist/config/settings.js +97 -108
  29. package/dist/config/state.js +57 -57
  30. package/dist/entry/knowledge-startup.js +32 -0
  31. package/dist/entry/mcp-launch.js +71 -0
  32. package/dist/entry/opencode-plugin.js +62 -0
  33. package/dist/{features/git-workspace/startup.js → entry/workspace-startup.js} +7 -2
  34. package/dist/errors.js +198 -55
  35. package/dist/features/asset-kinds/index.js +120 -0
  36. package/dist/features/asset-selection/index.js +51 -19
  37. package/dist/features/auth/credentials.js +80 -47
  38. package/dist/features/auth/session.js +80 -45
  39. package/dist/features/auth/transport.js +66 -15
  40. package/dist/features/catalog/index.js +32 -61
  41. package/dist/features/collaboration/api.js +160 -0
  42. package/dist/features/collaboration/index.js +321 -233
  43. package/dist/features/collaboration/remote.js +35 -115
  44. package/dist/features/collaboration/results.js +2 -0
  45. package/dist/features/collaboration/workspace-git.js +233 -149
  46. package/dist/features/collaboration/workspace-github.js +117 -54
  47. package/dist/features/collaboration/workspace-store.js +140 -100
  48. package/dist/features/collaboration/workspace.js +257 -172
  49. package/dist/features/discovery/index.js +68 -57
  50. package/dist/features/doctor/index.js +32 -24
  51. package/dist/features/environment/auto-sync.js +28 -27
  52. package/dist/features/environment/names.js +67 -47
  53. package/dist/features/environment/operations.js +321 -228
  54. package/dist/features/environment/own-entries.js +89 -0
  55. package/dist/features/environment/settle-names.js +91 -0
  56. package/dist/features/environment/stage.js +178 -0
  57. package/dist/features/environment/sync.js +113 -484
  58. package/dist/features/environment/transaction.js +179 -147
  59. package/dist/features/environment/writes.js +196 -0
  60. package/dist/features/github/account.js +25 -0
  61. package/dist/features/github/connections.js +119 -0
  62. package/dist/features/github/pulls.js +118 -0
  63. package/dist/features/hooks/adapt.js +32 -25
  64. package/dist/features/hooks/catalog.js +28 -0
  65. package/dist/features/hooks/compatibility.js +49 -0
  66. package/dist/features/hooks/divergence.js +9 -6
  67. package/dist/features/hooks/test.js +74 -49
  68. package/dist/features/hooks/types.js +1 -0
  69. package/dist/features/imports/discover.js +134 -61
  70. package/dist/features/imports/folder.js +48 -14
  71. package/dist/features/imports/local.js +113 -134
  72. package/dist/features/imports/remote.js +44 -25
  73. package/dist/features/inspection/index.js +17 -17
  74. package/dist/features/inventory/index.js +99 -110
  75. package/dist/features/knowledge/index.js +69 -49
  76. package/dist/features/mcps/catalog.js +31 -0
  77. package/dist/features/mcps/import.js +316 -0
  78. package/dist/features/mcps/index.js +98 -49
  79. package/dist/features/migration/migrate.js +263 -0
  80. package/dist/features/{git-workspace → migration}/move.js +165 -109
  81. package/dist/features/migration/promote.js +24 -0
  82. package/dist/features/native/adapters.js +53 -94
  83. package/dist/features/native/configuration.js +128 -82
  84. package/dist/features/native/hook-shell.js +55 -0
  85. package/dist/features/native/plugin-module.js +56 -0
  86. package/dist/features/onboarding/environment.js +67 -34
  87. package/dist/features/onboarding/setup.js +43 -40
  88. package/dist/features/repositories/context.js +30 -13
  89. package/dist/features/server/catalog.js +58 -0
  90. package/dist/features/server/client.js +13 -0
  91. package/dist/features/server/connection.js +37 -0
  92. package/dist/features/server/origin.js +74 -0
  93. package/dist/features/server/pages.js +24 -0
  94. package/dist/features/skills/catalog.js +42 -0
  95. package/dist/features/workspace/assets.js +57 -0
  96. package/dist/features/workspace/cloud-source.js +34 -0
  97. package/dist/features/workspace/directory.js +38 -0
  98. package/dist/features/{git-workspace → workspace}/format.js +114 -51
  99. package/dist/features/workspace/git.js +214 -0
  100. package/dist/features/workspace/installed.js +92 -0
  101. package/dist/features/{git-workspace → workspace}/overlay.js +43 -23
  102. package/dist/features/workspace/packages.js +160 -0
  103. package/dist/features/{git-workspace → workspace}/publish.js +120 -64
  104. package/dist/features/workspace/repo-source.js +192 -0
  105. package/dist/features/{git-workspace → workspace}/setup.js +60 -42
  106. package/dist/features/{git-workspace → workspace}/snapshot.js +53 -18
  107. package/dist/features/workspace/source.js +1 -0
  108. package/dist/features/workspace/tree.js +52 -0
  109. package/dist/features/workspace/workspace-source.js +27 -0
  110. package/dist/harnesses/claude.js +23 -1
  111. package/dist/harnesses/codex.js +57 -1
  112. package/dist/harnesses/cursor.js +22 -1
  113. package/dist/harnesses/detect.js +6 -50
  114. package/dist/harnesses/formats.js +45 -0
  115. package/dist/harnesses/opencode.js +111 -0
  116. package/dist/harnesses/registry.js +35 -2
  117. package/dist/platform.js +375 -0
  118. package/dist/program.js +225 -54
  119. package/dist/runtime.js +1 -0
  120. package/dist/shared/cli-error.js +22 -0
  121. package/dist/shared/constants.js +32 -0
  122. package/dist/shared/files.js +72 -0
  123. package/dist/shared/lock.js +49 -0
  124. package/dist/shared/lookup.js +11 -0
  125. package/dist/shared/patterns.js +94 -0
  126. package/dist/shared/shell.js +22 -0
  127. package/dist/shared/values.js +26 -0
  128. package/dist/ui/add-asset.js +41 -400
  129. package/dist/ui/add-hook.js +213 -0
  130. package/dist/ui/add-mcp.js +107 -0
  131. package/dist/ui/add-prompts.js +47 -0
  132. package/dist/ui/add-skills.js +115 -0
  133. package/dist/ui/asset-list.js +31 -13
  134. package/dist/ui/assets.js +33 -44
  135. package/dist/ui/auth.js +43 -33
  136. package/dist/ui/clash.js +11 -6
  137. package/dist/ui/collaboration.js +116 -44
  138. package/dist/ui/connection.js +10 -4
  139. package/dist/ui/decision-error.js +24 -0
  140. package/dist/ui/environment-onboarding.js +35 -13
  141. package/dist/ui/format.js +66 -18
  142. package/dist/ui/hook-compatibility.js +14 -6
  143. package/dist/ui/mcp.js +28 -3
  144. package/dist/ui/move.js +10 -5
  145. package/dist/ui/onboarding.js +113 -73
  146. package/dist/ui/options.js +9 -0
  147. package/dist/ui/output.js +106 -43
  148. package/dist/ui/pick.js +45 -33
  149. package/dist/ui/scope-install.js +15 -7
  150. package/dist/ui/selection.js +15 -11
  151. package/dist/ui/theme.js +37 -14
  152. package/dist/version.js +6 -3
  153. package/package.json +13 -3
  154. package/dist/features/capabilities/index.js +0 -106
  155. package/dist/features/collaboration/domain.js +0 -90
  156. package/dist/features/environment/cloud-source.js +0 -27
  157. package/dist/features/environment/installed.js +0 -124
  158. package/dist/features/environment/packages.js +0 -120
  159. package/dist/features/environment/remote.js +0 -71
  160. package/dist/features/environment/workspace-source.js +0 -19
  161. package/dist/features/git-hosts/index.js +0 -148
  162. package/dist/features/git-workspace/assets.js +0 -71
  163. package/dist/features/git-workspace/git.js +0 -135
  164. package/dist/features/git-workspace/migrate.js +0 -188
  165. package/dist/features/git-workspace/source.js +0 -159
  166. package/dist/features/imports/mcp.js +0 -219
  167. package/dist/features/knowledge/startup.js +0 -25
  168. package/dist/features/native/mcp-launch.js +0 -57
  169. package/dist/features/skills/install.js +0 -25
  170. package/dist/features/skills/remote.js +0 -177
  171. package/dist/features/skills/sync.js +0 -121
  172. package/dist/features/skills/validation.js +0 -34
  173. /package/dist/features/environment/{source.js → events.js} +0 -0
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Identifier shapes and text formats that several modules check. Each is
3
+ * defined once here so the copies can't drift apart; `src/tests/patterns.test.ts`
4
+ * covers them.
5
+ */
6
+ import { MAX_ASSET_NAME_LENGTH } from "./constants.js";
7
+ /** A UUIDv4 in either case, such as `729b9d5a-4a8c-4aa7-9b8d-975a55ac373e`. */
8
+ export const UUID_V4 = /^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i;
9
+ /**
10
+ * A full SHA-1 Git object name in lowercase, as Git prints it:
11
+ * `3f786850e387550fdab836ed7e6dc881de23001b`. SHA-256 repositories use 64
12
+ * digits and don't match.
13
+ */
14
+ export const GIT_OBJECT_ID = /^[\da-f]{40}$/;
15
+ /**
16
+ * An asset, folder or slug name: lowercase letters and digits in words joined by
17
+ * single hyphens, such as `code-review` or `team2`. Never `-a`, `a--b` or `A`.
18
+ */
19
+ export const NAME = /^[a-z\d]+(?:-[a-z\d]+)*$/;
20
+ /**
21
+ * Whether `name` can be an asset's folder and installed name: {@link NAME}, at
22
+ * most 64 characters.
23
+ */
24
+ export const validAssetName = (name) => NAME.test(name) && name.length <= MAX_ASSET_NAME_LENGTH;
25
+ /** Turns any text into a {@link NAME}-shaped slug: `Team A/Review!` → `team-a-review`. */
26
+ export function slugify(text) {
27
+ return text
28
+ .toLowerCase()
29
+ .replace(/[^a-z\d]+/g, "-")
30
+ .replace(/^-|-$/g, "");
31
+ }
32
+ /**
33
+ * YAML front matter at the very start of a Markdown file, optionally after a
34
+ * byte-order mark, with LF or CRLF line endings:
35
+ *
36
+ * ```text
37
+ * ---
38
+ * name: code-review
39
+ * description: Reviews a diff
40
+ * ---
41
+ * Body…
42
+ * ```
43
+ */
44
+ const FRONT_MATTER = /^(\uFEFF?---\r?\n)([\s\S]*?)(\r?\n---(?:\r?\n|$))/;
45
+ /** Splits a Markdown file into its front matter and body; null when there is none. */
46
+ export function splitFrontMatter(text) {
47
+ const match = FRONT_MATTER.exec(text);
48
+ if (!match) {
49
+ return null;
50
+ }
51
+ const [whole, open = "", yaml = "", close = ""] = match;
52
+ return { open, yaml, close, body: text.slice(whole.length) };
53
+ }
54
+ /** A top-level `name:` line in YAML, such as `name: code-review` or `name : x`. */
55
+ const NAME_LINE = /^name[ \t]*:.*$/m;
56
+ /**
57
+ * Sets the top-level `name:` in a YAML document (a `hook.yaml`, or the front
58
+ * matter of a `SKILL.md`), adding it as the first line when there is none.
59
+ * Only the first `name:` at the start of a line changes; nested keys are indented
60
+ * and left alone.
61
+ */
62
+ export function setYamlName(yaml, name) {
63
+ return NAME_LINE.test(yaml)
64
+ ? yaml.replace(NAME_LINE, () => `name: ${name}`)
65
+ : `name: ${name}\n${yaml}`;
66
+ }
67
+ /** A positive whole number as typed on the command line: `1`, `20`; never `0`, `01` or `1.5`. */
68
+ export const POSITIVE_INTEGER = /^[1-9]\d*$/;
69
+ /**
70
+ * A name in CONSTANT_CASE, such as an environment variable (`API_KEY`) or an
71
+ * error code (`KNOWLEDGE_NOT_FOUND`).
72
+ */
73
+ export const CONSTANT_CASE = /^[A-Z][\dA-Z_]*$/;
74
+ /**
75
+ * The name inside a tool's environment variable reference (`${API_KEY}`,
76
+ * `{env:api_key}`, `$_TOKEN2`): a letter or underscore (a word character
77
+ * that isn't a digit), then word characters. Unanchored and without flags, for
78
+ * building those reference patterns from its `source`.
79
+ */
80
+ export const VARIABLE_NAME = /[^\W\d]\w*/;
81
+ /**
82
+ * Splits an origin selector at its first `/` or `:`: `team/review` and
83
+ * `team:review` → `{ type: "team", value: "review" }`; `org` → `{ type: "org" }`.
84
+ * The value keeps any further separators: `repo/a/b` → `a/b`.
85
+ */
86
+ export function splitOrigin(selector) {
87
+ const separator = selector.search(/[/:]/);
88
+ return separator < 0
89
+ ? { type: selector }
90
+ : {
91
+ type: selector.slice(0, separator),
92
+ value: selector.slice(separator + 1),
93
+ };
94
+ }
@@ -0,0 +1,22 @@
1
+ /** Quotes text as one POSIX shell word: `it's` → `'it'\''s'`. */
2
+ export const posixQuote = (value) => "'" + value.replaceAll("'", "'\\''") + "'";
3
+ /**
4
+ * Text the shell reads as one word without quotes: `claude`, `v1.2-rc`, but
5
+ * not `a b`, `$HOME` or `/usr/bin`.
6
+ *
7
+ * @internal
8
+ */
9
+ export const PLAIN_WORD = /^[\w.-]+$/;
10
+ /** One POSIX shell word, quoted only when it needs to be. */
11
+ export const posixWord = (value) => PLAIN_WORD.test(value) ? value : posixQuote(value);
12
+ /**
13
+ * Quotes text as one PowerShell word. PowerShell also ends a single-quoted
14
+ * string at the typographic single quotes, so every one of them is doubled.
15
+ */
16
+ export function powershellQuote(value) {
17
+ let quoted = value;
18
+ for (const quote of "'\u2018\u2019\u201A\u201B") {
19
+ quoted = quoted.replaceAll(quote, quote + quote);
20
+ }
21
+ return `'${quoted}'`;
22
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Narrowing for values whose shape isn't known: parsed JSON, YAML and TOML,
3
+ * especially config files other tools write.
4
+ */
5
+ /** Whether `value` is a plain object: not null, not an array. */
6
+ export function isRecord(value) {
7
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8
+ }
9
+ /** `value` when it's a plain object, otherwise an empty one: for config files written by other tools. */
10
+ export function asRecord(value) {
11
+ return isRecord(value) ? value : {};
12
+ }
13
+ /** The strings in `value` when it's an array, otherwise none. */
14
+ export function asStrings(value) {
15
+ return Array.isArray(value)
16
+ ? value.filter((item) => typeof item === "string")
17
+ : [];
18
+ }
19
+ /** The `code` of a Node.js system error, such as `ENOENT`. */
20
+ export function errorCode(error) {
21
+ return error instanceof Error &&
22
+ "code" in error &&
23
+ typeof error.code === "string"
24
+ ? error.code
25
+ : undefined;
26
+ }
@@ -1,62 +1,8 @@
1
- import checkbox from "@inquirer/checkbox";
2
- import confirm from "@inquirer/confirm";
3
- import input from "@inquirer/input";
4
- import select from "@inquirer/select";
5
- import { createInterface } from "node:readline";
6
- import { basename, join } from "node:path";
7
1
  import { CliError } from "../errors.js";
8
- import { adapters, harnesses } from "../harnesses/registry.js";
9
- import { buildHookPackage, discoverHooks, discoverSkills, plainCommand, scopeExists, } from "../features/imports/discover.js";
10
- import { adaptHook, toolNames } from "../features/hooks/adapt.js";
11
- import { folderDivergence } from "../features/hooks/divergence.js";
12
- import { LOCAL_ORIGIN } from "../features/git-workspace/overlay.js";
13
- import { renamedSkill, saveImported, } from "../features/imports/local.js";
14
- import { addMcpServers, conflictingEntries, convertServer, harnessServers, parseMcpText, } from "../features/imports/mcp.js";
15
- import { assertSourceExists, plainFolder, readFolder, removeImported, } from "../features/imports/folder.js";
16
- import { fetchRemote, parseLocation, } from "../features/imports/remote.js";
2
+ import { assetKinds } from "../features/asset-kinds/index.js";
3
+ import { scopeExists } from "../features/imports/discover.js";
17
4
  import { synchronize } from "../features/environment/sync.js";
18
- import { readFile } from "node:fs/promises";
19
- import { bold, dim, ok, warn } from "./format.js";
20
- import { checkboxTheme, promptTheme } from "./theme.js";
21
- /** Reads pasted lines until they form complete JSON, so nobody has to press Ctrl+D. */
22
- function pasteJson(write) {
23
- write(dim("Paste the JSON. It's read as soon as it's complete."));
24
- return new Promise((resolve) => {
25
- const lines = [];
26
- const reader = createInterface({ input: process.stdin });
27
- reader.on("line", (line) => {
28
- lines.push(line);
29
- try {
30
- JSON.parse(lines.join("\n"));
31
- reader.close();
32
- }
33
- catch {
34
- // Not complete yet.
35
- }
36
- });
37
- reader.on("close", () => resolve(lines.join("\n")));
38
- });
39
- }
40
- export const terminalPrompts = (write) => ({
41
- chooseMany: (message, choices) => checkbox({
42
- message,
43
- choices,
44
- pageSize: 12,
45
- loop: false,
46
- theme: checkboxTheme,
47
- }),
48
- chooseOne: (message, choices, fallback) => select({
49
- message,
50
- choices,
51
- default: fallback,
52
- pageSize: 12,
53
- loop: false,
54
- theme: promptTheme,
55
- }),
56
- text: (message, fallback) => input({ message, default: fallback, theme: promptTheme }),
57
- yes: (message, fallback = true) => confirm({ message, default: fallback, theme: promptTheme }),
58
- paste: () => pasteJson(write),
59
- });
5
+ import { warn } from "./format.js";
60
6
  const updateChoices = [
61
7
  {
62
8
  name: "Update when I ask",
@@ -74,367 +20,62 @@ const updateChoices = [
74
20
  description: "Every sync takes the latest. Anyone with push rights to that repo can change what runs here.",
75
21
  },
76
22
  ];
77
- async function updateMode(options, context) {
78
- if (options.updates)
23
+ export async function updateMode(options, context) {
24
+ if (options.updates) {
79
25
  return options.updates;
80
- if (!context.interactive)
26
+ }
27
+ if (!context.interactive) {
81
28
  return "manual";
82
- return (await context.prompts.chooseOne("How should it stay up to date?", updateChoices, "manual"));
29
+ }
30
+ const mode = await context.prompts.chooseOne("How should it stay up to date?", updateChoices, "manual");
31
+ return (updateChoices.find((choice) => choice.value === mode)?.value ?? "manual");
83
32
  }
84
- async function finish(context) {
85
- const events = await synchronize(undefined, context.home, undefined, {
33
+ export async function finish(context) {
34
+ const events = await synchronize(undefined, context.runtime, undefined, {
86
35
  prompt: false,
87
36
  });
88
- for (const event of events)
89
- if (event.type === "invalid")
37
+ for (const event of events) {
38
+ if (event.type === "invalid") {
90
39
  context.write(`${warn("!")} ${event.name}: ${event.reason}`);
40
+ }
41
+ }
91
42
  }
92
- const folderLabel = (root) => root || "repo root";
43
+ export const folderLabel = (root) => root || "repo root";
93
44
  /** A link to a folder is searched on its own, so a miss there says so. */
94
- function notFound(remote, url, kind) {
45
+ export function notFound(remote, url, kind) {
95
46
  const command = `barndog ${kind === "Skill" ? "skills" : "hooks"} add`;
96
47
  const expects = kind === "Skill"
97
48
  ? "A Skill is a folder with a SKILL.md."
98
49
  : "A Hook is a folder with hook.yaml, hook settings, or scripts.";
99
- if (!scopeExists(remote))
50
+ if (!scopeExists(remote)) {
100
51
  return new CliError(`Can't find ${remote.path} in ${remote.url}${remote.ref ? ` at ${remote.ref}` : ""}.`, `${command} ${remote.url}`);
101
- if (remote.path)
52
+ }
53
+ if (remote.path) {
102
54
  return new CliError(`No valid ${kind} found in ${remote.path} or the folders below it. ${expects} BarnDog only looks where the link points, not in the rest of the repo.`, `${command} ${remote.url}`);
55
+ }
103
56
  return new CliError(`No valid ${kind} found in ${url}. ${expects}`);
104
57
  }
105
- /** Stops two copies of a Skill from claiming the same name, saying which folders hold them. */
106
- function assertDistinctNames(chosen, url) {
107
- const clash = chosen.find((skill, index) => chosen.findIndex((s) => s.name === skill.name) !== index);
108
- if (!clash)
109
- return;
110
- const copies = chosen.filter((s) => s.name === clash.name);
111
- throw new CliError(`${clash.name} is in more than one folder: ${copies.map((s) => folderLabel(s.root)).join(", ")}. Choose one.`, `barndog skills add ${url} --only ${copies.find((s) => s.root).root}`);
112
- }
113
- /** A plain folder is read in place; everything else is fetched with Git. */
114
- async function withSkillSource(source, folder, use) {
115
- if (folder)
116
- return use(await readFolder(folder));
117
- return fetchRemote(parseLocation(source), { allowPrompt: true }, use);
118
- }
119
- function assertFolderOptions(options, folder) {
120
- if (!folder && (options.copy || options.move))
121
- throw new CliError(`--${options.copy ? "copy" : "move"} only applies when adding from a local folder.`);
122
- if (folder && options.updates && options.updates !== "fork")
123
- throw new CliError("A plain folder has no history to update from, so --updates doesn't apply.", "barndog skills add <folder> --copy");
124
- }
125
- async function folderTransfer(count, options, context) {
126
- if (options.move)
127
- return "move";
128
- if (options.copy || !context.interactive)
129
- return "copy";
130
- return context.prompts.chooseOne(`Copy or move ${count === 1 ? "it" : "them"} into your workspace?`, [
131
- {
132
- name: "Copy",
133
- value: "copy",
134
- description: "Leaves the original where it is. Later edits to it won't carry over.",
135
- },
136
- {
137
- name: "Move",
138
- value: "move",
139
- description: "Deletes the imported files from the original folder once they're in your workspace.",
140
- },
141
- ], "copy");
142
- }
143
- export async function addSkills(url, options, context) {
144
- assertSourceExists(url);
145
- const folder = await plainFolder(url);
146
- assertFolderOptions(options, folder);
147
- await withSkillSource(url, folder, async (remote) => {
148
- const { skills, skipped } = discoverSkills(remote);
149
- for (const skip of skipped)
150
- context.write(`${warn("!")} ${skip.path}: ${skip.reason}`);
151
- if (!skills.length)
152
- throw notFound(remote, url, "Skill");
153
- const repeated = (name) => skills.filter((s) => s.name === name).length > 1;
154
- const distinctName = (s) => repeated(s.name) ? `${s.name} (${folderLabel(s.root)})` : s.name;
155
- let chosen = skills;
156
- if (options.only?.length)
157
- chosen = skills.filter((s) => options.only.includes(s.name) || options.only.includes(s.root));
158
- else if (skills.length > 1 && !options.all) {
159
- if (!context.interactive)
160
- throw new CliError(`${url} has ${skills.length} Skills: ${skills.map(distinctName).join(", ")}.`, "barndog skills add <url> --only <name or folder>");
161
- const picked = await context.prompts.chooseMany("Which Skills do you want?", skills.map((s) => ({
162
- name: `${s.name} ${dim(folderLabel(s.root))}`,
163
- value: s.root,
164
- short: distinctName(s),
165
- description: `Description: ${s.description}`,
166
- })));
167
- chosen = skills.filter((s) => picked.includes(s.root));
168
- }
169
- if (!chosen.length)
170
- throw new CliError("No Skills were chosen, so nothing was added.");
171
- assertDistinctNames(chosen, url);
172
- if (options.as && chosen.length !== 1)
173
- throw new CliError("--as renames one Skill, so choose exactly one.");
174
- const transfer = folder
175
- ? await folderTransfer(chosen.length, options, context)
176
- : null;
177
- const mode = folder ? "fork" : await updateMode(options, context);
178
- for (const skill of chosen) {
179
- const name = options.as ?? skill.name;
180
- await saveImported({
181
- kind: "skill",
182
- name,
183
- entries: renamedSkill(skill, name),
184
- mode,
185
- remote,
186
- root: skill.root,
187
- }, context.home);
188
- if (transfer !== "move") {
189
- context.write(`${ok("✔")} Added ${bold(name)}`);
190
- continue;
191
- }
192
- const original = join(folder, skill.root);
193
- const gone = await removeImported(original, skill.entries);
194
- context.write(`${ok("✔")} Moved ${bold(name)} into your workspace`);
195
- if (!gone)
196
- context.write(dim(` ${original} has other files, so it was left in place.`));
197
- }
198
- });
199
- await finish(context);
200
- }
201
- /** Scripts with no settings anywhere: the person says which tools and events run them. */
202
- export async function pickHookPlan(draft, executable, context) {
203
- const { prompts } = context;
204
- // Choices made for one coding tool start out selected for the next.
205
- const carried = new Map();
206
- const chosen = (await prompts.chooseMany("Which coding tools should this Hook support?", harnesses.map((h) => ({ name: adapters[h].name, value: h }))));
207
- const plan = {};
208
- for (const harness of chosen) {
209
- const known = adapters[harness].hooks.events;
210
- const events = await prompts.chooseMany(`${adapters[harness].name}: which events should run it?`, known.map(({ name }) => ({
211
- name,
212
- value: name,
213
- checked: carried.has(name.toLowerCase()),
214
- })));
215
- const drafts = [];
216
- for (const event of events) {
217
- const script = draft.scripts.length === 1
218
- ? draft.scripts[0]
219
- : await prompts.chooseOne(`${adapters[harness].name} ${event}: which script?`, draft.scripts.map((s) => ({ name: s, value: s })), carried.get(event.toLowerCase())?.script);
220
- const hint = known.find((e) => e.name === event)?.matcher;
221
- const matcher = hint
222
- ? (await prompts.text(`${event} matcher (${hint})`, "")).trim() ||
223
- undefined
224
- : undefined;
225
- const picked = {
226
- event,
227
- matcher,
228
- script,
229
- command: plainCommand(script, executable(script)),
230
- };
231
- drafts.push(picked);
232
- carried.set(event.toLowerCase(), picked);
233
- }
234
- if (drafts.length)
235
- plan[harness] = drafts;
58
+ /**
59
+ * The candidates `--only` names, by name or folder. A name that matches none
60
+ * stops the import with the names the source has, so a typo never adds the
61
+ * wrong asset or nothing.
62
+ */
63
+ export function onlyChosen(candidates, only, source) {
64
+ const named = (candidate, wanted) => candidate.name === wanted || candidate.root === wanted;
65
+ const missing = only.filter((wanted) => !candidates.some((candidate) => named(candidate, wanted)));
66
+ if (missing.length) {
67
+ const { one, command } = assetKinds[source.kind];
68
+ const available = [...new Set(candidates.map((c) => c.name))];
69
+ throw new CliError(`${source.url} has no ${one} named ${missing.join(", ")}. It has ${available.join(", ")}.`, `barndog ${command} add ${source.url} --only <name>`);
236
70
  }
237
- return plan;
71
+ return candidates.filter((candidate) => only.some((wanted) => named(candidate, wanted)));
238
72
  }
239
- /** Says which of this machine's coding tools a new Hook leaves out, with one prompt for all. */
240
- async function reportCoverage(name, folder, context) {
241
- const divergence = await folderDivergence(folder);
242
- if (divergence)
243
- context.write(`${warn("!")} ${divergence}`);
244
- const { written, targets, prompt } = await adaptHook(name, LOCAL_ORIGIN, undefined, context.home);
245
- if (!prompt)
73
+ /** Two chosen assets with one name would land in the same workspace folder. */
74
+ export function assertDistinctNames(chosen, source) {
75
+ const clash = chosen.find((candidate, index) => chosen.findIndex((c) => c.name === candidate.name) !== index);
76
+ if (!clash) {
246
77
  return;
247
- context.write(`${warn("!")} ${bold(name)} was written for ${toolNames(written)}. It won't run in ${toolNames(targets, "or")}: BarnDog doesn't adapt Hooks between coding tools.`);
248
- context.write(dim(" An AI agent can check whether it can be adapted. Give it this:"));
249
- context.write("");
250
- context.write(prompt);
251
- context.write("");
252
- context.write(dim(` Print it again: barndog hooks adapt ${name} --origin ${LOCAL_ORIGIN}`));
253
- }
254
- export async function addHook(url, options, context) {
255
- assertSourceExists(url);
256
- if (await plainFolder(url))
257
- throw new CliError(`${url} isn't a Git repo, and Hooks can only be added from one for now.`, "git init, commit the Hook, then run barndog hooks add again");
258
- const location = parseLocation(url);
259
- const fallback = basename(url.replace(/\/$/, "").replace(/\.git$/, ""))
260
- .toLowerCase()
261
- .replace(/[^a-z0-9-]+/g, "-")
262
- .replace(/^-+|-+$/g, "") || "hook";
263
- await fetchRemote(location, { allowPrompt: true }, async (remote) => {
264
- const { candidates, skipped } = discoverHooks(remote, fallback);
265
- for (const skip of skipped)
266
- context.write(`${warn("!")} ${skip.path}: ${skip.reason}`);
267
- if (!candidates.length)
268
- throw notFound(remote, url, "Hook");
269
- let candidate = candidates[0];
270
- if (candidates.length > 1) {
271
- if (options.only?.length === 1)
272
- candidate =
273
- candidates.find((c) => c.name === options.only[0]) ?? candidate;
274
- else if (!context.interactive)
275
- throw new CliError(`${url} has several Hooks: ${candidates.map((c) => c.name).join(", ")}.`, "barndog hooks add <url> --only <name>");
276
- else {
277
- const picked = await context.prompts.chooseOne("Which Hook do you want?", candidates.map((c, index) => ({
278
- name: c.type === "package"
279
- ? `${c.name} ${dim(folderLabel(c.root))}`
280
- : c.name,
281
- value: String(index),
282
- ...(c.type === "package"
283
- ? { description: `Description: ${c.description}` }
284
- : {}),
285
- })));
286
- candidate = candidates[Number(picked)];
287
- }
288
- }
289
- const mode = await updateMode(options, context);
290
- if (candidate.type === "package") {
291
- const name = options.as ?? candidate.name;
292
- const entries = candidate.entries.map((entry) => entry.path === "hook.yaml" && name !== candidate.name
293
- ? {
294
- ...entry,
295
- data: Buffer.from(entry.data
296
- .toString("utf8")
297
- .replace(/^name:.*$/m, `name: ${name}`)),
298
- }
299
- : entry);
300
- const saved = await saveImported({ kind: "hook", name, entries, mode, remote, root: candidate.root }, context.home);
301
- context.write(`${ok("✔")} Added ${bold(name)}`);
302
- await reportCoverage(name, saved.path, context);
303
- return;
304
- }
305
- const modes = new Map(remote.snapshot.entries.map((e) => [e.path, e.mode]));
306
- const executable = (script) => modes.get(script) === "100755";
307
- // Settings the author shipped answer every question, and no other tool is offered.
308
- const written = harnesses.filter((h) => candidate.implementations[h]?.length);
309
- let plan;
310
- if (written.length) {
311
- const chosen = context.interactive && written.length > 1
312
- ? (await context.prompts.chooseMany("Which coding tools should this Hook support?", written.map((h) => ({
313
- name: `${adapters[h].name} ${dim(`found in this ${remote.path ? "folder" : "repo"}`)}`,
314
- short: adapters[h].name,
315
- value: h,
316
- checked: true,
317
- }))))
318
- : written;
319
- plan = Object.fromEntries(chosen.map((h) => [h, candidate.implementations[h]]));
320
- }
321
- else if (context.interactive)
322
- plan = await pickHookPlan(candidate, executable, context);
323
- else
324
- throw new CliError("These scripts need events chosen for each coding tool. Run this in a terminal to choose them.");
325
- if (!Object.values(plan).some((events) => events?.length))
326
- throw new CliError("No events were chosen, so nothing was added.");
327
- const name = options.as ??
328
- (context.interactive
329
- ? (await context.prompts.text("Hook name", candidate.name)).trim()
330
- : candidate.name);
331
- const description = options.description ??
332
- (context.interactive
333
- ? (await context.prompts.text("What does it do?", `Hook from ${remote.url}`)).trim()
334
- : `Hook from ${remote.url}`);
335
- const built = buildHookPackage(remote, {
336
- name,
337
- description,
338
- implementations: plan,
339
- });
340
- context.write(dim("These commands will run on this machine:"));
341
- for (const [harness, events] of Object.entries(plan))
342
- for (const event of events ?? [])
343
- context.write(dim(` ${harness} ${event.event}${event.matcher ? ` (${event.matcher})` : ""} ${event.script}`));
344
- if (context.interactive && !(await context.prompts.yes("Add this Hook?")))
345
- throw new CliError("Nothing was added.");
346
- const saved = await saveImported({
347
- kind: "hook",
348
- name,
349
- entries: built.entries,
350
- mode,
351
- remote,
352
- root: built.root,
353
- files: built.files,
354
- }, context.home);
355
- context.write(`${ok("✔")} Added ${bold(name)}`);
356
- if (plan.codex?.length)
357
- context.write(dim("Codex skips new Hooks until you trust them with /hooks."));
358
- // Scripts placed by hand were given their tools on purpose.
359
- if (written.length)
360
- await reportCoverage(name, saved.path, context);
361
- });
362
- await finish(context);
363
- }
364
- async function serversToAdd(name, options, context) {
365
- if (options.config)
366
- return parseMcpText(options.config, name);
367
- if (options.file)
368
- return parseMcpText(await readFile(options.file, "utf8"), name);
369
- const fromHarness = async () => {
370
- const all = (await harnessServers(context.home)).filter((s) => !options.from || s.harness === options.from);
371
- const matching = name ? all.filter((s) => s.name === name) : all;
372
- if (!matching.length)
373
- throw new CliError(name
374
- ? `No MCP server named ${name} in your coding tools.`
375
- : "No MCP servers found in your coding tools that BarnDog doesn't already manage.");
376
- if (name && matching.length === 1)
377
- return matching;
378
- if (!context.interactive)
379
- throw new CliError(`Several servers match: ${matching.map((s) => `${s.name} (${s.label})`).join(", ")}.`, "barndog mcp add <name> --from <harness>");
380
- const picked = await context.prompts.chooseMany("Which MCP servers do you want to add?", matching.map((s, i) => ({
381
- name: `${s.name} ${dim(s.label)}`,
382
- value: String(i),
383
- })));
384
- return picked.map((i) => matching[Number(i)]);
385
- };
386
- if (options.from)
387
- return fromHarness();
388
- if (!context.interactive) {
389
- if (process.stdin.isTTY)
390
- throw new CliError("Pass the configuration with --config, --file or --from, or pipe it in.", "barndog mcp add --file <path>");
391
- let text = "";
392
- for await (const chunk of process.stdin)
393
- text += chunk;
394
- return parseMcpText(text, name);
395
- }
396
- const source = await context.prompts.chooseOne("Where's the configuration?", [
397
- { name: "Paste JSON", value: "paste" },
398
- { name: "One of my coding tools", value: "harness" },
399
- ]);
400
- return source === "paste"
401
- ? parseMcpText(await context.prompts.paste(), name)
402
- : fromHarness();
403
- }
404
- export async function addMcp(name, options, context) {
405
- // `--json` is the global output flag, so this catches the old spelling.
406
- if (name?.trimStart().startsWith("{"))
407
- throw new CliError("That looks like the configuration, not a name.", "barndog mcp add <name> --config '<json>'");
408
- const imported = await serversToAdd(name, options, context);
409
- const oauth = new Set();
410
- for (const { name: server, server: raw } of imported)
411
- if (options.oauth ||
412
- (context.interactive &&
413
- (raw.url || raw.httpUrl) &&
414
- !raw.headers &&
415
- !raw.http_headers &&
416
- !raw.env_http_headers &&
417
- !raw.bearer_token_env_var &&
418
- (await context.prompts.yes(`Does ${server} sign in through a browser (OAuth)?`, false))))
419
- oauth.add(server);
420
- const servers = imported.map((server) => convertServer(server, options.description, oauth.has(server.name)));
421
- if (!servers.length)
422
- throw new CliError("No MCP servers were chosen, so nothing was added.");
423
- let replace = options.replace;
424
- const conflicts = (await Promise.all(servers.map((s) => conflictingEntries(s.name, context.home)))).flat();
425
- if (conflicts.length && !replace && context.interactive) {
426
- context.write("These entries will be replaced by BarnDog-managed ones. A backup of each file is kept:");
427
- for (const conflict of conflicts)
428
- context.write(dim(` ${conflict.file}`));
429
- replace = await context.prompts.yes("Replace them?");
430
- if (!replace)
431
- throw new CliError("Nothing was added.");
432
78
  }
433
- const result = await addMcpServers(servers, { replace }, context.home);
434
- for (const added of result.added)
435
- context.write(`${ok("✔")} Added ${bold(added)}`);
436
- for (const note of result.notes)
437
- context.write(`${warn("!")} ${note}`);
438
- for (const backup of result.backups)
439
- context.write(dim(`Backup: ${backup}`));
79
+ const copies = chosen.filter((c) => c.name === clash.name);
80
+ throw new CliError(`${clash.name} is in more than one folder: ${copies.map((c) => folderLabel(c.root)).join(", ")}. Choose one.`, `barndog ${assetKinds[source.kind].command} add ${source.url} --only ${copies.find((c) => c.root)?.root ?? clash.name}`);
440
81
  }