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,369 @@
1
+ import { POSIX_MODE } from "../../shared/constants.js";
2
+ import { readState } from "../../config/state.js";
3
+ import { mkdir, readFile, readdir } from "node:fs/promises";
4
+ import { randomUUID } from "node:crypto";
5
+ import { basename, join } from "node:path";
6
+ import { mcpDefinitionSchema, } from "@barndog-ai/api-contract";
7
+ import { parse as parseJsonc } from "jsonc-parser";
8
+ import { parse as parseToml } from "smol-toml";
9
+ import { stringify } from "yaml";
10
+ import { readSettings, SetupRequiredError } from "../../config/settings.js";
11
+ import { CliError } from "../../errors.js";
12
+ import { adapters, harnesses, nativeFile, } from "../../harnesses/registry.js";
13
+ import { locked } from "../environment/transaction.js";
14
+ import { fileText, ifExists, writeAtomic } from "../../shared/files.js";
15
+ import { synchronize } from "../environment/sync.js";
16
+ import { patchNative } from "../native/configuration.js";
17
+ import { validMcpName, VARIABLE_NAME } from "../../shared/patterns.js";
18
+ import { assetKinds } from "../asset-kinds/index.js";
19
+ import { LOCAL_ORIGIN } from "../workspace/overlay.js";
20
+ import { ensureLocalWorkspace } from "../imports/local.js";
21
+ import { updateSecrets } from "../secrets/index.js";
22
+ import { asRecord, asStrings, isRecord } from "../../shared/values.js";
23
+ import { barndogPaths } from "../../config/paths.js";
24
+ /** Random characters that keep two backups of one file taken in the same millisecond apart. */
25
+ const BACKUP_SUFFIX_LENGTH = 8;
26
+ const isServer = (value) => isRecord(value) &&
27
+ ("command" in value || "url" in value || "httpUrl" in value);
28
+ /** Accepts the shapes people copy: a harness's whole file, a name map, or one server. */
29
+ export function parseMcpText(text, name) {
30
+ let value;
31
+ try {
32
+ value = JSON.parse(text);
33
+ }
34
+ catch (error) {
35
+ throw new CliError("That isn't valid JSON.", undefined, { cause: error });
36
+ }
37
+ if (isServer(value)) {
38
+ if (!name) {
39
+ throw new CliError("This JSON is one server without a name.", "barndog mcp add <name> --file <path>");
40
+ }
41
+ return [{ name, server: value }];
42
+ }
43
+ const object = asRecord(value);
44
+ const map = asRecord(object.mcpServers ?? object.servers ?? object);
45
+ const servers = Object.entries(map).flatMap(([key, server]) => isServer(server) ? [{ key, server }] : []);
46
+ if (!servers.length) {
47
+ throw new CliError("No MCP servers found in that JSON. Each one needs a command or url.");
48
+ }
49
+ if (name && servers.length > 1 && !servers.some(({ key }) => key === name)) {
50
+ throw new CliError(`No MCP server named ${name} in that JSON. It has ${servers.map(({ key }) => key).join(", ")}.`, "Run it again with one of those names");
51
+ }
52
+ return servers
53
+ .filter(({ key }) => !name || servers.length === 1 || key === name)
54
+ .map(({ key, server }) => ({
55
+ name: servers.length === 1 && name ? name : key,
56
+ server,
57
+ }));
58
+ }
59
+ /** A braced variable reference, `${API_KEY}` (Claude Code) or `${env:API_KEY}` (Cursor). */
60
+ const BRACED_VARIABLE = new RegExp(String.raw `\$\{(?:env:)?(${VARIABLE_NAME.source})\}`);
61
+ /** A whole value that is one variable reference, braced or bare (`$API_KEY`). */
62
+ const WHOLE_VARIABLE = new RegExp(String.raw `^(?:${BRACED_VARIABLE.source}|\$(${VARIABLE_NAME.source}))$`);
63
+ /**
64
+ * The variable a whole value refers to: `${env:TOKEN}` or `$TOKEN` → `TOKEN`.
65
+ *
66
+ * @internal Exported for its table test in `src/tests/patterns.test.ts`.
67
+ */
68
+ export const variableName = (value) => {
69
+ const [, braced, bare] = WHOLE_VARIABLE.exec(value) ?? [];
70
+ return braced ?? bare;
71
+ };
72
+ /**
73
+ * The first braced variable inside a value: `Bearer ${TOKEN}` → `TOKEN`.
74
+ *
75
+ * @internal Exported for its table test in `src/tests/patterns.test.ts`.
76
+ */
77
+ export const embeddedVariable = (value) => BRACED_VARIABLE.exec(value)?.[1];
78
+ /**
79
+ * An environment variable name made from any text: `my-server_x-api` → `MY_SERVER_X_API`.
80
+ *
81
+ * @internal Exported for its table test in `src/tests/patterns.test.ts`.
82
+ */
83
+ export const envName = (text) => text.toUpperCase().replace(/[^\dA-Z_]/g, "_");
84
+ /** Words that suggest a credential: `--api-key`, `apikey=`, `TOKEN`, `password`. */
85
+ const SECRET_WORD = /api[-_]?key|token|secret|password/i;
86
+ /**
87
+ * Whether a command-line argument may hold a credential: a secret-sounding word, or an `sk-` key.
88
+ *
89
+ * @internal Exported for its table test in `src/tests/patterns.test.ts`.
90
+ */
91
+ export const looksSecret = (arg) => SECRET_WORD.test(arg) || arg.startsWith("sk-");
92
+ /**
93
+ * What to tell the developer about each literal: where BarnDog keeps it, or
94
+ * which variable to set. `kept` holds the variables BarnDog keeps.
95
+ */
96
+ export function literalNotes(literals, kept) {
97
+ return literals.map((literal) => kept.includes(literal.variable)
98
+ ? `BarnDog keeps the value of ${literal.variable} in ~/.barndog/secrets.json on this machine, never uploaded, and writes it into your coding tools.`
99
+ : `${literal.key} held a literal value, which BarnDog doesn't keep. Set ${literal.variable} in your environment, or keep it with barndog mcp env set ${literal.variable}.`);
100
+ }
101
+ /** Secrets are named, never shared: every literal becomes a variable the definition refers to. */
102
+ function reference(key, value, fallback, found) {
103
+ const text = String(value);
104
+ const whole = variableName(text);
105
+ if (whole) {
106
+ return { secretRef: whole };
107
+ }
108
+ const inside = embeddedVariable(text);
109
+ if (inside) {
110
+ found.notes.push(`${key} mixes text with ${inside}. Set ${inside} to the complete value of ${key}, including that text.`);
111
+ return { secretRef: inside };
112
+ }
113
+ found.literals.push({ key, variable: fallback, value: text });
114
+ return { secretRef: fallback };
115
+ }
116
+ /**
117
+ * Converts environment and header values to local secret references. Command
118
+ * arguments and URLs are preserved, so the result is not guaranteed to be free
119
+ * of secrets.
120
+ */
121
+ /** An HTTP server's address, as `url` or Gemini's `httpUrl`; a stdio server has none. */
122
+ function serverUrl(name, server) {
123
+ const address = server.url ?? server.httpUrl;
124
+ if (address !== undefined && typeof address !== "string") {
125
+ throw new CliError(`${name} can't be added: its url must be text, such as "https://example.com/mcp".`);
126
+ }
127
+ return address;
128
+ }
129
+ export function convertServer({ name, server }, description, oauth) {
130
+ const notes = [];
131
+ const literals = [];
132
+ const found = { notes, literals };
133
+ const type = typeof server.type === "string" ? server.type : undefined;
134
+ if (type === "sse" || type === "ws") {
135
+ throw new CliError(`${name} uses ${type} transport. BarnDog supports stdio and HTTP servers.`);
136
+ }
137
+ const url = serverUrl(name, server);
138
+ const common = {
139
+ description: description ??
140
+ (typeof server.description === "string" && server.description.trim()
141
+ ? server.description
142
+ : `${name} MCP server`),
143
+ };
144
+ let candidate;
145
+ if (url) {
146
+ const headers = {};
147
+ for (const [key, value] of Object.entries(asRecord(server.headers ?? server.http_headers))) {
148
+ headers[key] = reference(key, value, envName(`${name}_${key}`), found);
149
+ }
150
+ for (const [key, value] of Object.entries(asRecord(server.env_http_headers))) {
151
+ if (typeof value === "string") {
152
+ headers[key] = { secretRef: value };
153
+ }
154
+ }
155
+ if (typeof server.bearer_token_env_var === "string") {
156
+ headers.Authorization = { secretRef: server.bearer_token_env_var };
157
+ notes.push(`Set ${server.bearer_token_env_var} to the whole Authorization value, including "Bearer ".`);
158
+ }
159
+ // Claude Code writes `oauth` and Cursor writes `auth` for servers that sign in natively.
160
+ const signsIn = oauth || !!server.oauth || !!server.auth;
161
+ if (signsIn) {
162
+ notes.push(`Sign in once it's added: barndog mcp auth ${name} --origin ${LOCAL_ORIGIN} --harness <tool>`);
163
+ }
164
+ candidate = {
165
+ ...common,
166
+ transport: "http",
167
+ url,
168
+ headers,
169
+ authentication: httpAuthentication(signsIn, headers),
170
+ };
171
+ }
172
+ else {
173
+ if (oauth) {
174
+ throw new CliError(`${name} runs as a local command, and only HTTP servers sign in with OAuth.`);
175
+ }
176
+ const environment = {};
177
+ for (const [key, value] of Object.entries(asRecord(server.env))) {
178
+ environment[key] = reference(key, value, key, found);
179
+ }
180
+ for (const key of asStrings(server.env_vars)) {
181
+ environment[key] = { secretRef: key };
182
+ }
183
+ const listed = Array.isArray(server.args) ? server.args : [];
184
+ const args = listed.map(String);
185
+ if (args.some(looksSecret)) {
186
+ notes.push("An argument looks like it may hold a secret. Arguments are stored as written, so check them before sharing this.");
187
+ }
188
+ candidate = {
189
+ ...common,
190
+ transport: "stdio",
191
+ command: server.command,
192
+ args,
193
+ environment,
194
+ authentication: Object.keys(environment).length ? "environment" : "none",
195
+ };
196
+ }
197
+ const parsed = mcpDefinitionSchema.safeParse(candidate);
198
+ if (!parsed.success) {
199
+ throw new CliError(`${name} can't be added: ${parsed.error.issues.map((issue) => `${issue.path.join(".") || "server"}: ${issue.message}`).join("; ")}`);
200
+ }
201
+ return { name, definition: parsed.data, notes, literals };
202
+ }
203
+ /** How an imported HTTP server authenticates. */
204
+ function httpAuthentication(signsIn, headers) {
205
+ if (signsIn) {
206
+ return "native-oauth";
207
+ }
208
+ return Object.keys(headers).length ? "environment" : "none";
209
+ }
210
+ async function jsonFile(path) {
211
+ const text = await fileText(path).catch(() => null);
212
+ return text ? asRecord(parseJsonc(text)) : {};
213
+ }
214
+ /** Servers each harness has configured, leaving out the ones BarnDog installed. */
215
+ export async function harnessServers(runtime) {
216
+ const { home } = runtime;
217
+ const { native } = await readState(home);
218
+ const owned = new Set(native
219
+ .filter((entry) => entry.kind === "mcp")
220
+ .map((entry) => `${entry.file}:${entry.key}`));
221
+ const found = [];
222
+ const add = (harness, source, servers) => {
223
+ const { imported } = adapters[harness].mcp;
224
+ for (const [name, entry] of Object.entries(asRecord(servers))) {
225
+ if (!isRecord(entry) || owned.has(`${source.file}:${name}`)) {
226
+ continue;
227
+ }
228
+ const server = imported ? imported(entry) : entry;
229
+ if (isServer(server)) {
230
+ found.push({ harness, ...source, name, server, native: entry });
231
+ }
232
+ }
233
+ };
234
+ const claudeFile = nativeFile("claude", "mcp", home);
235
+ const claude = await jsonFile(claudeFile);
236
+ add("claude", { label: adapters.claude.name, file: claudeFile }, claude.mcpServers);
237
+ for (const [project, value] of Object.entries(asRecord(claude.projects))) {
238
+ add("claude", {
239
+ label: `${adapters.claude.name}, ${basename(project)} project`,
240
+ file: claudeFile,
241
+ }, asRecord(value).mcpServers);
242
+ }
243
+ const cursorFile = nativeFile("cursor", "mcp", home);
244
+ add("cursor", { label: adapters.cursor.name, file: cursorFile }, (await jsonFile(cursorFile)).mcpServers);
245
+ const codexFile = nativeFile("codex", "mcp", home);
246
+ const codex = await fileText(codexFile).catch(() => null);
247
+ if (codex) {
248
+ let settings;
249
+ try {
250
+ settings = parseToml(codex);
251
+ }
252
+ catch (error) {
253
+ throw new CliError(`${codexFile} isn't valid TOML, so BarnDog can't read the MCP servers in it.`, `Fix ${codexFile}, then try again`, { cause: error });
254
+ }
255
+ add("codex", { label: adapters.codex.name, file: codexFile }, settings.mcp_servers);
256
+ }
257
+ const { mcp } = adapters.opencode;
258
+ for (const relative of mcp.files) {
259
+ const file = join(home, relative);
260
+ add("opencode", { label: `${adapters.opencode.name}, ${basename(file)}`, file }, mcp.path.reduce((value, key) => asRecord(value)[key], await jsonFile(file)));
261
+ }
262
+ return found;
263
+ }
264
+ /** Native entries BarnDog doesn't own that would block installing this name. */
265
+ export async function conflictingEntries(name, runtime) {
266
+ const { home } = runtime;
267
+ const settings = await readSettings(home);
268
+ if (!settings) {
269
+ throw new SetupRequiredError();
270
+ }
271
+ const servers = await harnessServers(runtime);
272
+ const selected = harnesses.filter((h) => settings.harnesses.includes(h));
273
+ return servers
274
+ .filter((entry) => entry.name === name &&
275
+ selected.includes(entry.harness) &&
276
+ !entry.label.includes("project"))
277
+ .map((entry) => ({
278
+ harness: entry.harness,
279
+ file: entry.file,
280
+ server: entry.native,
281
+ }));
282
+ }
283
+ /**
284
+ * The local MCP server named `name`, ignoring case: macOS and Windows disks
285
+ * usually treat `Docs.yaml` and `docs.yaml` as one file. Null when none is.
286
+ */
287
+ export async function localMcpNamed(name, runtime) {
288
+ const settings = await readSettings(runtime.home);
289
+ const folder = settings?.localWorkspace
290
+ ? join(settings.localWorkspace.path, "org", assetKinds.mcp.folder)
291
+ : null;
292
+ const files = folder ? ((await ifExists(readdir(folder))) ?? []) : [];
293
+ const names = files
294
+ .filter((file) => file.endsWith(".yaml"))
295
+ .map((file) => file.slice(0, -".yaml".length));
296
+ return (names.find((other) => other.toLowerCase() === name.toLowerCase()) ?? null);
297
+ }
298
+ /**
299
+ * Writes converted MCP servers and synchronizes them. Existing local workspace
300
+ * names are always rejected; replace permits backing up and removing
301
+ * conflicting native entries.
302
+ */
303
+ export async function addMcpServers(servers, options, runtime) {
304
+ const { home } = runtime;
305
+ const invalid = servers.filter(({ name }) => !validMcpName(name));
306
+ if (invalid.length) {
307
+ throw new CliError(`${invalid.map(({ name }) => name).join(", ")} can't be used as ${invalid.length === 1 ? "an MCP name" : "MCP names"}. ${assetKinds.mcp.nameRule}.`, "barndog mcp add <name> --as <new-name>");
308
+ }
309
+ return locked(runtime, async () => {
310
+ const workspace = await ensureLocalWorkspace(runtime);
311
+ for (const { name } of servers) {
312
+ const existing = await localMcpNamed(name, runtime);
313
+ if (existing !== null) {
314
+ throw new CliError(existing === name
315
+ ? `A local MCP server named ${name} already exists.`
316
+ : `${name} differs from the local MCP server ${existing} only in case, and they'd share one file on this disk.`, `barndog mcp add ${name} --as <new-name>`);
317
+ }
318
+ const conflicts = await conflictingEntries(name, runtime);
319
+ if (conflicts.length && !options.replace) {
320
+ throw new CliError(`${name} is already configured in ${conflicts.map((c) => c.file).join(" and ")}. Replacing it is required for BarnDog to manage it.`, `barndog mcp add ${name} --replace`);
321
+ }
322
+ }
323
+ // One backup per settings file, taken before its first change, so a file
324
+ // that holds several of the servers is backed up as the user left it.
325
+ const backedUp = new Set();
326
+ const backups = [];
327
+ for (const { name, definition } of servers) {
328
+ for (const conflict of await conflictingEntries(name, runtime)) {
329
+ const text = await readFile(conflict.file, "utf8");
330
+ if (!backedUp.has(conflict.file)) {
331
+ const backup = join(barndogPaths(home).migrations, `${basename(conflict.file)}-${Date.now()}-${randomUUID().slice(0, BACKUP_SUFFIX_LENGTH)}.bak`);
332
+ await writeAtomic(backup, text);
333
+ backedUp.add(conflict.file);
334
+ backups.push(backup);
335
+ }
336
+ await writeAtomic(conflict.file, patchNative(text, [
337
+ {
338
+ id: "import",
339
+ kind: "mcp",
340
+ harness: conflict.harness,
341
+ file: conflict.file,
342
+ key: name,
343
+ value: conflict.server,
344
+ },
345
+ ], []));
346
+ }
347
+ // The workspace's own folders keep default permissions; writeAtomic would make them private.
348
+ await mkdir(join(workspace.path, "org/mcp"), { recursive: true });
349
+ await writeAtomic(join(workspace.path, "org/mcp", `${name}.yaml`), stringify(definition), { mode: POSIX_MODE.regularFile });
350
+ }
351
+ // Saved before the sync, which writes them into the tools' settings.
352
+ const kept = servers.flatMap((s) => s.literals.filter((literal) => options.keep.includes(literal.variable)));
353
+ if (kept.length) {
354
+ await updateSecrets(Object.fromEntries(kept.map((l) => [l.variable, l.value])), runtime);
355
+ }
356
+ const events = await synchronize(undefined, runtime, undefined, {
357
+ prompt: false,
358
+ });
359
+ return {
360
+ added: servers.map((s) => s.name),
361
+ notes: servers.flatMap((s) => [...s.notes, ...literalNotes(s.literals, options.keep)].map((text) => ({
362
+ server: s.name,
363
+ text,
364
+ }))),
365
+ backups,
366
+ events,
367
+ };
368
+ });
369
+ }
@@ -1,56 +1,102 @@
1
- import { homedir } from "node:os";
2
- import { readFile, mkdir } from "node:fs/promises";
3
- import { join } from "node:path";
1
+ import { localPath } from "../../platform.js";
2
+ import { POSIX_MODE } from "../../shared/constants.js";
3
+ import { readState } from "../../config/state.js";
4
+ import { mkdir } from "node:fs/promises";
4
5
  import { randomUUID } from "node:crypto";
5
- import { spawn } from "node:child_process";
6
+ import crossSpawn from "cross-spawn";
6
7
  import { z } from "zod";
7
8
  import { mcpDefinitionSchema, mcpSchema, mcpVersionSchema, } from "@barndog-ai/api-contract";
8
- import { connection, selectOrigin } from "../collaboration/remote.js";
9
- import { request, selectAsset } from "../environment/remote.js";
9
+ import { selectOrigin } from "../server/origin.js";
10
+ import { connection } from "../server/connection.js";
11
+ import { selectAsset } from "../server/catalog.js";
12
+ import { parsed } from "../server/client.js";
10
13
  import { readSettings } from "../../config/settings.js";
11
- import { repoForOrigin, selectRepoAsset } from "../git-workspace/assets.js";
12
- import { gitHistory } from "../collaboration/workspace-git.js";
13
- import { patchNative, nativeFile, } from "../native/configuration.js";
14
- import { fileText } from "../environment/transaction.js";
15
- export async function writeMcp(name, origin, file, home = homedir(), key = randomUUID(), expectedVersionId) {
16
- const conn = await connection(home), scope = await selectOrigin(origin, conn, home);
17
- const definition = mcpDefinitionSchema.parse(JSON.parse(await readFile(file, "utf8")));
18
- if (expectedVersionId) {
19
- const selected = await selectAsset("mcp", name, origin, home);
20
- return request(conn, `/v1/mcps/${selected.reference.id}/versions`, mcpSchema, home, "POST", {
14
+ import { repoForOrigin, selectRepoAsset, showRepoAsset, } from "../workspace/assets.js";
15
+ import { gitVersions } from "../collaboration/workspace-git.js";
16
+ import { adapters } from "../../harnesses/registry.js";
17
+ import { patchNative } from "../native/configuration.js";
18
+ import { fileText, inputJson } from "../../shared/files.js";
19
+ import { defined } from "../../shared/lookup.js";
20
+ import { CliError, friendlyMessage } from "../../errors.js";
21
+ import { barndogPaths } from "../../config/paths.js";
22
+ import { apiClient } from "../auth/transport.js";
23
+ async function readDefinition(file, runtime) {
24
+ const result = mcpDefinitionSchema.safeParse(await inputJson(localPath(file, runtime)));
25
+ if (!result.success) {
26
+ throw new CliError(`${file} isn't an MCP definition: ${friendlyMessage(result.error)}.`, "Check the fields against the MCP definition format at barndog.dev/docs", { cause: result.error });
27
+ }
28
+ return result.data;
29
+ }
30
+ /** Publishes a new MCP configuration in a scope. */
31
+ export async function createMcp(input, runtime) {
32
+ const conn = await connection(runtime);
33
+ const scope = await selectOrigin(input.origin, conn, runtime);
34
+ const definition = await readDefinition(input.file, runtime);
35
+ return parsed(mcpSchema, apiClient(conn.server, runtime).POST("/v1/mcps", {
36
+ body: {
37
+ name: input.name,
38
+ origin: { type: scope.type, id: scope.id },
39
+ definition,
40
+ idempotencyKey: input.key ?? randomUUID(),
41
+ },
42
+ }));
43
+ }
44
+ /** Publishes a new revision of an MCP configuration, against the inspected version. */
45
+ export async function updateMcp(input, runtime) {
46
+ const conn = await connection(runtime);
47
+ await selectOrigin(input.origin, conn, runtime);
48
+ const definition = await readDefinition(input.file, runtime);
49
+ const selected = await selectAsset("mcp", input.name, input.origin, runtime);
50
+ return parsed(mcpSchema, apiClient(conn.server, runtime).POST("/v1/mcps/{id}/versions", {
51
+ params: { path: { id: selected.reference.id } },
52
+ body: {
21
53
  definition,
22
- expectedVersionId: z.uuidv4().parse(expectedVersionId),
23
- idempotencyKey: key,
24
- });
54
+ expectedVersionId: z.uuidv4().parse(input.expectedVersion),
55
+ idempotencyKey: input.key ?? randomUUID(),
56
+ },
57
+ }));
58
+ }
59
+ /** One MCP configuration with its definition, from the repo or the server. */
60
+ export async function showMcp(name, origin, runtime) {
61
+ const { home } = runtime;
62
+ const settings = await readSettings(home);
63
+ const repo = settings && repoForOrigin(settings, runtime, origin);
64
+ if (repo) {
65
+ return showRepoAsset(selectRepoAsset(await repo.model(), "mcp", name, origin));
25
66
  }
26
- return request(conn, "/v1/mcps", mcpSchema, home, "POST", {
27
- name,
28
- origin: { type: scope.type, id: scope.id },
29
- definition,
30
- idempotencyKey: key,
31
- });
67
+ return (await selectAsset("mcp", name, origin, runtime)).asset;
32
68
  }
33
- export async function mcpVersions(name, origin, home = homedir()) {
69
+ export async function mcpVersions(name, origin, runtime) {
70
+ const { home } = runtime;
34
71
  const settings = await readSettings(home);
35
- if (settings?.version === 2 && settings.gitWorkspace)
36
- return gitHistory(settings.gitWorkspace, "versions", { name, origin, kind: "mcp" }, home);
37
- const selected = await selectAsset("mcp", name, origin, home);
38
- return request(selected.connection, `/v1/mcps/${selected.reference.id}/versions`, z.array(mcpVersionSchema), home);
72
+ if (settings?.gitWorkspace) {
73
+ return gitVersions(settings.gitWorkspace, { name, origin, kind: "mcp" }, runtime);
74
+ }
75
+ const selected = await selectAsset("mcp", name, origin, runtime);
76
+ return parsed(z.array(mcpVersionSchema), apiClient(selected.connection.server, runtime).GET("/v1/mcps/{id}/versions", {
77
+ params: { path: { id: selected.reference.id } },
78
+ }));
39
79
  }
40
- export async function authenticateMcp(name, origin, harness, home = homedir()) {
80
+ /**
81
+ * Guides MCP authentication or starts the native harness login command;
82
+ * credentials remain in native storage.
83
+ */
84
+ export async function authenticateMcp(name, origin, harness, runtime) {
85
+ const { home } = runtime;
41
86
  const settings = await readSettings(home);
42
- const repo = settings && repoForOrigin(settings, home, origin);
87
+ const repo = settings && repoForOrigin(settings, runtime, origin);
43
88
  const asset = repo
44
89
  ? await (async () => {
45
90
  const found = selectRepoAsset(await repo.model(), "mcp", name, origin);
46
91
  return {
47
92
  id: found.id,
48
93
  name: found.name,
49
- definition: found.definition,
94
+ definition: defined(found.definition, `${found.name} has no MCP definition`),
50
95
  };
51
96
  })()
52
97
  : await (async () => {
53
- const selected = await selectAsset("mcp", name, origin, home), parsed = mcpSchema.parse(selected.asset);
98
+ const selected = await selectAsset("mcp", name, origin, runtime);
99
+ const parsed = mcpSchema.parse(selected.asset);
54
100
  return {
55
101
  id: parsed.id,
56
102
  name: parsed.name,
@@ -70,32 +116,40 @@ export async function authenticateMcp(name, origin, harness, home = homedir()) {
70
116
  .join(", ")}. Credential values are never uploaded.`,
71
117
  };
72
118
  }
73
- const state = JSON.parse((await fileText(join(home, ".barndog/state.json"))) ?? "{}");
74
- if (!Array.isArray(state.native) ||
75
- !state.native.some((e) => e.id === asset.id && e.kind === "mcp" && e.harness === harness))
76
- throw new Error("Install and enable this MCP for the selected harness before authenticating");
77
- const entry = state.native.find((e) => e.id === asset.id && e.kind === "mcp" && e.harness === harness);
78
- if (entry.file !== nativeFile(harness, "mcp", home))
79
- throw new Error("Invalid native installation state");
119
+ const { native } = await readState(home);
120
+ const installed = native.find((e) => e.id === asset.id && e.kind === "mcp" && e.harness === harness);
121
+ if (!installed) {
122
+ throw new CliError(`${asset.name} isn't installed and enabled for ${harness}.`, `barndog mcp install ${asset.name}`);
123
+ }
124
+ const entry = { ...installed, kind: "mcp", harness };
80
125
  patchNative(await fileText(entry.file), [entry], [entry]);
81
- if (harness === "cursor")
126
+ const { name: tool, mcp } = adapters[harness];
127
+ if ("settings" in mcp.login) {
82
128
  return {
83
- message: `Open Cursor → Settings → MCP and authenticate ${asset.name}. Cursor manages this login locally.`,
129
+ message: `Open ${tool} → ${mcp.login.settings} and authenticate ${installed.key}. ${tool} manages this login locally.`,
84
130
  };
85
- const cwd = join(home, ".barndog/native-auth");
86
- await mkdir(cwd, { recursive: true, mode: 0o700 });
87
- const command = harness === "claude" ? "claude" : "codex";
88
- const child = spawn(command, ["mcp", "login", asset.name], {
131
+ }
132
+ const [command, ...loginArguments] = mcp.login.command;
133
+ const login = mcp.login.command.join(" ");
134
+ if (!command) {
135
+ throw new Error(`The ${tool} adapter has an empty MCP login command`);
136
+ }
137
+ const cwd = barndogPaths(home).nativeAuth;
138
+ await mkdir(cwd, { recursive: true, mode: POSIX_MODE.privateDirectory });
139
+ // cross-spawn also starts Windows .cmd shims, such as an npm-installed claude.
140
+ // The installed key differs from the asset's name after a clash rename.
141
+ const child = crossSpawn(command, [...loginArguments, installed.key], {
89
142
  cwd,
90
143
  stdio: "inherit",
91
- env: process.env,
144
+ env: { ...runtime.env },
92
145
  });
93
146
  const code = await new Promise((resolve, reject) => {
94
147
  child.once("error", reject);
95
148
  child.once("exit", (code) => resolve(code ?? 1));
96
149
  });
97
- if (code)
98
- throw new Error(`Native ${harness} authentication did not complete (${code})`);
150
+ if (code) {
151
+ throw new CliError(`${login} exited with code ${code}, so sign-in didn't finish.`, `${login} ${installed.key}`);
152
+ }
99
153
  return {
100
154
  message: `${harness} authentication completed. Credentials remain in native storage.`,
101
155
  };
@@ -0,0 +1,33 @@
1
+ import { readState } from "../../config/state.js";
2
+ import { CliError } from "../../errors.js";
3
+ import { synchronize } from "../environment/sync.js";
4
+ import { recordedVariables } from "../native/secret-values.js";
5
+ import { readSecrets, updateSecrets } from "../secrets/index.js";
6
+ /** Keeps `value` for `variable` and writes it into the coding tools. */
7
+ export async function keepMcpValue(variable, value, runtime) {
8
+ if (!value) {
9
+ throw new CliError(`The value for ${variable} is empty, so nothing was kept.`, `barndog mcp env set ${variable}`);
10
+ }
11
+ const file = await updateSecrets({ [variable]: value }, runtime);
12
+ return { file, events: await synchronize(undefined, runtime) };
13
+ }
14
+ /** Forgets a kept value; the tools refer to the environment variable again. */
15
+ export async function forgetMcpValue(variable, runtime) {
16
+ if ((await readSecrets(runtime))[variable] === undefined) {
17
+ throw new CliError(`BarnDog doesn't keep a value for ${variable}.`, "barndog mcp env list");
18
+ }
19
+ const file = await updateSecrets({ [variable]: null }, runtime);
20
+ return { file, events: await synchronize(undefined, runtime) };
21
+ }
22
+ /** The kept variables, with the settings files sync wrote each into. */
23
+ export async function listKeptValues(runtime) {
24
+ const names = Object.keys(await readSecrets(runtime)).sort();
25
+ const { native } = await readState(runtime.home);
26
+ return names.map((variable) => ({
27
+ variable,
28
+ writtenTo: native
29
+ .filter((entry) => entry.kind === "mcp" &&
30
+ recordedVariables(entry.value).includes(variable))
31
+ .map((entry) => ({ file: entry.file, server: entry.key })),
32
+ }));
33
+ }