barndog 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/README.md +8 -7
  2. package/dist/cli.js +11 -7
  3. package/dist/commands/add.js +33 -21
  4. package/dist/commands/arguments.js +12 -0
  5. package/dist/commands/asset-install.js +160 -0
  6. package/dist/commands/asset-list.js +121 -0
  7. package/dist/commands/asset-share.js +94 -0
  8. package/dist/commands/auth.js +4 -0
  9. package/dist/commands/availability.js +54 -26
  10. package/dist/commands/capabilities.js +71 -415
  11. package/dist/commands/collaboration.js +194 -110
  12. package/dist/commands/environment.js +18 -411
  13. package/dist/commands/github.js +200 -0
  14. package/dist/commands/helpers.js +39 -0
  15. package/dist/commands/hooks.js +87 -0
  16. package/dist/commands/init.js +4 -2
  17. package/dist/commands/knowledge.js +73 -0
  18. package/dist/commands/mcp.js +62 -0
  19. package/dist/commands/origin.js +21 -23
  20. package/dist/commands/people.js +51 -0
  21. package/dist/commands/sets.js +141 -0
  22. package/dist/commands/status.js +34 -24
  23. package/dist/commands/sync.js +11 -4
  24. package/dist/commands/workspace.js +33 -19
  25. package/dist/config/environment.js +13 -27
  26. package/dist/config/paths.js +62 -0
  27. package/dist/config/selection.js +30 -0
  28. package/dist/config/settings.js +97 -108
  29. package/dist/config/state.js +57 -57
  30. package/dist/entry/knowledge-startup.js +32 -0
  31. package/dist/entry/mcp-launch.js +71 -0
  32. package/dist/entry/opencode-plugin.js +62 -0
  33. package/dist/{features/git-workspace/startup.js → entry/workspace-startup.js} +7 -2
  34. package/dist/errors.js +198 -55
  35. package/dist/features/asset-kinds/index.js +120 -0
  36. package/dist/features/asset-selection/index.js +51 -19
  37. package/dist/features/auth/credentials.js +80 -47
  38. package/dist/features/auth/session.js +80 -45
  39. package/dist/features/auth/transport.js +66 -15
  40. package/dist/features/catalog/index.js +32 -61
  41. package/dist/features/collaboration/api.js +160 -0
  42. package/dist/features/collaboration/index.js +321 -233
  43. package/dist/features/collaboration/remote.js +35 -115
  44. package/dist/features/collaboration/results.js +2 -0
  45. package/dist/features/collaboration/workspace-git.js +233 -149
  46. package/dist/features/collaboration/workspace-github.js +117 -54
  47. package/dist/features/collaboration/workspace-store.js +140 -100
  48. package/dist/features/collaboration/workspace.js +257 -172
  49. package/dist/features/discovery/index.js +68 -57
  50. package/dist/features/doctor/index.js +32 -24
  51. package/dist/features/environment/auto-sync.js +28 -27
  52. package/dist/features/environment/names.js +67 -47
  53. package/dist/features/environment/operations.js +321 -228
  54. package/dist/features/environment/own-entries.js +89 -0
  55. package/dist/features/environment/settle-names.js +91 -0
  56. package/dist/features/environment/stage.js +178 -0
  57. package/dist/features/environment/sync.js +113 -484
  58. package/dist/features/environment/transaction.js +179 -147
  59. package/dist/features/environment/writes.js +196 -0
  60. package/dist/features/github/account.js +25 -0
  61. package/dist/features/github/connections.js +119 -0
  62. package/dist/features/github/pulls.js +118 -0
  63. package/dist/features/hooks/adapt.js +32 -25
  64. package/dist/features/hooks/catalog.js +28 -0
  65. package/dist/features/hooks/compatibility.js +49 -0
  66. package/dist/features/hooks/divergence.js +9 -6
  67. package/dist/features/hooks/test.js +74 -49
  68. package/dist/features/hooks/types.js +1 -0
  69. package/dist/features/imports/discover.js +134 -61
  70. package/dist/features/imports/folder.js +48 -14
  71. package/dist/features/imports/local.js +113 -134
  72. package/dist/features/imports/remote.js +44 -25
  73. package/dist/features/inspection/index.js +17 -17
  74. package/dist/features/inventory/index.js +99 -110
  75. package/dist/features/knowledge/index.js +69 -49
  76. package/dist/features/mcps/catalog.js +31 -0
  77. package/dist/features/mcps/import.js +316 -0
  78. package/dist/features/mcps/index.js +98 -49
  79. package/dist/features/migration/migrate.js +263 -0
  80. package/dist/features/{git-workspace → migration}/move.js +165 -109
  81. package/dist/features/migration/promote.js +24 -0
  82. package/dist/features/native/adapters.js +53 -94
  83. package/dist/features/native/configuration.js +128 -82
  84. package/dist/features/native/hook-shell.js +55 -0
  85. package/dist/features/native/plugin-module.js +56 -0
  86. package/dist/features/onboarding/environment.js +67 -34
  87. package/dist/features/onboarding/setup.js +43 -40
  88. package/dist/features/repositories/context.js +30 -13
  89. package/dist/features/server/catalog.js +58 -0
  90. package/dist/features/server/client.js +13 -0
  91. package/dist/features/server/connection.js +37 -0
  92. package/dist/features/server/origin.js +74 -0
  93. package/dist/features/server/pages.js +24 -0
  94. package/dist/features/skills/catalog.js +42 -0
  95. package/dist/features/workspace/assets.js +57 -0
  96. package/dist/features/workspace/cloud-source.js +34 -0
  97. package/dist/features/workspace/directory.js +38 -0
  98. package/dist/features/{git-workspace → workspace}/format.js +114 -51
  99. package/dist/features/workspace/git.js +214 -0
  100. package/dist/features/workspace/installed.js +92 -0
  101. package/dist/features/{git-workspace → workspace}/overlay.js +43 -23
  102. package/dist/features/workspace/packages.js +160 -0
  103. package/dist/features/{git-workspace → workspace}/publish.js +120 -64
  104. package/dist/features/workspace/repo-source.js +192 -0
  105. package/dist/features/{git-workspace → workspace}/setup.js +60 -42
  106. package/dist/features/{git-workspace → workspace}/snapshot.js +53 -18
  107. package/dist/features/workspace/source.js +1 -0
  108. package/dist/features/workspace/tree.js +52 -0
  109. package/dist/features/workspace/workspace-source.js +27 -0
  110. package/dist/harnesses/claude.js +23 -1
  111. package/dist/harnesses/codex.js +57 -1
  112. package/dist/harnesses/cursor.js +22 -1
  113. package/dist/harnesses/detect.js +6 -50
  114. package/dist/harnesses/formats.js +45 -0
  115. package/dist/harnesses/opencode.js +111 -0
  116. package/dist/harnesses/registry.js +35 -2
  117. package/dist/platform.js +375 -0
  118. package/dist/program.js +225 -54
  119. package/dist/runtime.js +1 -0
  120. package/dist/shared/cli-error.js +22 -0
  121. package/dist/shared/constants.js +32 -0
  122. package/dist/shared/files.js +72 -0
  123. package/dist/shared/lock.js +49 -0
  124. package/dist/shared/lookup.js +11 -0
  125. package/dist/shared/patterns.js +94 -0
  126. package/dist/shared/shell.js +22 -0
  127. package/dist/shared/values.js +26 -0
  128. package/dist/ui/add-asset.js +41 -400
  129. package/dist/ui/add-hook.js +213 -0
  130. package/dist/ui/add-mcp.js +107 -0
  131. package/dist/ui/add-prompts.js +47 -0
  132. package/dist/ui/add-skills.js +115 -0
  133. package/dist/ui/asset-list.js +31 -13
  134. package/dist/ui/assets.js +33 -44
  135. package/dist/ui/auth.js +43 -33
  136. package/dist/ui/clash.js +11 -6
  137. package/dist/ui/collaboration.js +116 -44
  138. package/dist/ui/connection.js +10 -4
  139. package/dist/ui/decision-error.js +24 -0
  140. package/dist/ui/environment-onboarding.js +35 -13
  141. package/dist/ui/format.js +66 -18
  142. package/dist/ui/hook-compatibility.js +14 -6
  143. package/dist/ui/mcp.js +28 -3
  144. package/dist/ui/move.js +10 -5
  145. package/dist/ui/onboarding.js +113 -73
  146. package/dist/ui/options.js +9 -0
  147. package/dist/ui/output.js +106 -43
  148. package/dist/ui/pick.js +45 -33
  149. package/dist/ui/scope-install.js +15 -7
  150. package/dist/ui/selection.js +15 -11
  151. package/dist/ui/theme.js +37 -14
  152. package/dist/version.js +6 -3
  153. package/package.json +13 -3
  154. package/dist/features/capabilities/index.js +0 -106
  155. package/dist/features/collaboration/domain.js +0 -90
  156. package/dist/features/environment/cloud-source.js +0 -27
  157. package/dist/features/environment/installed.js +0 -124
  158. package/dist/features/environment/packages.js +0 -120
  159. package/dist/features/environment/remote.js +0 -71
  160. package/dist/features/environment/workspace-source.js +0 -19
  161. package/dist/features/git-hosts/index.js +0 -148
  162. package/dist/features/git-workspace/assets.js +0 -71
  163. package/dist/features/git-workspace/git.js +0 -135
  164. package/dist/features/git-workspace/migrate.js +0 -188
  165. package/dist/features/git-workspace/source.js +0 -159
  166. package/dist/features/imports/mcp.js +0 -219
  167. package/dist/features/knowledge/startup.js +0 -25
  168. package/dist/features/native/mcp-launch.js +0 -57
  169. package/dist/features/skills/install.js +0 -25
  170. package/dist/features/skills/remote.js +0 -177
  171. package/dist/features/skills/sync.js +0 -121
  172. package/dist/features/skills/validation.js +0 -34
  173. /package/dist/features/environment/{source.js → events.js} +0 -0
@@ -0,0 +1,316 @@
1
+ import { POSIX_MODE } from "../../shared/constants.js";
2
+ import { readState } from "../../config/state.js";
3
+ import { mkdir, readFile } from "node:fs/promises";
4
+ import { basename, join } from "node:path";
5
+ import { mcpDefinitionSchema, } from "@barndog-ai/api-contract";
6
+ import { parse as parseJsonc } from "jsonc-parser";
7
+ import { parse as parseToml } from "smol-toml";
8
+ import { stringify } from "yaml";
9
+ import { readSettings, SetupRequiredError } from "../../config/settings.js";
10
+ import { CliError } from "../../errors.js";
11
+ import { adapters, harnesses, nativeFile, } from "../../harnesses/registry.js";
12
+ import { locked } from "../environment/transaction.js";
13
+ import { fileText, writeAtomic } from "../../shared/files.js";
14
+ import { synchronize } from "../environment/sync.js";
15
+ import { patchNative } from "../native/configuration.js";
16
+ import { NAME_RULE } from "../workspace/format.js";
17
+ import { validAssetName, VARIABLE_NAME } from "../../shared/patterns.js";
18
+ import { LOCAL_ORIGIN } from "../workspace/overlay.js";
19
+ import { ensureLocalWorkspace } from "../imports/local.js";
20
+ import { asRecord, asStrings, isRecord } from "../../shared/values.js";
21
+ import { barndogPaths } from "../../config/paths.js";
22
+ const isServer = (value) => isRecord(value) &&
23
+ ("command" in value || "url" in value || "httpUrl" in value);
24
+ /** Accepts the shapes people copy: a harness's whole file, a name map, or one server. */
25
+ export function parseMcpText(text, name) {
26
+ let value;
27
+ try {
28
+ value = JSON.parse(text);
29
+ }
30
+ catch (error) {
31
+ throw new CliError("That isn't valid JSON.", undefined, { cause: error });
32
+ }
33
+ if (isServer(value)) {
34
+ if (!name) {
35
+ throw new CliError("This JSON is one server without a name.", "barndog mcp add <name> --file <path>");
36
+ }
37
+ return [{ name, server: value }];
38
+ }
39
+ const object = asRecord(value);
40
+ const map = asRecord(object.mcpServers ?? object.servers ?? object);
41
+ const servers = Object.entries(map).flatMap(([key, server]) => isServer(server) ? [{ key, server }] : []);
42
+ if (!servers.length) {
43
+ throw new CliError("No MCP servers found in that JSON. Each one needs a command or url.");
44
+ }
45
+ if (name && servers.length > 1 && !servers.some(({ key }) => key === name)) {
46
+ 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");
47
+ }
48
+ return servers
49
+ .filter(({ key }) => !name || servers.length === 1 || key === name)
50
+ .map(({ key, server }) => ({
51
+ name: servers.length === 1 && name ? name : key,
52
+ server,
53
+ }));
54
+ }
55
+ /** A braced variable reference, `${API_KEY}` (Claude Code) or `${env:API_KEY}` (Cursor). */
56
+ const BRACED_VARIABLE = new RegExp(String.raw `\$\{(?:env:)?(${VARIABLE_NAME.source})\}`);
57
+ /** A whole value that is one variable reference, braced or bare (`$API_KEY`). */
58
+ const WHOLE_VARIABLE = new RegExp(String.raw `^(?:${BRACED_VARIABLE.source}|\$(${VARIABLE_NAME.source}))$`);
59
+ /**
60
+ * The variable a whole value refers to: `${env:TOKEN}` or `$TOKEN` → `TOKEN`.
61
+ *
62
+ * @internal Exported for its table test in `src/tests/patterns.test.ts`.
63
+ */
64
+ export const variableName = (value) => {
65
+ const [, braced, bare] = WHOLE_VARIABLE.exec(value) ?? [];
66
+ return braced ?? bare;
67
+ };
68
+ /**
69
+ * The first braced variable inside a value: `Bearer ${TOKEN}` → `TOKEN`.
70
+ *
71
+ * @internal Exported for its table test in `src/tests/patterns.test.ts`.
72
+ */
73
+ export const embeddedVariable = (value) => BRACED_VARIABLE.exec(value)?.[1];
74
+ /**
75
+ * An environment variable name made from any text: `my-server_x-api` → `MY_SERVER_X_API`.
76
+ *
77
+ * @internal Exported for its table test in `src/tests/patterns.test.ts`.
78
+ */
79
+ export const envName = (text) => text.toUpperCase().replace(/[^\dA-Z_]/g, "_");
80
+ /** Words that suggest a credential: `--api-key`, `apikey=`, `TOKEN`, `password`. */
81
+ const SECRET_WORD = /api[-_]?key|token|secret|password/i;
82
+ /**
83
+ * Whether a command-line argument may hold a credential: a secret-sounding word, or an `sk-` key.
84
+ *
85
+ * @internal Exported for its table test in `src/tests/patterns.test.ts`.
86
+ */
87
+ export const looksSecret = (arg) => SECRET_WORD.test(arg) || arg.startsWith("sk-");
88
+ /** Secrets are named, never stored: every literal becomes a variable to set locally. */
89
+ function reference(key, value, fallback, notes) {
90
+ const text = String(value);
91
+ const whole = variableName(text);
92
+ if (whole) {
93
+ return { secretRef: whole };
94
+ }
95
+ const inside = embeddedVariable(text);
96
+ if (inside) {
97
+ notes.push(`${key} mixes text with ${inside}. Set ${inside} to the complete value of ${key}, including that text.`);
98
+ return { secretRef: inside };
99
+ }
100
+ notes.push(`${key} held a literal value, which BarnDog doesn't store. Set ${fallback} in your environment.`);
101
+ return { secretRef: fallback };
102
+ }
103
+ /**
104
+ * Converts environment and header values to local secret references. Command
105
+ * arguments and URLs are preserved, so the result is not guaranteed to be free
106
+ * of secrets.
107
+ */
108
+ /** An HTTP server's address, as `url` or Gemini's `httpUrl`; a stdio server has none. */
109
+ function serverUrl(name, server) {
110
+ const address = server.url ?? server.httpUrl;
111
+ if (address !== undefined && typeof address !== "string") {
112
+ throw new CliError(`${name} can't be added: its url must be text, such as "https://example.com/mcp".`);
113
+ }
114
+ return address;
115
+ }
116
+ export function convertServer({ name, server }, description, oauth) {
117
+ const notes = [];
118
+ const type = typeof server.type === "string" ? server.type : undefined;
119
+ if (type === "sse" || type === "ws") {
120
+ throw new CliError(`${name} uses ${type} transport. BarnDog supports stdio and HTTP servers.`);
121
+ }
122
+ const url = serverUrl(name, server);
123
+ const common = {
124
+ description: description ??
125
+ (typeof server.description === "string" && server.description.trim()
126
+ ? server.description
127
+ : `${name} MCP server`),
128
+ };
129
+ let candidate;
130
+ if (url) {
131
+ const headers = {};
132
+ for (const [key, value] of Object.entries(asRecord(server.headers ?? server.http_headers))) {
133
+ headers[key] = reference(key, value, envName(`${name}_${key}`), notes);
134
+ }
135
+ for (const [key, value] of Object.entries(asRecord(server.env_http_headers))) {
136
+ if (typeof value === "string") {
137
+ headers[key] = { secretRef: value };
138
+ }
139
+ }
140
+ if (typeof server.bearer_token_env_var === "string") {
141
+ headers.Authorization = { secretRef: server.bearer_token_env_var };
142
+ notes.push(`Set ${server.bearer_token_env_var} to the whole Authorization value, including "Bearer ".`);
143
+ }
144
+ // Claude Code writes `oauth` and Cursor writes `auth` for servers that sign in natively.
145
+ const signsIn = oauth || !!server.oauth || !!server.auth;
146
+ if (signsIn) {
147
+ notes.push(`Sign in once it's added: barndog mcp auth ${name} --origin ${LOCAL_ORIGIN} --harness <tool>`);
148
+ }
149
+ candidate = {
150
+ ...common,
151
+ transport: "http",
152
+ url,
153
+ headers,
154
+ authentication: httpAuthentication(signsIn, headers),
155
+ };
156
+ }
157
+ else {
158
+ if (oauth) {
159
+ throw new CliError(`${name} runs as a local command, and only HTTP servers sign in with OAuth.`);
160
+ }
161
+ const environment = {};
162
+ for (const [key, value] of Object.entries(asRecord(server.env))) {
163
+ environment[key] = reference(key, value, key, notes);
164
+ }
165
+ for (const key of asStrings(server.env_vars)) {
166
+ environment[key] = { secretRef: key };
167
+ }
168
+ const listed = Array.isArray(server.args) ? server.args : [];
169
+ const args = listed.map(String);
170
+ if (args.some(looksSecret)) {
171
+ notes.push("An argument looks like it may hold a secret. Arguments are stored as written, so check them before sharing this.");
172
+ }
173
+ candidate = {
174
+ ...common,
175
+ transport: "stdio",
176
+ command: server.command,
177
+ args,
178
+ environment,
179
+ authentication: Object.keys(environment).length ? "environment" : "none",
180
+ };
181
+ }
182
+ const parsed = mcpDefinitionSchema.safeParse(candidate);
183
+ if (!parsed.success) {
184
+ throw new CliError(`${name} can't be added: ${parsed.error.issues.map((issue) => `${issue.path.join(".") || "server"}: ${issue.message}`).join("; ")}`);
185
+ }
186
+ return { name, definition: parsed.data, notes };
187
+ }
188
+ /** How an imported HTTP server authenticates. */
189
+ function httpAuthentication(signsIn, headers) {
190
+ if (signsIn) {
191
+ return "native-oauth";
192
+ }
193
+ return Object.keys(headers).length ? "environment" : "none";
194
+ }
195
+ async function jsonFile(path) {
196
+ const text = await fileText(path).catch(() => null);
197
+ return text ? asRecord(parseJsonc(text)) : {};
198
+ }
199
+ /** Servers each harness has configured, leaving out the ones BarnDog installed. */
200
+ export async function harnessServers(runtime) {
201
+ const { home } = runtime;
202
+ const { native } = await readState(home);
203
+ const owned = new Set(native
204
+ .filter((entry) => entry.kind === "mcp")
205
+ .map((entry) => `${entry.file}:${entry.key}`));
206
+ const found = [];
207
+ const add = (harness, source, servers) => {
208
+ const { imported } = adapters[harness].mcp;
209
+ for (const [name, entry] of Object.entries(asRecord(servers))) {
210
+ if (!isRecord(entry) || owned.has(`${source.file}:${name}`)) {
211
+ continue;
212
+ }
213
+ const server = imported ? imported(entry) : entry;
214
+ if (isServer(server)) {
215
+ found.push({ harness, ...source, name, server, native: entry });
216
+ }
217
+ }
218
+ };
219
+ const claudeFile = nativeFile("claude", "mcp", home);
220
+ const claude = await jsonFile(claudeFile);
221
+ add("claude", { label: adapters.claude.name, file: claudeFile }, claude.mcpServers);
222
+ for (const [project, value] of Object.entries(asRecord(claude.projects))) {
223
+ add("claude", {
224
+ label: `${adapters.claude.name}, ${basename(project)} project`,
225
+ file: claudeFile,
226
+ }, asRecord(value).mcpServers);
227
+ }
228
+ const cursorFile = nativeFile("cursor", "mcp", home);
229
+ add("cursor", { label: adapters.cursor.name, file: cursorFile }, (await jsonFile(cursorFile)).mcpServers);
230
+ const codexFile = nativeFile("codex", "mcp", home);
231
+ const codex = await fileText(codexFile).catch(() => null);
232
+ if (codex) {
233
+ add("codex", { label: adapters.codex.name, file: codexFile }, parseToml(codex).mcp_servers);
234
+ }
235
+ const { mcp } = adapters.opencode;
236
+ for (const relative of mcp.files) {
237
+ const file = join(home, relative);
238
+ add("opencode", { label: `${adapters.opencode.name}, ${basename(file)}`, file }, mcp.path.reduce((value, key) => asRecord(value)[key], await jsonFile(file)));
239
+ }
240
+ return found;
241
+ }
242
+ /** Native entries BarnDog doesn't own that would block installing this name. */
243
+ export async function conflictingEntries(name, runtime) {
244
+ const { home } = runtime;
245
+ const settings = await readSettings(home);
246
+ if (!settings) {
247
+ throw new SetupRequiredError();
248
+ }
249
+ const servers = await harnessServers(runtime);
250
+ const selected = harnesses.filter((h) => settings.harnesses.includes(h));
251
+ return servers
252
+ .filter((entry) => entry.name === name &&
253
+ selected.includes(entry.harness) &&
254
+ !entry.label.includes("project"))
255
+ .map((entry) => ({
256
+ harness: entry.harness,
257
+ file: entry.file,
258
+ server: entry.native,
259
+ }));
260
+ }
261
+ /**
262
+ * Writes converted MCP servers and synchronizes them. Existing local workspace
263
+ * names are always rejected; replace permits backing up and removing
264
+ * conflicting native entries.
265
+ */
266
+ export async function addMcpServers(servers, options, runtime) {
267
+ const { home } = runtime;
268
+ const invalid = servers.filter(({ name }) => !validAssetName(name));
269
+ if (invalid.length) {
270
+ throw new CliError(`${invalid.map(({ name }) => name).join(", ")} can't be used as ${invalid.length === 1 ? "an MCP name" : "MCP names"}. ${NAME_RULE}. To add one, save only that server to a JSON file under a new name.`, "barndog mcp add <new-name> --file <path>");
271
+ }
272
+ return locked(runtime, async () => {
273
+ const workspace = await ensureLocalWorkspace(runtime);
274
+ for (const { name } of servers) {
275
+ const target = join(workspace.path, "org/mcp", `${name}.yaml`);
276
+ if (await fileText(target).catch(() => null)) {
277
+ throw new CliError(`A local MCP server named ${name} already exists.`, `barndog mcp add ${name}-2 --file <path>`);
278
+ }
279
+ const conflicts = await conflictingEntries(name, runtime);
280
+ if (conflicts.length && !options.replace) {
281
+ 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`);
282
+ }
283
+ }
284
+ const backups = [];
285
+ for (const { name, definition } of servers) {
286
+ for (const conflict of await conflictingEntries(name, runtime)) {
287
+ const text = await readFile(conflict.file, "utf8");
288
+ const backup = join(barndogPaths(home).migrations, `${basename(conflict.file)}-${Date.now()}.bak`);
289
+ await writeAtomic(backup, text);
290
+ backups.push(backup);
291
+ await writeAtomic(conflict.file, patchNative(text, [
292
+ {
293
+ id: "import",
294
+ kind: "mcp",
295
+ harness: conflict.harness,
296
+ file: conflict.file,
297
+ key: name,
298
+ value: conflict.server,
299
+ },
300
+ ], []));
301
+ }
302
+ // The workspace's own folders keep default permissions; writeAtomic would make them private.
303
+ await mkdir(join(workspace.path, "org/mcp"), { recursive: true });
304
+ await writeAtomic(join(workspace.path, "org/mcp", `${name}.yaml`), stringify(definition), { mode: POSIX_MODE.regularFile });
305
+ }
306
+ const events = await synchronize(undefined, runtime, undefined, {
307
+ prompt: false,
308
+ });
309
+ return {
310
+ added: servers.map((s) => s.name),
311
+ notes: servers.flatMap((s) => s.notes),
312
+ backups,
313
+ events,
314
+ };
315
+ });
316
+ }
@@ -1,56 +1,98 @@
1
- import { homedir } from "node:os";
1
+ import { localPath } from "../../platform.js";
2
+ import { POSIX_MODE } from "../../shared/constants.js";
3
+ import { readState } from "../../config/state.js";
2
4
  import { readFile, mkdir } from "node:fs/promises";
3
- import { join } from "node:path";
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 } from "../../shared/files.js";
19
+ import { defined } from "../../shared/lookup.js";
20
+ import { CliError } from "../../errors.js";
21
+ import { barndogPaths } from "../../config/paths.js";
22
+ import { apiClient } from "../auth/transport.js";
23
+ async function readDefinition(file, runtime) {
24
+ return mcpDefinitionSchema.parse(JSON.parse(await readFile(localPath(file, runtime), "utf8")));
25
+ }
26
+ /** Publishes a new MCP configuration in a scope. */
27
+ export async function createMcp(input, runtime) {
28
+ const conn = await connection(runtime);
29
+ const scope = await selectOrigin(input.origin, conn, runtime);
30
+ const definition = await readDefinition(input.file, runtime);
31
+ return parsed(mcpSchema, apiClient(conn.server, runtime).POST("/v1/mcps", {
32
+ body: {
33
+ name: input.name,
34
+ origin: { type: scope.type, id: scope.id },
35
+ definition,
36
+ idempotencyKey: input.key ?? randomUUID(),
37
+ },
38
+ }));
39
+ }
40
+ /** Publishes a new revision of an MCP configuration, against the inspected version. */
41
+ export async function updateMcp(input, runtime) {
42
+ const conn = await connection(runtime);
43
+ await selectOrigin(input.origin, conn, runtime);
44
+ const definition = await readDefinition(input.file, runtime);
45
+ const selected = await selectAsset("mcp", input.name, input.origin, runtime);
46
+ return parsed(mcpSchema, apiClient(conn.server, runtime).POST("/v1/mcps/{id}/versions", {
47
+ params: { path: { id: selected.reference.id } },
48
+ body: {
21
49
  definition,
22
- expectedVersionId: z.uuidv4().parse(expectedVersionId),
23
- idempotencyKey: key,
24
- });
50
+ expectedVersionId: z.uuidv4().parse(input.expectedVersion),
51
+ idempotencyKey: input.key ?? randomUUID(),
52
+ },
53
+ }));
54
+ }
55
+ /** One MCP configuration with its definition, from the repo or the server. */
56
+ export async function showMcp(name, origin, runtime) {
57
+ const { home } = runtime;
58
+ const settings = await readSettings(home);
59
+ const repo = settings && repoForOrigin(settings, runtime, origin);
60
+ if (repo) {
61
+ return showRepoAsset(selectRepoAsset(await repo.model(), "mcp", name, origin));
25
62
  }
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
- });
63
+ return (await selectAsset("mcp", name, origin, runtime)).asset;
32
64
  }
33
- export async function mcpVersions(name, origin, home = homedir()) {
65
+ export async function mcpVersions(name, origin, runtime) {
66
+ const { home } = runtime;
34
67
  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);
68
+ if (settings?.gitWorkspace) {
69
+ return gitVersions(settings.gitWorkspace, { name, origin, kind: "mcp" }, runtime);
70
+ }
71
+ const selected = await selectAsset("mcp", name, origin, runtime);
72
+ return parsed(z.array(mcpVersionSchema), apiClient(selected.connection.server, runtime).GET("/v1/mcps/{id}/versions", {
73
+ params: { path: { id: selected.reference.id } },
74
+ }));
39
75
  }
40
- export async function authenticateMcp(name, origin, harness, home = homedir()) {
76
+ /**
77
+ * Guides MCP authentication or starts the native harness login command;
78
+ * credentials remain in native storage.
79
+ */
80
+ export async function authenticateMcp(name, origin, harness, runtime) {
81
+ const { home } = runtime;
41
82
  const settings = await readSettings(home);
42
- const repo = settings && repoForOrigin(settings, home, origin);
83
+ const repo = settings && repoForOrigin(settings, runtime, origin);
43
84
  const asset = repo
44
85
  ? await (async () => {
45
86
  const found = selectRepoAsset(await repo.model(), "mcp", name, origin);
46
87
  return {
47
88
  id: found.id,
48
89
  name: found.name,
49
- definition: found.definition,
90
+ definition: defined(found.definition, `${found.name} has no MCP definition`),
50
91
  };
51
92
  })()
52
93
  : await (async () => {
53
- const selected = await selectAsset("mcp", name, origin, home), parsed = mcpSchema.parse(selected.asset);
94
+ const selected = await selectAsset("mcp", name, origin, runtime);
95
+ const parsed = mcpSchema.parse(selected.asset);
54
96
  return {
55
97
  id: parsed.id,
56
98
  name: parsed.name,
@@ -70,32 +112,39 @@ export async function authenticateMcp(name, origin, harness, home = homedir()) {
70
112
  .join(", ")}. Credential values are never uploaded.`,
71
113
  };
72
114
  }
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");
115
+ const { native } = await readState(home);
116
+ const installed = native.find((e) => e.id === asset.id && e.kind === "mcp" && e.harness === harness);
117
+ if (!installed) {
118
+ throw new CliError(`${asset.name} isn't installed and enabled for ${harness}.`, `barndog mcp install ${asset.name}`);
119
+ }
120
+ const entry = { ...installed, kind: "mcp", harness };
80
121
  patchNative(await fileText(entry.file), [entry], [entry]);
81
- if (harness === "cursor")
122
+ const { name: tool, mcp } = adapters[harness];
123
+ if ("settings" in mcp.login) {
82
124
  return {
83
- message: `Open Cursor → Settings → MCP and authenticate ${asset.name}. Cursor manages this login locally.`,
125
+ message: `Open ${tool} → ${mcp.login.settings} and authenticate ${asset.name}. ${tool} manages this login locally.`,
84
126
  };
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], {
127
+ }
128
+ const [command, ...loginArguments] = mcp.login.command;
129
+ const login = mcp.login.command.join(" ");
130
+ if (!command) {
131
+ throw new Error(`The ${tool} adapter has an empty MCP login command`);
132
+ }
133
+ const cwd = barndogPaths(home).nativeAuth;
134
+ await mkdir(cwd, { recursive: true, mode: POSIX_MODE.privateDirectory });
135
+ // cross-spawn also starts Windows .cmd shims, such as an npm-installed claude.
136
+ const child = crossSpawn(command, [...loginArguments, asset.name], {
89
137
  cwd,
90
138
  stdio: "inherit",
91
- env: process.env,
139
+ env: { ...runtime.env },
92
140
  });
93
141
  const code = await new Promise((resolve, reject) => {
94
142
  child.once("error", reject);
95
143
  child.once("exit", (code) => resolve(code ?? 1));
96
144
  });
97
- if (code)
98
- throw new Error(`Native ${harness} authentication did not complete (${code})`);
145
+ if (code) {
146
+ throw new CliError(`${login} exited with code ${code}, so sign-in didn't finish.`, `${login} ${asset.name}`);
147
+ }
99
148
  return {
100
149
  message: `${harness} authentication completed. Credentials remain in native storage.`,
101
150
  };