barndog 0.1.1 → 0.2.1

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 (194) hide show
  1. package/README.md +31 -28
  2. package/dist/cli.js +11 -7
  3. package/dist/commands/add.js +34 -21
  4. package/dist/commands/adopt.js +91 -0
  5. package/dist/commands/arguments.js +12 -0
  6. package/dist/commands/asset-install.js +161 -0
  7. package/dist/commands/asset-list.js +126 -0
  8. package/dist/commands/asset-share.js +94 -0
  9. package/dist/commands/auth.js +4 -0
  10. package/dist/commands/availability.js +72 -27
  11. package/dist/commands/capabilities.js +79 -417
  12. package/dist/commands/collaboration.js +212 -108
  13. package/dist/commands/environment.js +18 -411
  14. package/dist/commands/github.js +200 -0
  15. package/dist/commands/harnesses.js +74 -0
  16. package/dist/commands/helpers.js +39 -0
  17. package/dist/commands/hooks.js +87 -0
  18. package/dist/commands/init.js +4 -2
  19. package/dist/commands/knowledge.js +73 -0
  20. package/dist/commands/mcp-env.js +78 -0
  21. package/dist/commands/mcp.js +64 -0
  22. package/dist/commands/origin.js +21 -23
  23. package/dist/commands/people.js +51 -0
  24. package/dist/commands/sets.js +141 -0
  25. package/dist/commands/status.js +36 -25
  26. package/dist/commands/sync.js +13 -5
  27. package/dist/commands/workspace.js +75 -23
  28. package/dist/config/environment.js +13 -27
  29. package/dist/config/paths.js +81 -0
  30. package/dist/config/selection.js +30 -0
  31. package/dist/config/settings.js +99 -108
  32. package/dist/config/state.js +67 -55
  33. package/dist/entry/knowledge-startup.js +32 -0
  34. package/dist/entry/mcp-launch.js +71 -0
  35. package/dist/entry/opencode-plugin.js +62 -0
  36. package/dist/{features/git-workspace/startup.js → entry/workspace-startup.js} +7 -2
  37. package/dist/errors.js +198 -55
  38. package/dist/features/adoption/adopt.js +234 -0
  39. package/dist/features/adoption/copies.js +29 -0
  40. package/dist/features/adoption/originals.js +116 -0
  41. package/dist/features/adoption/record.js +120 -0
  42. package/dist/features/adoption/restore.js +28 -0
  43. package/dist/features/adoption/scan.js +482 -0
  44. package/dist/features/adoption/undo.js +42 -0
  45. package/dist/features/asset-kinds/index.js +129 -0
  46. package/dist/features/asset-selection/index.js +51 -19
  47. package/dist/features/auth/credentials.js +80 -54
  48. package/dist/features/auth/session.js +83 -49
  49. package/dist/features/auth/transport.js +69 -17
  50. package/dist/features/catalog/index.js +32 -61
  51. package/dist/features/collaboration/api.js +160 -0
  52. package/dist/features/collaboration/index.js +321 -233
  53. package/dist/features/collaboration/remote.js +35 -115
  54. package/dist/features/collaboration/results.js +2 -0
  55. package/dist/features/collaboration/workspace-git.js +242 -152
  56. package/dist/features/collaboration/workspace-github.js +118 -54
  57. package/dist/features/collaboration/workspace-store.js +157 -97
  58. package/dist/features/collaboration/workspace.js +278 -173
  59. package/dist/features/discovery/index.js +68 -57
  60. package/dist/features/doctor/index.js +56 -26
  61. package/dist/features/environment/auto-sync.js +28 -27
  62. package/dist/features/environment/harnesses.js +36 -0
  63. package/dist/features/environment/moves.js +171 -0
  64. package/dist/features/environment/names.js +73 -49
  65. package/dist/features/environment/operations.js +322 -229
  66. package/dist/features/environment/own-entries.js +89 -0
  67. package/dist/features/environment/settle-names.js +91 -0
  68. package/dist/features/environment/stage.js +202 -0
  69. package/dist/features/environment/sync.js +127 -487
  70. package/dist/features/environment/transaction.js +179 -147
  71. package/dist/features/environment/writes.js +243 -0
  72. package/dist/features/github/account.js +25 -0
  73. package/dist/features/github/connections.js +119 -0
  74. package/dist/features/github/pulls.js +118 -0
  75. package/dist/features/hooks/adapt.js +32 -25
  76. package/dist/features/hooks/catalog.js +28 -0
  77. package/dist/features/hooks/compatibility.js +55 -0
  78. package/dist/features/hooks/divergence.js +36 -12
  79. package/dist/features/hooks/test.js +91 -66
  80. package/dist/features/hooks/types.js +1 -0
  81. package/dist/features/imports/discover.js +133 -60
  82. package/dist/features/imports/folder.js +48 -14
  83. package/dist/features/imports/local.js +127 -135
  84. package/dist/features/imports/remote.js +46 -26
  85. package/dist/features/inspection/index.js +17 -17
  86. package/dist/features/inventory/index.js +111 -111
  87. package/dist/features/inventory/show.js +74 -0
  88. package/dist/features/knowledge/index.js +69 -49
  89. package/dist/features/mcps/catalog.js +31 -0
  90. package/dist/features/mcps/import.js +369 -0
  91. package/dist/features/mcps/index.js +104 -50
  92. package/dist/features/mcps/values.js +33 -0
  93. package/dist/features/migration/migrate.js +263 -0
  94. package/dist/features/migration/move.js +448 -0
  95. package/dist/features/migration/promote.js +26 -0
  96. package/dist/features/native/adapters.js +69 -96
  97. package/dist/features/native/configuration.js +134 -84
  98. package/dist/features/native/hook-shell.js +55 -0
  99. package/dist/features/native/plugin-module.js +56 -0
  100. package/dist/features/native/secret-values.js +74 -0
  101. package/dist/features/onboarding/environment.js +67 -34
  102. package/dist/features/onboarding/setup.js +43 -40
  103. package/dist/features/repositories/context.js +30 -13
  104. package/dist/features/secrets/index.js +77 -0
  105. package/dist/features/server/catalog.js +58 -0
  106. package/dist/features/server/client.js +13 -0
  107. package/dist/features/server/connection.js +37 -0
  108. package/dist/features/server/origin.js +74 -0
  109. package/dist/features/server/pages.js +24 -0
  110. package/dist/features/skills/catalog.js +42 -0
  111. package/dist/features/workspace/assets.js +57 -0
  112. package/dist/features/workspace/cloud-source.js +34 -0
  113. package/dist/features/workspace/directory.js +38 -0
  114. package/dist/features/{git-workspace → workspace}/format.js +121 -54
  115. package/dist/features/workspace/git.js +221 -0
  116. package/dist/features/workspace/installed.js +92 -0
  117. package/dist/features/{git-workspace → workspace}/overlay.js +53 -46
  118. package/dist/features/workspace/packages.js +173 -0
  119. package/dist/features/{git-workspace → workspace}/publish.js +120 -64
  120. package/dist/features/workspace/repo-source.js +193 -0
  121. package/dist/features/{git-workspace → workspace}/setup.js +72 -45
  122. package/dist/features/{git-workspace → workspace}/snapshot.js +60 -19
  123. package/dist/features/workspace/source.js +1 -0
  124. package/dist/features/workspace/tree.js +52 -0
  125. package/dist/features/workspace/workspace-source.js +27 -0
  126. package/dist/harnesses/claude.js +23 -1
  127. package/dist/harnesses/codex.js +67 -1
  128. package/dist/harnesses/cursor.js +22 -1
  129. package/dist/harnesses/detect.js +6 -50
  130. package/dist/harnesses/formats.js +52 -0
  131. package/dist/harnesses/opencode.js +108 -0
  132. package/dist/harnesses/registry.js +35 -2
  133. package/dist/platform.js +403 -0
  134. package/dist/program.js +275 -56
  135. package/dist/runtime.js +1 -0
  136. package/dist/shared/cli-error.js +22 -0
  137. package/dist/shared/constants.js +32 -0
  138. package/dist/shared/files.js +107 -0
  139. package/dist/shared/lock.js +113 -0
  140. package/dist/shared/lookup.js +11 -0
  141. package/dist/shared/patterns.js +102 -0
  142. package/dist/shared/shell.js +20 -0
  143. package/dist/shared/values.js +26 -0
  144. package/dist/ui/add-asset.js +41 -400
  145. package/dist/ui/add-hook.js +219 -0
  146. package/dist/ui/add-mcp.js +170 -0
  147. package/dist/ui/add-prompts.js +47 -0
  148. package/dist/ui/add-skills.js +117 -0
  149. package/dist/ui/adopt.js +197 -0
  150. package/dist/ui/asset-list.js +31 -13
  151. package/dist/ui/assets.js +38 -47
  152. package/dist/ui/auth.js +45 -34
  153. package/dist/ui/clash.js +10 -6
  154. package/dist/ui/collaboration.js +116 -44
  155. package/dist/ui/connection.js +17 -6
  156. package/dist/ui/decision-error.js +24 -0
  157. package/dist/ui/environment-onboarding.js +35 -13
  158. package/dist/ui/format.js +66 -18
  159. package/dist/ui/harness-picker.js +18 -0
  160. package/dist/ui/hook-compatibility.js +14 -6
  161. package/dist/ui/mcp.js +28 -3
  162. package/dist/ui/move.js +57 -6
  163. package/dist/ui/onboarding.js +148 -95
  164. package/dist/ui/options.js +9 -0
  165. package/dist/ui/output.js +108 -43
  166. package/dist/ui/package-details.js +34 -0
  167. package/dist/ui/pick.js +45 -33
  168. package/dist/ui/scope-install.js +18 -7
  169. package/dist/ui/secret-input.js +19 -0
  170. package/dist/ui/selection.js +17 -11
  171. package/dist/ui/theme.js +37 -14
  172. package/dist/version.js +6 -3
  173. package/package.json +13 -3
  174. package/dist/features/capabilities/index.js +0 -106
  175. package/dist/features/collaboration/domain.js +0 -90
  176. package/dist/features/environment/cloud-source.js +0 -27
  177. package/dist/features/environment/installed.js +0 -124
  178. package/dist/features/environment/packages.js +0 -120
  179. package/dist/features/environment/remote.js +0 -71
  180. package/dist/features/environment/workspace-source.js +0 -19
  181. package/dist/features/git-hosts/index.js +0 -148
  182. package/dist/features/git-workspace/assets.js +0 -71
  183. package/dist/features/git-workspace/git.js +0 -135
  184. package/dist/features/git-workspace/migrate.js +0 -188
  185. package/dist/features/git-workspace/move.js +0 -337
  186. package/dist/features/git-workspace/source.js +0 -159
  187. package/dist/features/imports/mcp.js +0 -219
  188. package/dist/features/knowledge/startup.js +0 -25
  189. package/dist/features/native/mcp-launch.js +0 -57
  190. package/dist/features/skills/install.js +0 -25
  191. package/dist/features/skills/remote.js +0 -177
  192. package/dist/features/skills/sync.js +0 -121
  193. package/dist/features/skills/validation.js +0 -34
  194. /package/dist/features/environment/{source.js → events.js} +0 -0
@@ -0,0 +1,219 @@
1
+ /** `barndog hooks add`: brings Hooks from a repository into the local workspace. */
2
+ import { GIT_MODE } from "../features/workspace/snapshot.js";
3
+ import { basename } from "node:path";
4
+ import { CliError } from "../errors.js";
5
+ import { readSettings } from "../config/settings.js";
6
+ import { adapters, hookHarnesses, isHookHarness, } from "../harnesses/registry.js";
7
+ import { buildHookPackage, discoverHooks, plainCommand, } from "../features/imports/discover.js";
8
+ import { adaptHook, toolNames } from "../features/hooks/adapt.js";
9
+ import { folderDivergence } from "../features/hooks/divergence.js";
10
+ import { LOCAL_ORIGIN } from "../features/workspace/overlay.js";
11
+ import { saveImported } from "../features/imports/local.js";
12
+ import { assertSourceExists, plainFolder } from "../features/imports/folder.js";
13
+ import { fetchRemote, parseLocation } from "../features/imports/remote.js";
14
+ import { bold, dim, ok, warn } from "./format.js";
15
+ import { setYamlName, slugify } from "../shared/patterns.js";
16
+ import { only } from "../shared/lookup.js";
17
+ import { assertDistinctNames, finish, folderLabel, notFound, onlyChosen, updateMode, } from "./add-asset.js";
18
+ /** Scripts with no settings anywhere: the person says which tools and events run them. */
19
+ async function pickHookPlan(draft, executable, context) {
20
+ const { prompts } = context;
21
+ // Choices made for one coding tool start out selected for the next.
22
+ const carried = new Map();
23
+ const managed = (await readSettings(context.runtime.home))?.harnesses ?? [];
24
+ const chosen = (await prompts.chooseMany("Which coding tools should this Hook support?", hookHarnesses.map((h) => ({
25
+ name: adapters[h].name,
26
+ value: h,
27
+ checked: managed.includes(h),
28
+ })))).filter(isHookHarness);
29
+ const plan = {};
30
+ for (const harness of chosen) {
31
+ const known = adapters[harness].hooks.events;
32
+ const events = await prompts.chooseMany(`${adapters[harness].name}: which events should run it?`, known.map(({ name }) => ({
33
+ name,
34
+ value: name,
35
+ checked: carried.has(name.toLowerCase()),
36
+ })));
37
+ const drafts = [];
38
+ for (const event of events) {
39
+ const script = only(draft.scripts) ??
40
+ (await prompts.chooseOne(`${adapters[harness].name} ${event}: which script?`, draft.scripts.map((s) => ({ name: s, value: s })), carried.get(event.toLowerCase())?.script));
41
+ const hint = known.find((e) => e.name === event)?.matcher;
42
+ const matcher = hint
43
+ ? (await prompts.text(`${event} matcher (${hint})`, "")).trim() ||
44
+ undefined
45
+ : undefined;
46
+ const picked = {
47
+ event,
48
+ matcher,
49
+ script,
50
+ command: plainCommand(script, executable(script)),
51
+ };
52
+ drafts.push(picked);
53
+ carried.set(event.toLowerCase(), picked);
54
+ }
55
+ if (drafts.length) {
56
+ plan[harness] = drafts;
57
+ }
58
+ }
59
+ return plan;
60
+ }
61
+ /** The packaged Hooks to add: named by `--only`, all of them, or ticked in a picker. */
62
+ async function choosePackages(packages, url, options, context) {
63
+ let chosen = packages;
64
+ if (options.only?.length) {
65
+ chosen = onlyChosen(packages, options.only, { url, kind: "hook" });
66
+ }
67
+ else if (packages.length > 1 && !options.all) {
68
+ if (!context.interactive) {
69
+ throw new CliError(`${url} has ${packages.length} Hooks: ${packages.map((p) => p.name).join(", ")}.`, `barndog hooks add ${url} --only <name>`);
70
+ }
71
+ const picked = await context.prompts.chooseMany("Which Hooks do you want?", packages.map((p) => ({
72
+ name: `${p.name} ${dim(folderLabel(p.root))}`,
73
+ value: p.root,
74
+ short: p.name,
75
+ description: `Description: ${p.description}`,
76
+ })));
77
+ chosen = packages.filter((p) => picked.includes(p.root));
78
+ }
79
+ if (!chosen.length) {
80
+ throw new CliError("No Hooks were chosen, so nothing was added.");
81
+ }
82
+ assertDistinctNames(chosen, { url, kind: "hook" });
83
+ if (options.as && chosen.length !== 1) {
84
+ throw new CliError("--as renames one Hook, so choose exactly one.");
85
+ }
86
+ return chosen;
87
+ }
88
+ /** Says which of this machine's coding tools a new Hook leaves out, with one prompt for all. */
89
+ async function reportCoverage(name, folder, context) {
90
+ const divergence = await folderDivergence(folder);
91
+ if (divergence) {
92
+ context.write(`${warn("!")} ${divergence}`);
93
+ }
94
+ const { written, targets, prompt } = await adaptHook(name, LOCAL_ORIGIN, undefined, context.runtime);
95
+ if (!prompt) {
96
+ return;
97
+ }
98
+ 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.`);
99
+ context.write(dim(" An AI agent can check whether it can be adapted. Give it this:"));
100
+ context.write("");
101
+ context.write(prompt);
102
+ context.write("");
103
+ context.write(dim(` Print it again: barndog hooks adapt ${name} --origin ${LOCAL_ORIGIN}`));
104
+ }
105
+ /**
106
+ * `hooks add <url>`: copies a Hook package, or a draft built from harness
107
+ * settings, into the local workspace.
108
+ */
109
+ export async function addHook(url, options, context) {
110
+ assertSourceExists(url, context.runtime);
111
+ if (await plainFolder(url, context.runtime)) {
112
+ 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");
113
+ }
114
+ const location = parseLocation(url);
115
+ const fallback = slugify(basename(url.replace(/\/$/, "").replace(/\.git$/, ""))) || "hook";
116
+ await fetchRemote(location, { allowPrompt: context.interactive }, async (remote) => {
117
+ const { candidates, skipped } = discoverHooks(remote, fallback);
118
+ for (const skip of skipped) {
119
+ context.write(`${warn("!")} ${skip.path}: ${skip.reason}`);
120
+ }
121
+ const packages = candidates.flatMap((c) => c.type === "package" ? [c] : []);
122
+ if (packages.length) {
123
+ const chosen = await choosePackages(packages, url, options, context);
124
+ const mode = await updateMode(options, context);
125
+ for (const candidate of chosen) {
126
+ const name = options.as ?? candidate.name;
127
+ const entries = candidate.entries.map((entry) => entry.path === "hook.yaml" && name !== candidate.name
128
+ ? {
129
+ ...entry,
130
+ data: Buffer.from(setYamlName(entry.data.toString("utf8"), name)),
131
+ }
132
+ : entry);
133
+ const saved = await saveImported({ kind: "hook", name, entries, mode, remote, root: candidate.root }, context.runtime);
134
+ context.write(`${ok("✔")} Added ${bold(name)}`);
135
+ await reportCoverage(name, saved.path, context);
136
+ }
137
+ return;
138
+ }
139
+ const [candidate] = candidates.flatMap((c) => c.type === "draft" ? [c] : []);
140
+ if (!candidate) {
141
+ throw notFound(remote, url, "Hook");
142
+ }
143
+ // A draft is built from loose scripts and settings, so it has no name to choose by.
144
+ if (options.only?.length) {
145
+ throw new CliError(`${url} has no packaged Hooks to choose from, only scripts and settings to build one from.`, `barndog hooks add ${url}`);
146
+ }
147
+ const mode = await updateMode(options, context);
148
+ const modes = new Map(remote.snapshot.entries.map((e) => [e.path, e.mode]));
149
+ const executable = (script) => modes.get(script) === GIT_MODE.executable;
150
+ // Settings the author shipped answer every question, and no other tool is offered.
151
+ const written = hookHarnesses.filter((h) => candidate.implementations[h]?.length);
152
+ let plan;
153
+ if (written.length) {
154
+ const chosen = context.interactive && written.length > 1
155
+ ? (await context.prompts.chooseMany("Which coding tools should this Hook support?", written.map((h) => ({
156
+ name: `${adapters[h].name} ${dim(`found in this ${remote.path ? "folder" : "repo"}`)}`,
157
+ short: adapters[h].name,
158
+ value: h,
159
+ checked: true,
160
+ })))).filter(isHookHarness)
161
+ : written;
162
+ const { implementations } = candidate;
163
+ plan = Object.fromEntries(chosen.map((h) => [h, implementations[h] ?? []]));
164
+ }
165
+ else if (context.interactive) {
166
+ plan = await pickHookPlan(candidate, executable, context);
167
+ }
168
+ else {
169
+ throw new CliError("These scripts need events chosen for each coding tool. Run this in a terminal to choose them.");
170
+ }
171
+ if (!Object.values(plan).some((events) => events?.length)) {
172
+ throw new CliError("No events were chosen, so nothing was added.");
173
+ }
174
+ const name = options.as ??
175
+ (context.interactive
176
+ ? (await context.prompts.text("Hook name", candidate.name)).trim()
177
+ : candidate.name);
178
+ const description = options.description ??
179
+ (context.interactive
180
+ ? (await context.prompts.text("What does it do?", `Hook from ${remote.url}`)).trim()
181
+ : `Hook from ${remote.url}`);
182
+ const built = buildHookPackage(remote, {
183
+ name,
184
+ description,
185
+ implementations: plan,
186
+ });
187
+ context.write(dim("These commands will run on this machine:"));
188
+ for (const [harness, events] of Object.entries(plan)) {
189
+ for (const event of events ?? []) {
190
+ context.write(dim(` ${harness} ${event.event}${event.matcher ? ` (${event.matcher})` : ""} ${event.script}`));
191
+ }
192
+ }
193
+ if (context.interactive &&
194
+ !(await context.prompts.yes("Add this Hook?"))) {
195
+ throw new CliError("Nothing was added.");
196
+ }
197
+ const saved = await saveImported({
198
+ kind: "hook",
199
+ name,
200
+ entries: built.entries,
201
+ mode,
202
+ remote,
203
+ root: built.root,
204
+ files: built.files,
205
+ }, context.runtime);
206
+ context.write(`${ok("✔")} Added ${bold(name)}`);
207
+ for (const harness of hookHarnesses) {
208
+ const { trustNote } = adapters[harness].hooks;
209
+ if (trustNote && plan[harness]?.length) {
210
+ context.write(dim(trustNote));
211
+ }
212
+ }
213
+ // Scripts placed by hand were given their tools on purpose.
214
+ if (written.length) {
215
+ await reportCoverage(name, saved.path, context);
216
+ }
217
+ }, context.runtime);
218
+ await finish(context);
219
+ }
@@ -0,0 +1,170 @@
1
+ /** `barndog mcp add`: brings MCP servers from JSON or a coding tool into the local workspace. */
2
+ import { localPath } from "../platform.js";
3
+ import { CliError } from "../errors.js";
4
+ import { only } from "../shared/lookup.js";
5
+ import { inputFile } from "../shared/files.js";
6
+ import { addMcpServers, conflictingEntries, convertServer, harnessServers, localMcpNamed, parseMcpText, } from "../features/mcps/import.js";
7
+ import { assetKinds } from "../features/asset-kinds/index.js";
8
+ import { validMcpName } from "../shared/patterns.js";
9
+ import { bold, dim, ok, warn } from "./format.js";
10
+ async function serversToAdd(name, options, context) {
11
+ if (options.config) {
12
+ return parseMcpText(options.config, name);
13
+ }
14
+ if (options.file) {
15
+ return parseMcpText((await inputFile(localPath(options.file, context.runtime))).toString("utf8"), name);
16
+ }
17
+ const fromHarness = async () => {
18
+ const all = (await harnessServers(context.runtime)).filter((s) => !options.from || s.harness === options.from);
19
+ const matching = name ? all.filter((s) => s.name === name) : all;
20
+ const listed = (servers) => servers.map((s) => `${s.name} (${s.label})`).join(", ");
21
+ if (!matching.length) {
22
+ throw new CliError(name && all.length
23
+ ? `No MCP server named ${name} in your coding tools. They have ${listed(all)}.`
24
+ : "No MCP servers found in your coding tools that BarnDog doesn't already manage.");
25
+ }
26
+ if (name && matching.length === 1) {
27
+ return matching;
28
+ }
29
+ if (!context.interactive) {
30
+ throw new CliError(matching.length === 1
31
+ ? `Name the MCP server to add: ${listed(matching)}.`
32
+ : `Several servers match: ${listed(matching)}.`, "barndog mcp add <name> --from <harness>");
33
+ }
34
+ const picked = await context.prompts.chooseMany("Which MCP servers do you want to add?", matching.map((s, i) => ({
35
+ name: `${s.name} ${dim(s.label)}`,
36
+ value: String(i),
37
+ })));
38
+ return picked.flatMap((i) => matching[Number(i)] ?? []);
39
+ };
40
+ if (options.from) {
41
+ return fromHarness();
42
+ }
43
+ if (!context.interactive) {
44
+ if (process.stdin.isTTY) {
45
+ throw new CliError("Pass the configuration with --config, --file or --from, or pipe it in.", "barndog mcp add --file <path>");
46
+ }
47
+ let text = "";
48
+ for await (const chunk of process.stdin) {
49
+ text += chunk;
50
+ }
51
+ return parseMcpText(text, name);
52
+ }
53
+ const source = await context.prompts.chooseOne("Where's the configuration?", [
54
+ { name: "Paste JSON", value: "paste" },
55
+ { name: "One of my coding tools", value: "harness" },
56
+ ]);
57
+ return source === "paste"
58
+ ? parseMcpText(await context.prompts.paste(), name)
59
+ : fromHarness();
60
+ }
61
+ /**
62
+ * Which literal values BarnDog keeps on this machine. Only asked in a
63
+ * terminal; otherwise none are kept and the notes say which variables to set.
64
+ */
65
+ async function chooseKept(found, context) {
66
+ if (!found.length || !context.interactive) {
67
+ return [];
68
+ }
69
+ context.write(dim("BarnDog can keep these values in ~/.barndog/secrets.json, which only you can read and which is never uploaded, and write them into your coding tools' settings. Leave one unticked to set it yourself."));
70
+ return context.prompts.chooseMany("Which values should BarnDog keep on this machine?", found.map(({ server, literal }) => ({
71
+ name: `${literal.variable} ${dim(`${server}: ${literal.key}`)}`,
72
+ short: literal.variable,
73
+ value: literal.variable,
74
+ checked: true,
75
+ })));
76
+ }
77
+ /** Why a server can't be added under `name` here, or null when it can. */
78
+ async function nameProblem(name, context) {
79
+ if (!validMcpName(name)) {
80
+ return `${name} can't be an MCP server name. ${assetKinds.mcp.nameRule}.`;
81
+ }
82
+ const existing = await localMcpNamed(name, context.runtime);
83
+ if (existing === null) {
84
+ return null;
85
+ }
86
+ return existing === name
87
+ ? `You already have a local MCP server named ${name}.`
88
+ : `${name} differs from your local MCP server ${existing} only in case, and they'd share one file on this disk.`;
89
+ }
90
+ /**
91
+ * Applies `--as`, then asks in a terminal for a new name wherever one is
92
+ * unusable or taken. Without a terminal, adding reports it with the fix.
93
+ */
94
+ async function namedServers(servers, as, context) {
95
+ const one = only(servers);
96
+ if (as !== undefined && !one) {
97
+ throw new CliError("--as renames one MCP server, so add exactly one.", "barndog mcp add <name> --as <new-name>");
98
+ }
99
+ const renamed = one && as !== undefined ? [{ ...one, name: as }] : servers;
100
+ if (!context.interactive) {
101
+ return renamed;
102
+ }
103
+ const result = [];
104
+ for (const server of renamed) {
105
+ let name = server.name;
106
+ for (let problem = await nameProblem(name, context); problem; problem = await nameProblem(name, context)) {
107
+ context.write(`${warn("!")} ${problem}`);
108
+ name = (await context.prompts.text(`New name for ${server.name}`)).trim();
109
+ }
110
+ result.push({ ...server, name });
111
+ }
112
+ return result;
113
+ }
114
+ /**
115
+ * `mcp add`: imports MCP servers from a harness's configuration or pasted JSON
116
+ * into the local workspace.
117
+ */
118
+ export async function addMcp(name, options, context) {
119
+ // `--json` is the global output flag, so this catches the old spelling.
120
+ if (name?.trimStart().startsWith("{")) {
121
+ throw new CliError("That looks like the configuration, not a name.", "barndog mcp add <name> --config '<json>'");
122
+ }
123
+ const imported = await namedServers(await serversToAdd(name, options, context), options.as, context);
124
+ const oauth = new Set();
125
+ for (const { name: server, server: raw } of imported) {
126
+ if (options.oauth ||
127
+ (context.interactive &&
128
+ (raw.url || raw.httpUrl) &&
129
+ !raw.headers &&
130
+ !raw.http_headers &&
131
+ !raw.env_http_headers &&
132
+ !raw.bearer_token_env_var &&
133
+ (await context.prompts.yes(`Does ${server} sign in through a browser (OAuth)?`, false)))) {
134
+ oauth.add(server);
135
+ }
136
+ }
137
+ const servers = imported.map((server) => convertServer(server, options.description, oauth.has(server.name)));
138
+ if (!servers.length) {
139
+ throw new CliError("No MCP servers were chosen, so nothing was added.");
140
+ }
141
+ let replace = options.replace;
142
+ const conflicts = (await Promise.all(servers.map((s) => conflictingEntries(s.name, context.runtime)))).flat();
143
+ if (conflicts.length && !replace && context.interactive) {
144
+ context.write("These entries will be replaced by BarnDog-managed ones. A backup of each file is kept:");
145
+ for (const conflict of conflicts) {
146
+ context.write(dim(` ${conflict.file}`));
147
+ }
148
+ replace = await context.prompts.yes("Replace them?");
149
+ if (!replace) {
150
+ throw new CliError("Nothing was added.");
151
+ }
152
+ }
153
+ const keep = await chooseKept(servers.flatMap((server) => server.literals.map((literal) => ({ server: server.name, literal }))), context);
154
+ const result = await addMcpServers(servers, { replace, keep }, context.runtime);
155
+ for (const added of result.added) {
156
+ context.write(`${ok("✔")} Added ${bold(added)}`);
157
+ }
158
+ for (const note of result.notes) {
159
+ context.write(`${warn("!")} ${bold(note.server)}: ${note.text}`);
160
+ }
161
+ // Sync says where each kept value was written.
162
+ result.events.forEach((event) => {
163
+ if (event.type === "notice") {
164
+ context.write(dim(event.message));
165
+ }
166
+ });
167
+ for (const backup of result.backups) {
168
+ context.write(dim(`Backup: ${backup}`));
169
+ }
170
+ }
@@ -0,0 +1,47 @@
1
+ /** The questions the add commands ask in a terminal; tests supply their own answers. */
2
+ import checkbox from "@inquirer/checkbox";
3
+ import confirm from "@inquirer/confirm";
4
+ import input from "@inquirer/input";
5
+ import select from "@inquirer/select";
6
+ import { createInterface } from "node:readline";
7
+ import { dim } from "./format.js";
8
+ import { checkboxTheme, promptTheme } from "./theme.js";
9
+ /** Reads pasted lines until they form complete JSON, so nobody has to press Ctrl+D. */
10
+ function pasteJson(write) {
11
+ write(dim("Paste the JSON. It's read as soon as it's complete."));
12
+ return new Promise((resolve) => {
13
+ const lines = [];
14
+ const reader = createInterface({ input: process.stdin });
15
+ reader.on("line", (line) => {
16
+ lines.push(line);
17
+ try {
18
+ JSON.parse(lines.join("\n"));
19
+ reader.close();
20
+ }
21
+ catch {
22
+ // Not complete yet.
23
+ }
24
+ });
25
+ reader.on("close", () => resolve(lines.join("\n")));
26
+ });
27
+ }
28
+ export const terminalPrompts = (write) => ({
29
+ chooseMany: (message, choices) => checkbox({
30
+ message,
31
+ choices,
32
+ pageSize: 12,
33
+ loop: false,
34
+ theme: checkboxTheme,
35
+ }),
36
+ chooseOne: (message, choices, fallback) => select({
37
+ message,
38
+ choices,
39
+ default: fallback,
40
+ pageSize: 12,
41
+ loop: false,
42
+ theme: promptTheme,
43
+ }),
44
+ text: (message, fallback) => input({ message, default: fallback, theme: promptTheme }),
45
+ yes: (message, fallback = true) => confirm({ message, default: fallback, theme: promptTheme }),
46
+ paste: () => pasteJson(write),
47
+ });
@@ -0,0 +1,117 @@
1
+ import { join } from "node:path";
2
+ import { CliError } from "../errors.js";
3
+ import { discoverSkills, } from "../features/imports/discover.js";
4
+ import { renamedSkill, saveImported } from "../features/imports/local.js";
5
+ import { assertSourceExists, plainFolder, readFolder, removeImported, } from "../features/imports/folder.js";
6
+ import { fetchRemote, parseLocation, } from "../features/imports/remote.js";
7
+ import { bold, dim, ok, warn } from "./format.js";
8
+ import { defined } from "../shared/lookup.js";
9
+ import { finish, folderLabel, assertDistinctNames, notFound, onlyChosen, updateMode, } from "./add-asset.js";
10
+ /** Stops two copies of a Skill from claiming the same name, saying which folders hold them. */
11
+ /** A plain folder is read in place; everything else is fetched with Git. */
12
+ async function withSkillSource(source, runtime, use) {
13
+ if (source.folder) {
14
+ return use(await readFolder(source.folder, runtime));
15
+ }
16
+ // Git may ask for credentials only when someone is there to answer.
17
+ return fetchRemote(parseLocation(source.location), { allowPrompt: source.interactive }, use, runtime);
18
+ }
19
+ function assertFolderOptions(options, folder) {
20
+ if (!folder && (options.copy || options.move)) {
21
+ throw new CliError(`--${options.copy ? "copy" : "move"} only applies when adding from a local folder.`);
22
+ }
23
+ if (folder && options.updates && options.updates !== "fork") {
24
+ throw new CliError("A plain folder has no history to update from, so --updates doesn't apply.", "barndog skills add <folder> --copy");
25
+ }
26
+ }
27
+ async function folderTransfer(count, options, context) {
28
+ if (options.move) {
29
+ return "move";
30
+ }
31
+ if (options.copy || !context.interactive) {
32
+ return "copy";
33
+ }
34
+ return context.prompts.chooseOne(`Copy or move ${count === 1 ? "it" : "them"} into your workspace?`, [
35
+ {
36
+ name: "Copy",
37
+ value: "copy",
38
+ description: "Leaves the original where it is. Later edits to it won't carry over.",
39
+ },
40
+ {
41
+ name: "Move",
42
+ value: "move",
43
+ description: "Deletes the imported files from the original folder once they're in your workspace.",
44
+ },
45
+ ], "copy");
46
+ }
47
+ /**
48
+ * `skills add <url>`: copies Skills from a repository, a harness folder or a
49
+ * plain folder into the local workspace.
50
+ */
51
+ export async function addSkills(url, options, context) {
52
+ assertSourceExists(url, context.runtime);
53
+ const folder = await plainFolder(url, context.runtime);
54
+ assertFolderOptions(options, folder);
55
+ const source = { location: url, folder, interactive: context.interactive };
56
+ await withSkillSource(source, context.runtime, async (remote) => {
57
+ const { skills, skipped } = discoverSkills(remote);
58
+ for (const skip of skipped) {
59
+ context.write(`${warn("!")} ${skip.path}: ${skip.reason}`);
60
+ }
61
+ if (!skills.length) {
62
+ throw notFound(remote, url, "Skill");
63
+ }
64
+ const repeated = (name) => skills.filter((s) => s.name === name).length > 1;
65
+ const distinctName = (s) => repeated(s.name) ? `${s.name} (${folderLabel(s.root)})` : s.name;
66
+ let chosen = skills;
67
+ const { only } = options;
68
+ if (only?.length) {
69
+ chosen = onlyChosen(skills, only, { url, kind: "skill" });
70
+ }
71
+ else if (skills.length > 1 && !options.all) {
72
+ if (!context.interactive) {
73
+ throw new CliError(`${url} has ${skills.length} Skills: ${skills.map(distinctName).join(", ")}.`, "barndog skills add <url> --only <name or folder>");
74
+ }
75
+ const picked = await context.prompts.chooseMany("Which Skills do you want?", skills.map((s) => ({
76
+ name: `${s.name} ${dim(folderLabel(s.root))}`,
77
+ value: s.root,
78
+ short: distinctName(s),
79
+ description: `Description: ${s.description}`,
80
+ })));
81
+ chosen = skills.filter((s) => picked.includes(s.root));
82
+ }
83
+ if (!chosen.length) {
84
+ throw new CliError("No Skills were chosen, so nothing was added.");
85
+ }
86
+ assertDistinctNames(chosen, { url, kind: "skill" });
87
+ if (options.as && chosen.length !== 1) {
88
+ throw new CliError("--as renames one Skill, so choose exactly one.");
89
+ }
90
+ const transfer = folder
91
+ ? await folderTransfer(chosen.length, options, context)
92
+ : null;
93
+ const mode = folder ? "fork" : await updateMode(options, context);
94
+ for (const skill of chosen) {
95
+ const name = options.as ?? skill.name;
96
+ await saveImported({
97
+ kind: "skill",
98
+ name,
99
+ entries: renamedSkill(skill, name),
100
+ mode,
101
+ remote,
102
+ root: skill.root,
103
+ }, context.runtime);
104
+ if (transfer !== "move") {
105
+ context.write(`${ok("✔")} Added ${bold(name)}`);
106
+ continue;
107
+ }
108
+ const original = join(defined(folder, "Only a local folder can be moved"), skill.root);
109
+ const gone = await removeImported(original, skill.entries);
110
+ context.write(`${ok("✔")} Moved ${bold(name)} into your workspace`);
111
+ if (!gone) {
112
+ context.write(dim(` ${original} has other files, so it was left in place.`));
113
+ }
114
+ }
115
+ });
116
+ await finish(context);
117
+ }