barndog 0.2.0 → 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 (93) hide show
  1. package/README.md +29 -27
  2. package/dist/commands/add.js +1 -0
  3. package/dist/commands/adopt.js +91 -0
  4. package/dist/commands/asset-install.js +1 -0
  5. package/dist/commands/asset-list.js +7 -2
  6. package/dist/commands/availability.js +25 -8
  7. package/dist/commands/capabilities.js +8 -2
  8. package/dist/commands/collaboration.js +22 -2
  9. package/dist/commands/harnesses.js +74 -0
  10. package/dist/commands/mcp-env.js +78 -0
  11. package/dist/commands/mcp.js +4 -2
  12. package/dist/commands/status.js +2 -1
  13. package/dist/commands/sync.js +2 -1
  14. package/dist/commands/workspace.js +43 -5
  15. package/dist/config/paths.js +19 -0
  16. package/dist/config/settings.js +5 -3
  17. package/dist/config/state.js +18 -6
  18. package/dist/features/adoption/adopt.js +234 -0
  19. package/dist/features/adoption/copies.js +29 -0
  20. package/dist/features/adoption/originals.js +116 -0
  21. package/dist/features/adoption/record.js +120 -0
  22. package/dist/features/adoption/restore.js +28 -0
  23. package/dist/features/adoption/scan.js +482 -0
  24. package/dist/features/adoption/undo.js +42 -0
  25. package/dist/features/asset-kinds/index.js +9 -0
  26. package/dist/features/auth/credentials.js +7 -14
  27. package/dist/features/auth/session.js +4 -5
  28. package/dist/features/auth/transport.js +3 -2
  29. package/dist/features/collaboration/workspace-git.js +13 -7
  30. package/dist/features/collaboration/workspace-github.js +2 -1
  31. package/dist/features/collaboration/workspace-store.js +23 -3
  32. package/dist/features/collaboration/workspace.js +22 -2
  33. package/dist/features/doctor/index.js +24 -2
  34. package/dist/features/environment/harnesses.js +36 -0
  35. package/dist/features/environment/moves.js +171 -0
  36. package/dist/features/environment/names.js +10 -6
  37. package/dist/features/environment/operations.js +7 -7
  38. package/dist/features/environment/stage.js +25 -1
  39. package/dist/features/environment/sync.js +17 -6
  40. package/dist/features/environment/writes.js +55 -8
  41. package/dist/features/hooks/compatibility.js +11 -5
  42. package/dist/features/hooks/divergence.js +30 -9
  43. package/dist/features/hooks/test.js +25 -25
  44. package/dist/features/imports/discover.js +1 -1
  45. package/dist/features/imports/local.js +15 -2
  46. package/dist/features/imports/remote.js +2 -1
  47. package/dist/features/inventory/index.js +13 -2
  48. package/dist/features/inventory/show.js +74 -0
  49. package/dist/features/mcps/import.js +74 -21
  50. package/dist/features/mcps/index.js +12 -7
  51. package/dist/features/mcps/values.js +33 -0
  52. package/dist/features/migration/move.js +72 -17
  53. package/dist/features/migration/promote.js +2 -0
  54. package/dist/features/native/adapters.js +20 -6
  55. package/dist/features/native/configuration.js +8 -4
  56. package/dist/features/native/secret-values.js +74 -0
  57. package/dist/features/secrets/index.js +77 -0
  58. package/dist/features/workspace/format.js +13 -9
  59. package/dist/features/workspace/git.js +11 -4
  60. package/dist/features/workspace/overlay.js +23 -36
  61. package/dist/features/workspace/packages.js +16 -3
  62. package/dist/features/workspace/publish.js +1 -1
  63. package/dist/features/workspace/repo-source.js +4 -3
  64. package/dist/features/workspace/setup.js +12 -3
  65. package/dist/features/workspace/snapshot.js +7 -1
  66. package/dist/harnesses/claude.js +2 -2
  67. package/dist/harnesses/codex.js +19 -9
  68. package/dist/harnesses/cursor.js +2 -2
  69. package/dist/harnesses/formats.js +12 -5
  70. package/dist/harnesses/opencode.js +3 -6
  71. package/dist/platform.js +39 -11
  72. package/dist/program.js +51 -3
  73. package/dist/shared/files.js +35 -0
  74. package/dist/shared/lock.js +87 -23
  75. package/dist/shared/patterns.js +8 -0
  76. package/dist/shared/shell.js +0 -2
  77. package/dist/ui/add-hook.js +8 -2
  78. package/dist/ui/add-mcp.js +69 -6
  79. package/dist/ui/add-skills.js +7 -5
  80. package/dist/ui/adopt.js +197 -0
  81. package/dist/ui/assets.js +5 -3
  82. package/dist/ui/auth.js +2 -1
  83. package/dist/ui/clash.js +2 -3
  84. package/dist/ui/connection.js +7 -2
  85. package/dist/ui/harness-picker.js +18 -0
  86. package/dist/ui/move.js +48 -2
  87. package/dist/ui/onboarding.js +40 -27
  88. package/dist/ui/output.js +3 -1
  89. package/dist/ui/package-details.js +34 -0
  90. package/dist/ui/scope-install.js +4 -1
  91. package/dist/ui/secret-input.js +19 -0
  92. package/dist/ui/selection.js +3 -1
  93. package/package.json +1 -1
package/dist/program.js CHANGED
@@ -8,14 +8,20 @@ import { registerAuth } from "./commands/auth.js";
8
8
  import { runLogin, runLogout, showAuthStatus } from "./ui/auth.js";
9
9
  import { registerInit } from "./commands/init.js";
10
10
  import { registerSync } from "./commands/sync.js";
11
+ import { registerHarnesses } from "./commands/harnesses.js";
11
12
  import { registerStatus } from "./commands/status.js";
12
13
  import { clashPrompt, synchronize } from "./features/environment/sync.js";
13
14
  import { changeAsset, changeAssets, changeSet, installSet, installSetAssets, listSets, previewSet, renameAsset, setKnowledge, switchSet, } from "./features/environment/operations.js";
15
+ import { changeHarnesses, listHarnesses, selectHarnesses, } from "./features/environment/harnesses.js";
14
16
  import { doctor } from "./features/doctor/index.js";
15
17
  import { repoStatus, workspaceUrl } from "./features/inspection/index.js";
16
18
  import { validateFolder } from "./features/workspace/assets.js";
17
19
  import { migrate } from "./features/migration/migrate.js";
18
20
  import { listLocalAssets, moveLocalAssets } from "./features/migration/move.js";
21
+ import { adoptNative } from "./features/adoption/adopt.js";
22
+ import { undoAdoption } from "./features/adoption/undo.js";
23
+ import { listAdoptions } from "./features/adoption/record.js";
24
+ import { scanNative } from "./features/adoption/scan.js";
19
25
  import { updateImported } from "./features/imports/local.js";
20
26
  import { authenticateMcp, createMcp, mcpVersions, showMcp, updateMcp, } from "./features/mcps/index.js";
21
27
  import { adaptHook, toolNames } from "./features/hooks/adapt.js";
@@ -33,6 +39,7 @@ import { searchCatalog } from "./features/catalog/index.js";
33
39
  import { registerEnvironment } from "./commands/environment.js";
34
40
  import { registerCapabilities } from "./commands/capabilities.js";
35
41
  import { registerWorkspace } from "./commands/workspace.js";
42
+ import { registerAdopt } from "./commands/adopt.js";
36
43
  import { registerAdd } from "./commands/add.js";
37
44
  import { commandNeeds, modeName, needText, unavailableNote, } from "./commands/availability.js";
38
45
  import { runSetup } from "./ui/onboarding.js";
@@ -42,13 +49,27 @@ import { primary } from "./ui/theme.js";
42
49
  import { versionReport } from "./version.js";
43
50
  import { defined } from "./shared/lookup.js";
44
51
  import { barndogPaths } from "./config/paths.js";
52
+ import { showPackage } from "./features/inventory/show.js";
53
+ import { forgetMcpValue, keepMcpValue, listKeptValues, } from "./features/mcps/values.js";
54
+ import { readSettings } from "./config/settings.js";
45
55
  /** Keep command help readable at the conventional eighty-column terminal width. */
46
56
  const HELP_WIDTH = 80;
47
57
  /** Help sections, in order; every top-level command belongs to one. */
48
58
  const groups = [
49
59
  [
50
60
  "Get started:",
51
- ["init", "login", "logout", "auth", "whoami", "sync", "status", "doctor"],
61
+ [
62
+ "init",
63
+ "login",
64
+ "logout",
65
+ "auth",
66
+ "whoami",
67
+ "sync",
68
+ "status",
69
+ "doctor",
70
+ "harnesses",
71
+ "adopt",
72
+ ],
52
73
  ],
53
74
  ["Assets:", ["skills", "mcp", "hooks", "sets", "knowledge"]],
54
75
  [
@@ -251,15 +272,20 @@ export function createProgram(options = {}) {
251
272
  versionFiles: options.versionFiles ?? ((target) => versionFiles(target, runtime)),
252
273
  workingDiff: options.workingDiff ?? (() => workingDiff(runtime)),
253
274
  workingStatus: options.workingStatus ?? (() => workingStatus(runtime)),
254
- login: options.login ?? ((login) => runLogin({ ...login, runtime }, write)),
275
+ login: options.login ??
276
+ ((login) => runLogin({ ...login, runtime, interactive: mode.interactive }, write)),
255
277
  logout: options.logout ?? (() => runLogout(write, runtime)),
256
278
  authStatus: options.authStatus ??
257
279
  (() => showAuthStatus({ write, json: mode.json }, runtime)),
280
+ isSetUp: options.isSetUp ??
281
+ // A damaged file counts as set up: the command that reads it explains what's wrong.
282
+ (async () => (await readSettings(home).catch(() => true)) !== null),
258
283
  setup: options.setup ??
259
284
  ((restart, server, setupOptions) => runSetup({
260
285
  restart,
261
286
  server,
262
287
  ...setupOptions,
288
+ interactive: mode.interactive,
263
289
  write: options.write,
264
290
  runtime,
265
291
  })),
@@ -277,9 +303,18 @@ export function createProgram(options = {}) {
277
303
  ((change, options) => changeSet(change, options, runtime)),
278
304
  switchSet: options.switchSet ?? ((options) => switchSet(options, runtime)),
279
305
  setKnowledge: options.setKnowledge ?? ((enabled) => setKnowledge(enabled, runtime)),
306
+ listHarnesses: options.listHarnesses ?? (() => listHarnesses(runtime)),
307
+ changeHarnesses: options.changeHarnesses ??
308
+ ((change, targets) => changeHarnesses(change, targets, runtime)),
309
+ selectHarnesses: options.selectHarnesses ??
310
+ ((selected) => selectHarnesses(selected, runtime)),
280
311
  doctor: options.doctor ?? (() => doctor(runtime)),
281
312
  workspaceUrl: options.workspaceUrl ?? (() => workspaceUrl(runtime)),
282
313
  repoStatus: options.repoStatus ?? (() => repoStatus(runtime)),
314
+ scanNative: options.scanNative ?? (() => scanNative(runtime)),
315
+ adoptNative: options.adoptNative ?? ((keys, keep) => adoptNative(keys, keep, runtime)),
316
+ listAdoptions: options.listAdoptions ?? (() => listAdoptions(home)),
317
+ undoAdoption: options.undoAdoption ?? ((target) => undoAdoption(target, runtime)),
283
318
  listLocalAssets: options.listLocalAssets ?? (() => listLocalAssets(runtime)),
284
319
  knowledgeProblems: options.knowledgeProblems ?? (() => knowledgeProblems(runtime)),
285
320
  githubStatus: options.githubStatus ?? (() => githubStatus(runtime)),
@@ -292,6 +327,13 @@ export function createProgram(options = {}) {
292
327
  ((options) => moveLocalAssets(options, runtime)),
293
328
  updateImported: options.updateImported ??
294
329
  ((kind, name, options) => updateImported(kind, name, options, runtime)),
330
+ keepMcpValue: options.keepMcpValue ??
331
+ ((variable, value) => keepMcpValue(variable, value, runtime)),
332
+ forgetMcpValue: options.forgetMcpValue ??
333
+ ((variable) => forgetMcpValue(variable, runtime)),
334
+ listKeptValues: options.listKeptValues ?? (() => listKeptValues(runtime)),
335
+ showPackage: options.showPackage ??
336
+ ((kind, name, origin) => showPackage(kind, name, origin, runtime)),
295
337
  showMcp: options.showMcp ?? ((name, origin) => showMcp(name, origin, runtime)),
296
338
  createMcp: options.createMcp ?? ((input) => createMcp(input, runtime)),
297
339
  updateMcp: options.updateMcp ?? ((input) => updateMcp(input, runtime)),
@@ -376,10 +418,14 @@ export function createProgram(options = {}) {
376
418
  .showHelpAfterError(styleText("dim", "Add --help to any command to see its usage."))
377
419
  .addHelpText("after", `\nRun ${styleText("bold", "barndog <command> --help")} for details. Configuration: ${barndogPaths(home).settings}`)
378
420
  .addHelpText("afterAll", ({ command }) => options.setupMode ? unavailableHint(command, options.setupMode) : "")
379
- .action((_, command) => {
421
+ .action(async (_, command) => {
380
422
  if (command.args.length) {
381
423
  program.error(`error: unknown command '${command.args[0]}'`);
382
424
  }
425
+ // Setup needs a terminal; without one, help says to run `barndog init`.
426
+ if (mode.interactive && !(await context.isSetUp())) {
427
+ return context.setup(true);
428
+ }
383
429
  program.help();
384
430
  });
385
431
  program.hook("preAction", async (_, action) => {
@@ -405,6 +451,8 @@ export function createProgram(options = {}) {
405
451
  registerAuth(program, context);
406
452
  registerInit(program, context);
407
453
  registerSync(program, context);
454
+ registerHarnesses(program, context);
455
+ registerAdopt(program, context);
408
456
  registerStatus(program, context);
409
457
  registerEnvironment(program, context);
410
458
  registerCapabilities(program, context);
@@ -35,6 +35,41 @@ export async function ifExists(operation) {
35
35
  throw error;
36
36
  }
37
37
  }
38
+ /** Why a file named on the command line can't be read, by Node error code. */
39
+ const inputProblems = {
40
+ ENOENT: "doesn't exist",
41
+ EISDIR: "is a folder, not a file",
42
+ EACCES: "can't be read: permission denied",
43
+ EPERM: "can't be read: permission denied",
44
+ };
45
+ /**
46
+ * A file the person running the CLI named, such as `--file` or `--input`. A
47
+ * missing or unreadable one is a mistake they can fix, so it says which file.
48
+ */
49
+ export async function inputFile(path) {
50
+ try {
51
+ return await readFile(path);
52
+ }
53
+ catch (error) {
54
+ const problem = inputProblems[errorCode(error) ?? ""];
55
+ if (problem) {
56
+ throw new CliError(`${path} ${problem}.`, undefined, { cause: error });
57
+ }
58
+ throw error;
59
+ }
60
+ }
61
+ /** `inputFile()` parsed as JSON; invalid JSON says which file. */
62
+ export async function inputJson(path) {
63
+ const text = (await inputFile(path)).toString("utf8");
64
+ try {
65
+ return JSON.parse(text);
66
+ }
67
+ catch (error) {
68
+ throw new CliError(`${path} isn't valid JSON.`, undefined, {
69
+ cause: error,
70
+ });
71
+ }
72
+ }
38
73
  /** A file's text, or null when it doesn't exist. */
39
74
  export function readIfExists(path) {
40
75
  return ifExists(readFile(path, "utf8"));
@@ -1,44 +1,108 @@
1
1
  import { POSIX_MODE } from "./constants.js";
2
- import { mkdir, readFile, rm } from "node:fs/promises";
2
+ import { mkdir, readFile, rm, stat } from "node:fs/promises";
3
3
  import { dirname, join } from "node:path";
4
+ import { setTimeout as sleep } from "node:timers/promises";
4
5
  import { errorCode } from "./values.js";
5
6
  import { CliError } from "./cli-error.js";
6
- import { writeAtomic } from "./files.js";
7
+ import { ifExists, writeAtomic } from "./files.js";
7
8
  /**
8
- * Runs `run` while holding a lock across processes: a folder at `path` holding
9
- * the owner's PID. A lock whose process has died is taken over; liveness comes
10
- * from the PID, not from the lock's age, so a long operation never loses it.
9
+ * How long a lock may exist without a PID before it counts as left by a
10
+ * process that crashed between creating it and writing its PID. Writing the
11
+ * PID takes milliseconds.
11
12
  */
12
- export async function withPidLock(path, messages, run) {
13
- await mkdir(dirname(path), {
14
- recursive: true,
15
- mode: POSIX_MODE.privateDirectory,
16
- });
13
+ const STARTING_GRACE_MS = 10_000;
14
+ /** How long to wait while another process clears the same stale lock. */
15
+ const TAKEOVER_RETRY_MS = 50;
16
+ /** Attempts before giving up on a lock that keeps changing hands. */
17
+ const MAX_ATTEMPTS = 100;
18
+ async function ownerOf(path) {
19
+ const info = await ifExists(stat(path));
20
+ if (!info) {
21
+ return "free";
22
+ }
23
+ const text = await ifExists(readFile(join(path, "pid"), "utf8"));
24
+ const pid = Number(text ?? 0);
25
+ if (!Number.isSafeInteger(pid) || pid <= 0) {
26
+ return Date.now() - info.mtimeMs > STARTING_GRACE_MS ? "stale" : "starting";
27
+ }
28
+ try {
29
+ process.kill(pid, 0);
30
+ return "running";
31
+ }
32
+ catch (failure) {
33
+ // EPERM: the owner is alive but belongs to another user, so it still holds the lock.
34
+ return errorCode(failure) === "ESRCH" ? "stale" : "running";
35
+ }
36
+ }
37
+ /**
38
+ * Removes the lock at `path` if it is still stale. A short-lived guard folder
39
+ * makes the check and the removal one step, so a process that saw the same
40
+ * stale lock can't remove a fresh lock another process just took.
41
+ */
42
+ async function removeStale(path) {
43
+ const guard = `${path}.takeover`;
17
44
  try {
18
- await mkdir(path);
45
+ await mkdir(guard);
19
46
  }
20
47
  catch (error) {
21
48
  if (errorCode(error) !== "EEXIST") {
22
49
  throw error;
23
50
  }
24
- const pid = Number(await readFile(join(path, "pid"), "utf8").catch(() => "0"));
25
- if (!pid) {
26
- throw new CliError(messages.starting, undefined, { cause: error });
51
+ const info = await ifExists(stat(guard));
52
+ if (info && Date.now() - info.mtimeMs > STARTING_GRACE_MS) {
53
+ await rm(guard, { recursive: true, force: true });
54
+ }
55
+ else {
56
+ await sleep(TAKEOVER_RETRY_MS);
57
+ }
58
+ return;
59
+ }
60
+ try {
61
+ if ((await ownerOf(path)) === "stale") {
62
+ await rm(path, { recursive: true, force: true });
27
63
  }
64
+ }
65
+ finally {
66
+ await rm(guard, { recursive: true, force: true });
67
+ }
68
+ }
69
+ /** Creates the lock folder, taking over a stale one; throws when it is held. */
70
+ async function acquire(path, messages) {
71
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
28
72
  try {
29
- process.kill(pid, 0);
73
+ await mkdir(path, { mode: POSIX_MODE.privateDirectory });
74
+ return;
30
75
  }
31
- catch (failure) {
32
- // EPERM: the owner is alive but belongs to another user, so it still holds the lock.
33
- if (errorCode(failure) !== "ESRCH") {
34
- throw new CliError(messages.running, undefined, { cause: failure });
76
+ catch (error) {
77
+ if (errorCode(error) !== "EEXIST") {
78
+ throw error;
79
+ }
80
+ const owner = await ownerOf(path);
81
+ if (owner === "starting") {
82
+ throw new CliError(messages.starting, undefined, { cause: error });
83
+ }
84
+ if (owner === "running") {
85
+ throw new CliError(messages.running, undefined, { cause: error });
86
+ }
87
+ if (owner === "stale") {
88
+ await removeStale(path);
35
89
  }
36
- // Another process may have cleared the same stale lock first.
37
- await rm(path, { recursive: true, force: true });
38
- return withPidLock(path, messages, run);
39
90
  }
40
- throw new CliError(messages.running, undefined, { cause: error });
41
91
  }
92
+ throw new CliError(messages.running);
93
+ }
94
+ /**
95
+ * Runs `run` while holding a lock across processes: a folder at `path` holding
96
+ * the owner's PID. A lock whose process has died, or that never got a PID, is
97
+ * taken over; liveness comes from the PID, not from the lock's age, so a long
98
+ * operation never loses it.
99
+ */
100
+ export async function withPidLock(path, messages, run) {
101
+ await mkdir(dirname(path), {
102
+ recursive: true,
103
+ mode: POSIX_MODE.privateDirectory,
104
+ });
105
+ await acquire(path, messages);
42
106
  try {
43
107
  await writeAtomic(join(path, "pid"), String(process.pid));
44
108
  return await run();
@@ -22,6 +22,14 @@ export const NAME = /^[a-z\d]+(?:-[a-z\d]+)*$/;
22
22
  * most 64 characters.
23
23
  */
24
24
  export const validAssetName = (name) => NAME.test(name) && name.length <= MAX_ASSET_NAME_LENGTH;
25
+ /**
26
+ * An MCP server name as coding tools accept it: letters, digits, `_` and `-`,
27
+ * such as `my_server` or `GitHub`. Tools name its tools after it
28
+ * (`mcp__my_server__search`), so BarnDog keeps it as written.
29
+ */
30
+ export const MCP_NAME = /^[\w-]+$/;
31
+ /** Whether `name` can be an MCP server's name: {@link MCP_NAME}, at most 64 characters. */
32
+ export const validMcpName = (name) => MCP_NAME.test(name) && name.length <= MAX_ASSET_NAME_LENGTH;
25
33
  /** Turns any text into a {@link NAME}-shaped slug: `Team A/Review!` → `team-a-review`. */
26
34
  export function slugify(text) {
27
35
  return text
@@ -3,8 +3,6 @@ export const posixQuote = (value) => "'" + value.replaceAll("'", "'\\''") + "'";
3
3
  /**
4
4
  * Text the shell reads as one word without quotes: `claude`, `v1.2-rc`, but
5
5
  * not `a b`, `$HOME` or `/usr/bin`.
6
- *
7
- * @internal
8
6
  */
9
7
  export const PLAIN_WORD = /^[\w.-]+$/;
10
8
  /** One POSIX shell word, quoted only when it needs to be. */
@@ -2,6 +2,7 @@
2
2
  import { GIT_MODE } from "../features/workspace/snapshot.js";
3
3
  import { basename } from "node:path";
4
4
  import { CliError } from "../errors.js";
5
+ import { readSettings } from "../config/settings.js";
5
6
  import { adapters, hookHarnesses, isHookHarness, } from "../harnesses/registry.js";
6
7
  import { buildHookPackage, discoverHooks, plainCommand, } from "../features/imports/discover.js";
7
8
  import { adaptHook, toolNames } from "../features/hooks/adapt.js";
@@ -19,7 +20,12 @@ async function pickHookPlan(draft, executable, context) {
19
20
  const { prompts } = context;
20
21
  // Choices made for one coding tool start out selected for the next.
21
22
  const carried = new Map();
22
- const chosen = (await prompts.chooseMany("Which coding tools should this Hook support?", hookHarnesses.map((h) => ({ name: adapters[h].name, value: h })))).filter(isHookHarness);
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);
23
29
  const plan = {};
24
30
  for (const harness of chosen) {
25
31
  const known = adapters[harness].hooks.events;
@@ -107,7 +113,7 @@ export async function addHook(url, options, context) {
107
113
  }
108
114
  const location = parseLocation(url);
109
115
  const fallback = slugify(basename(url.replace(/\/$/, "").replace(/\.git$/, ""))) || "hook";
110
- await fetchRemote(location, { allowPrompt: true }, async (remote) => {
116
+ await fetchRemote(location, { allowPrompt: context.interactive }, async (remote) => {
111
117
  const { candidates, skipped } = discoverHooks(remote, fallback);
112
118
  for (const skip of skipped) {
113
119
  context.write(`${warn("!")} ${skip.path}: ${skip.reason}`);
@@ -1,15 +1,18 @@
1
1
  /** `barndog mcp add`: brings MCP servers from JSON or a coding tool into the local workspace. */
2
2
  import { localPath } from "../platform.js";
3
3
  import { CliError } from "../errors.js";
4
- import { addMcpServers, conflictingEntries, convertServer, harnessServers, parseMcpText, } from "../features/mcps/import.js";
5
- import { readFile } from "node:fs/promises";
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";
6
9
  import { bold, dim, ok, warn } from "./format.js";
7
10
  async function serversToAdd(name, options, context) {
8
11
  if (options.config) {
9
12
  return parseMcpText(options.config, name);
10
13
  }
11
14
  if (options.file) {
12
- return parseMcpText(await readFile(localPath(options.file, context.runtime), "utf8"), name);
15
+ return parseMcpText((await inputFile(localPath(options.file, context.runtime))).toString("utf8"), name);
13
16
  }
14
17
  const fromHarness = async () => {
15
18
  const all = (await harnessServers(context.runtime)).filter((s) => !options.from || s.harness === options.from);
@@ -55,6 +58,59 @@ async function serversToAdd(name, options, context) {
55
58
  ? parseMcpText(await context.prompts.paste(), name)
56
59
  : fromHarness();
57
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
+ }
58
114
  /**
59
115
  * `mcp add`: imports MCP servers from a harness's configuration or pasted JSON
60
116
  * into the local workspace.
@@ -64,7 +120,7 @@ export async function addMcp(name, options, context) {
64
120
  if (name?.trimStart().startsWith("{")) {
65
121
  throw new CliError("That looks like the configuration, not a name.", "barndog mcp add <name> --config '<json>'");
66
122
  }
67
- const imported = await serversToAdd(name, options, context);
123
+ const imported = await namedServers(await serversToAdd(name, options, context), options.as, context);
68
124
  const oauth = new Set();
69
125
  for (const { name: server, server: raw } of imported) {
70
126
  if (options.oauth ||
@@ -94,13 +150,20 @@ export async function addMcp(name, options, context) {
94
150
  throw new CliError("Nothing was added.");
95
151
  }
96
152
  }
97
- const result = await addMcpServers(servers, { replace }, context.runtime);
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);
98
155
  for (const added of result.added) {
99
156
  context.write(`${ok("✔")} Added ${bold(added)}`);
100
157
  }
101
158
  for (const note of result.notes) {
102
- context.write(`${warn("!")} ${note}`);
159
+ context.write(`${warn("!")} ${bold(note.server)}: ${note.text}`);
103
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
+ });
104
167
  for (const backup of result.backups) {
105
168
  context.write(dim(`Backup: ${backup}`));
106
169
  }
@@ -9,11 +9,12 @@ import { defined } from "../shared/lookup.js";
9
9
  import { finish, folderLabel, assertDistinctNames, notFound, onlyChosen, updateMode, } from "./add-asset.js";
10
10
  /** Stops two copies of a Skill from claiming the same name, saying which folders hold them. */
11
11
  /** A plain folder is read in place; everything else is fetched with Git. */
12
- async function withSkillSource(source, folder, runtime, use) {
13
- if (folder) {
14
- return use(await readFolder(folder, runtime));
12
+ async function withSkillSource(source, runtime, use) {
13
+ if (source.folder) {
14
+ return use(await readFolder(source.folder, runtime));
15
15
  }
16
- return fetchRemote(parseLocation(source), { allowPrompt: true }, use, runtime);
16
+ // Git may ask for credentials only when someone is there to answer.
17
+ return fetchRemote(parseLocation(source.location), { allowPrompt: source.interactive }, use, runtime);
17
18
  }
18
19
  function assertFolderOptions(options, folder) {
19
20
  if (!folder && (options.copy || options.move)) {
@@ -51,7 +52,8 @@ export async function addSkills(url, options, context) {
51
52
  assertSourceExists(url, context.runtime);
52
53
  const folder = await plainFolder(url, context.runtime);
53
54
  assertFolderOptions(options, folder);
54
- await withSkillSource(url, folder, context.runtime, async (remote) => {
55
+ const source = { location: url, folder, interactive: context.interactive };
56
+ await withSkillSource(source, context.runtime, async (remote) => {
55
57
  const { skills, skipped } = discoverSkills(remote);
56
58
  for (const skip of skipped) {
57
59
  context.write(`${warn("!")} ${skip.path}: ${skip.reason}`);