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
@@ -1,159 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
- import { join } from "node:path";
4
- import { randomUUID } from "node:crypto";
5
- import { CliError } from "../../errors.js";
6
- import { storePackage } from "../environment/packages.js";
7
- import { loadWorkspace, NAME_RULE, } from "./format.js";
8
- import { git, GitError, gitReason, gitText } from "./git.js";
9
- import { folderSnapshot, gitSnapshot } from "./snapshot.js";
10
- function repoSource(backend, home) {
11
- let loading;
12
- const model = () => (loading ??= backend.open().then((snapshot) => loadWorkspace(snapshot, backend.workspaceId, {
13
- localOnly: backend.localOnly ?? false,
14
- })));
15
- const find = async (reference) => {
16
- const asset = (await model()).assets.find((a) => a.id === reference.id);
17
- if (!asset || asset.publishedVersion !== reference.publishedVersion)
18
- throw new Error("Catalog changed during staging; retry sync");
19
- if (asset.invalid)
20
- throw new CliError(`${asset.path} is invalid: ${asset.invalid}`);
21
- return asset;
22
- };
23
- return {
24
- cacheKey: backend.cacheKey,
25
- journal: { workspaceId: backend.workspaceId },
26
- label: backend.label,
27
- model,
28
- catalog: async () => (await model()).catalog,
29
- invalidAssets: async () => (await model()).invalid,
30
- notices: backend.notices,
31
- warnings: async () => {
32
- const { invalidKnowledge, problems } = await model();
33
- return [
34
- ...invalidKnowledge.map((problem) => `Knowledge file ${problem.path} was skipped: ${problem.reason}`),
35
- ...problems
36
- .filter((problem) => problem.reason === NAME_RULE)
37
- .map((problem) => `${problem.path} was skipped: ${problem.reason}. Rename it to deliver it.`),
38
- ];
39
- },
40
- skillOrHookPackage: async (kind, reference) => {
41
- const asset = await find(reference);
42
- return storePackage(kind, {
43
- id: asset.id,
44
- name: asset.name,
45
- revision: asset.publishedVersion,
46
- }, backend.cacheKey, home, async () => asset.entries);
47
- },
48
- mcpDefinition: async (reference) => (await find(reference)).definition,
49
- };
50
- }
51
- export function localRepoSource(workspace, home) {
52
- return repoSource({
53
- cacheKey: join("local", workspace.workspaceId),
54
- workspaceId: workspace.workspaceId,
55
- label: workspace.path,
56
- open: () => folderSnapshot(workspace.path),
57
- notices: () => [],
58
- localOnly: true,
59
- }, home);
60
- }
61
- const AUTO_FETCH_INTERVAL_MS = 5 * 60 * 1000;
62
- export const gitDirectory = (workspaceId, home) => join(home, ".barndog", "git", `${workspaceId}.git`);
63
- const statePath = (workspaceId, home) => join(home, ".barndog", "git", `${workspaceId}.json`);
64
- export async function readFetchState(workspaceId, home) {
65
- try {
66
- return JSON.parse(await readFile(statePath(workspaceId, home), "utf8"));
67
- }
68
- catch (error) {
69
- if (error.code === "ENOENT")
70
- return {};
71
- throw error;
72
- }
73
- }
74
- async function writeFetchState(workspaceId, home, state) {
75
- const path = statePath(workspaceId, home);
76
- const temporary = `${path}.${randomUUID()}.tmp`;
77
- try {
78
- await writeFile(temporary, JSON.stringify(state), { mode: 0o600 });
79
- await rename(temporary, path);
80
- }
81
- finally {
82
- await rm(temporary, { force: true });
83
- }
84
- }
85
- /** Creates or repairs the bare clone; nothing is ever checked out of it. */
86
- export async function ensureBareClone(repo, url) {
87
- await mkdir(repo, { recursive: true, mode: 0o700 });
88
- await git(["init", "--quiet", "--bare", "."], { repo });
89
- await git(["config", "remote.origin.url", url], { repo });
90
- }
91
- export const fetchBranch = (repo, branch, allowPrompt = false) => git([
92
- "fetch",
93
- "--quiet",
94
- "--prune",
95
- "--no-tags",
96
- "origin",
97
- `+refs/heads/${branch}:refs/remotes/origin/${branch}`,
98
- ], { repo, allowPrompt });
99
- export function trackingRef(branch) {
100
- return `refs/remotes/origin/${branch}`;
101
- }
102
- const age = (fetchedAt) => {
103
- if (!fetchedAt)
104
- return "an unknown time";
105
- const minutes = Math.round((Date.now() - Date.parse(fetchedAt)) / 60000);
106
- if (minutes < 1)
107
- return "less than a minute";
108
- if (minutes < 60)
109
- return `${minutes} minute${minutes === 1 ? "" : "s"}`;
110
- const hours = Math.round(minutes / 60);
111
- return hours < 48 ? `${hours} hours` : `${Math.round(hours / 24)} days`;
112
- };
113
- export function gitRepoSource(workspace, home, options = {}) {
114
- const repo = gitDirectory(workspace.workspaceId, home);
115
- const notices = [];
116
- async function currentCommit() {
117
- const state = await readFetchState(workspace.workspaceId, home);
118
- const policy = options.refresh ?? "always";
119
- const recent = state.fetchedAt &&
120
- Date.now() - Date.parse(state.fetchedAt) < AUTO_FETCH_INTERVAL_MS;
121
- if (policy === "none" || (policy === "auto" && recent && state.accepted)) {
122
- if (!state.accepted)
123
- throw new CliError("This Git workspace hasn't been fetched yet.", "barndog sync");
124
- return state.accepted;
125
- }
126
- await ensureBareClone(repo, workspace.url);
127
- try {
128
- await fetchBranch(repo, workspace.branch);
129
- }
130
- catch (error) {
131
- if (!(error instanceof GitError))
132
- throw error;
133
- if (!state.accepted)
134
- throw new CliError(`Can't fetch ${workspace.url}: ${gitReason(error.stderr)}. Make sure you can clone it on this machine; BarnDog manages it from there.`, `git clone ${workspace.url}`, { cause: error });
135
- notices.push(`Can't reach ${workspace.url}, so this uses what was fetched ${age(state.fetchedAt)} ago.`);
136
- return state.accepted;
137
- }
138
- const tip = await gitText(["rev-parse", "--verify", trackingRef(workspace.branch)], { repo });
139
- await writeFetchState(workspace.workspaceId, home, {
140
- accepted: tip,
141
- fetchedAt: new Date().toISOString(),
142
- });
143
- return tip;
144
- }
145
- return repoSource({
146
- cacheKey: join("git", createHash("sha256").update(workspace.workspaceId).digest("hex")),
147
- workspaceId: workspace.workspaceId,
148
- label: workspace.url,
149
- open: async () => gitSnapshot(repo, await currentCommit()),
150
- notices: () => notices,
151
- }, home);
152
- }
153
- export async function recordFetch(workspace, commit, home) {
154
- await writeFetchState(workspace.workspaceId, home, {
155
- accepted: commit,
156
- fetchedAt: new Date().toISOString(),
157
- });
158
- }
159
- export const acceptedCommit = async (workspaceId, home) => (await readFetchState(workspaceId, home)).accepted;
@@ -1,219 +0,0 @@
1
- import { copyFile, mkdir, readFile, writeFile } from "node:fs/promises";
2
- import { homedir } from "node:os";
3
- import { basename, join } from "node:path";
4
- import { mcpDefinitionSchema, } from "@barndog-ai/api-contract";
5
- import { parse as parseJsonc } from "jsonc-parser";
6
- import { parse as parseToml } from "smol-toml";
7
- import { stringify } from "yaml";
8
- import { readSettings, SetupRequiredError } from "../../config/settings.js";
9
- import { CliError } from "../../errors.js";
10
- import { harnesses } from "../../harnesses/registry.js";
11
- import { atomicFile, fileText, locked } from "../environment/transaction.js";
12
- import { synchronize } from "../environment/sync.js";
13
- import { nativeFile, patchNative } from "../native/configuration.js";
14
- import { NAME_RULE, validAssetName } from "../git-workspace/format.js";
15
- import { LOCAL_ORIGIN } from "../git-workspace/overlay.js";
16
- import { ensureLocalWorkspace } from "./local.js";
17
- const isServer = (value) => !!value &&
18
- typeof value === "object" &&
19
- ("command" in value || "url" in value || "httpUrl" in value);
20
- /** Accepts the shapes people copy: a harness's whole file, a name map, or one server. */
21
- export function parseMcpText(text, name) {
22
- let value;
23
- try {
24
- value = JSON.parse(text);
25
- }
26
- catch (error) {
27
- throw new CliError("That isn't valid JSON.", undefined, { cause: error });
28
- }
29
- if (isServer(value)) {
30
- if (!name)
31
- throw new CliError("This JSON is one server without a name.", "barndog mcp add <name> --file <path>");
32
- return [{ name, server: value }];
33
- }
34
- const object = value;
35
- const map = (object?.mcpServers ?? object?.servers ?? object);
36
- const servers = Object.entries(map ?? {}).filter(([, server]) => isServer(server));
37
- if (!servers.length)
38
- throw new CliError("No MCP servers found in that JSON. Each one needs a command or url.");
39
- return servers
40
- .filter(([key]) => !name || servers.length === 1 || key === name)
41
- .map(([key, server]) => ({
42
- name: servers.length === 1 && name ? name : key,
43
- server: server,
44
- }));
45
- }
46
- const variable = (value) => /^\$\{(?:env:)?([A-Za-z_][A-Za-z0-9_]*)\}$|^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(value);
47
- const embedded = (value) => /\$\{(?:env:)?([A-Za-z_][A-Za-z0-9_]*)\}/.exec(value)?.[1];
48
- const envName = (text) => text.toUpperCase().replace(/[^A-Z0-9_]/g, "_");
49
- /** Secrets are named, never stored: every literal becomes a variable to set locally. */
50
- function reference(key, value, fallback, notes) {
51
- const text = String(value);
52
- const whole = variable(text);
53
- if (whole)
54
- return { secretRef: whole[1] ?? whole[2] };
55
- const inside = embedded(text);
56
- if (inside) {
57
- notes.push(`${key} mixes text with ${inside}. Set ${inside} to the complete value of ${key}, including that text.`);
58
- return { secretRef: inside };
59
- }
60
- notes.push(`${key} held a literal value, which BarnDog doesn't store. Set ${fallback} in your environment.`);
61
- return { secretRef: fallback };
62
- }
63
- export function convertServer({ name, server }, description, oauth) {
64
- const notes = [];
65
- const type = typeof server.type === "string" ? server.type : undefined;
66
- if (type === "sse" || type === "ws")
67
- throw new CliError(`${name} uses ${type} transport. BarnDog supports stdio and HTTP servers.`);
68
- const url = (server.url ?? server.httpUrl);
69
- const common = {
70
- description: description ??
71
- (typeof server.description === "string" && server.description.trim()
72
- ? server.description
73
- : `${name} MCP server`),
74
- };
75
- let candidate;
76
- if (url) {
77
- const headers = {};
78
- for (const [key, value] of Object.entries((server.headers ?? server.http_headers ?? {})))
79
- headers[key] = reference(key, value, envName(`${name}_${key}`), notes);
80
- for (const [key, value] of Object.entries((server.env_http_headers ?? {})))
81
- headers[key] = { secretRef: value };
82
- if (typeof server.bearer_token_env_var === "string") {
83
- headers.Authorization = { secretRef: server.bearer_token_env_var };
84
- notes.push(`Set ${server.bearer_token_env_var} to the whole Authorization value, including "Bearer ".`);
85
- }
86
- // Claude Code writes `oauth` and Cursor writes `auth` for servers that sign in natively.
87
- const signsIn = oauth || !!server.oauth || !!server.auth;
88
- if (signsIn)
89
- notes.push(`Sign in once it's added: barndog mcp auth ${name} --origin ${LOCAL_ORIGIN} --harness <tool>`);
90
- candidate = {
91
- ...common,
92
- transport: "http",
93
- url,
94
- headers,
95
- authentication: signsIn
96
- ? "native-oauth"
97
- : Object.keys(headers).length
98
- ? "environment"
99
- : "none",
100
- };
101
- }
102
- else {
103
- if (oauth)
104
- throw new CliError(`${name} runs as a local command, and only HTTP servers sign in with OAuth.`);
105
- const environment = {};
106
- for (const [key, value] of Object.entries((server.env ?? {})))
107
- environment[key] = reference(key, value, key, notes);
108
- for (const key of (server.env_vars ?? []))
109
- environment[key] = { secretRef: key };
110
- const args = (server.args ?? []).map(String);
111
- if (args.some((arg) => /(api[-_]?key|token|secret|password)/i.test(arg) || /^sk-/.test(arg)))
112
- notes.push("An argument looks like it may hold a secret. Arguments are stored as written, so check them before sharing this.");
113
- candidate = {
114
- ...common,
115
- transport: "stdio",
116
- command: server.command,
117
- args,
118
- environment,
119
- authentication: Object.keys(environment).length ? "environment" : "none",
120
- };
121
- }
122
- const parsed = mcpDefinitionSchema.safeParse(candidate);
123
- if (!parsed.success)
124
- throw new CliError(`${name} can't be added: ${parsed.error.issues.map((issue) => `${issue.path.join(".") || "server"}: ${issue.message}`).join("; ")}`);
125
- return { name, definition: parsed.data, notes };
126
- }
127
- async function jsonFile(path) {
128
- const text = await fileText(path).catch(() => null);
129
- return text ? (parseJsonc(text) ?? {}) : {};
130
- }
131
- /** Servers each harness has configured, leaving out the ones BarnDog installed. */
132
- export async function harnessServers(home = homedir()) {
133
- const state = await jsonFile(join(home, ".barndog/state.json"));
134
- const owned = new Set((state.native ?? [])
135
- .filter((entry) => entry.kind === "mcp")
136
- .map((entry) => `${entry.harness}:${entry.key}`));
137
- const found = [];
138
- const add = (harness, label, servers) => {
139
- for (const [name, server] of Object.entries((servers ?? {})))
140
- if (isServer(server) && !owned.has(`${harness}:${name}`))
141
- found.push({ harness, label, name, server });
142
- };
143
- const claude = await jsonFile(nativeFile("claude", "mcp", home));
144
- add("claude", "Claude Code", claude.mcpServers);
145
- for (const [project, value] of Object.entries((claude.projects ?? {})))
146
- add("claude", `Claude Code, ${basename(project)} project`, value?.mcpServers);
147
- add("cursor", "Cursor", (await jsonFile(nativeFile("cursor", "mcp", home))).mcpServers);
148
- const codex = await fileText(nativeFile("codex", "mcp", home)).catch(() => null);
149
- if (codex)
150
- add("codex", "Codex", parseToml(codex).mcp_servers);
151
- return found;
152
- }
153
- /** Native entries BarnDog doesn't own that would block installing this name. */
154
- export async function conflictingEntries(name, home = homedir()) {
155
- const settings = await readSettings(home);
156
- if (!settings)
157
- throw new SetupRequiredError();
158
- const servers = await harnessServers(home);
159
- const selected = harnesses.filter((h) => settings.harnesses.includes(h));
160
- return servers
161
- .filter((entry) => entry.name === name &&
162
- selected.includes(entry.harness) &&
163
- !entry.label.includes("project"))
164
- .map((entry) => ({
165
- harness: entry.harness,
166
- file: nativeFile(entry.harness, "mcp", home),
167
- server: entry.server,
168
- }));
169
- }
170
- export async function addMcpServers(servers, options, home = homedir()) {
171
- const invalid = servers.filter(({ name }) => !validAssetName(name));
172
- if (invalid.length)
173
- 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>");
174
- return locked(home, async () => {
175
- const workspace = await ensureLocalWorkspace(home);
176
- for (const { name } of servers) {
177
- const target = join(workspace.path, "org/mcp", `${name}.yaml`);
178
- if (await fileText(target).catch(() => null))
179
- throw new CliError(`A local MCP server named ${name} already exists.`, `barndog mcp add ${name}-2 --file <path>`);
180
- const conflicts = await conflictingEntries(name, home);
181
- if (conflicts.length && !options.replace)
182
- 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`);
183
- }
184
- const backups = [];
185
- for (const { name, definition } of servers) {
186
- for (const conflict of await conflictingEntries(name, home)) {
187
- const text = await readFile(conflict.file, "utf8");
188
- const backup = join(home, ".barndog/migrations", `${basename(conflict.file)}-${Date.now()}.bak`);
189
- await mkdir(join(home, ".barndog/migrations"), {
190
- recursive: true,
191
- mode: 0o700,
192
- });
193
- await copyFile(conflict.file, backup);
194
- backups.push(backup);
195
- await atomicFile(conflict.file, patchNative(text, [
196
- {
197
- id: "import",
198
- kind: "mcp",
199
- harness: conflict.harness,
200
- file: conflict.file,
201
- key: name,
202
- value: conflict.server,
203
- },
204
- ], []));
205
- }
206
- await mkdir(join(workspace.path, "org/mcp"), { recursive: true });
207
- await writeFile(join(workspace.path, "org/mcp", `${name}.yaml`), stringify(definition));
208
- }
209
- const events = await synchronize(undefined, home, undefined, {
210
- prompt: false,
211
- });
212
- return {
213
- added: servers.map((s) => s.name),
214
- notes: servers.flatMap((s) => s.notes),
215
- backups,
216
- events,
217
- };
218
- });
219
- }
@@ -1,25 +0,0 @@
1
- import { knowledgeList, knowledgeIndexText } from "./index.js";
2
- // BarnDog-owned integration, independent from developer-authored Hook packages.
3
- // Failure to retrieve an index must never block starting a coding session.
4
- const timer = setTimeout(() => {
5
- console.error("BarnDog knowledge index timed out; use barndog knowledge list.");
6
- process.exit(0);
7
- }, 5000);
8
- try {
9
- const text = knowledgeIndexText(await knowledgeList(process.argv[3], true));
10
- if (text)
11
- console.log(JSON.stringify(process.argv[2] === "cursor"
12
- ? { additional_context: text }
13
- : {
14
- hookSpecificOutput: {
15
- hookEventName: "SessionStart",
16
- additionalContext: text,
17
- },
18
- }));
19
- }
20
- catch {
21
- console.error("BarnDog knowledge index is unavailable; use barndog knowledge list after reconnecting.");
22
- }
23
- finally {
24
- clearTimeout(timer);
25
- }
@@ -1,57 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { mcpDefinitionSchema } from "@barndog-ai/api-contract";
3
- // This process runs only when the native harness starts a selected stdio MCP.
4
- // Definitions contain references, never credential values. No shell is involved.
5
- try {
6
- const definition = mcpDefinitionSchema.parse(JSON.parse(Buffer.from(process.argv[2] ?? "", "base64url").toString("utf8")));
7
- if (definition.transport !== "stdio")
8
- throw new Error("A stdio configuration is required");
9
- const env = { ...process.env };
10
- for (const [name, reference] of Object.entries(definition.environment)) {
11
- if (!process.env[reference.secretRef])
12
- throw new Error(`Missing local environment variable: ${reference.secretRef}`);
13
- env[name] = process.env[reference.secretRef];
14
- }
15
- const child = spawn(definition.command, definition.args, {
16
- env,
17
- stdio: "inherit",
18
- detached: process.platform !== "win32",
19
- });
20
- for (const signal of ["SIGINT", "SIGTERM"])
21
- process.on(signal, () => {
22
- if (!child.pid)
23
- return;
24
- try {
25
- if (process.platform !== "win32")
26
- process.kill(-child.pid, signal);
27
- else
28
- child.kill(signal);
29
- const timer = setTimeout(() => {
30
- try {
31
- if (process.platform !== "win32")
32
- process.kill(-child.pid, "SIGKILL");
33
- else
34
- child.kill("SIGKILL");
35
- }
36
- catch {
37
- /* exited */
38
- }
39
- }, 2000);
40
- timer.unref();
41
- }
42
- catch {
43
- /* already exited */
44
- }
45
- });
46
- child.once("error", () => {
47
- console.error("Unable to start the configured MCP command");
48
- process.exitCode = 1;
49
- });
50
- child.once("exit", (code) => {
51
- process.exitCode = code ?? 1;
52
- });
53
- }
54
- catch (error) {
55
- console.error(error instanceof Error ? error.message : "Invalid MCP configuration");
56
- process.exitCode = 1;
57
- }
@@ -1,25 +0,0 @@
1
- import { matchesOrigin } from "../collaboration/remote.js";
2
- import { homedir } from "node:os";
3
- import { readSettings, saveSettings, upgradeSettings, SetupRequiredError, } from "../../config/settings.js";
4
- import { catalog } from "./remote.js";
5
- import { sync } from "./sync.js";
6
- export async function installSkill(name, origin, home = homedir()) {
7
- const settings = await readSettings(home);
8
- if (!settings)
9
- throw new SetupRequiredError();
10
- const next = upgradeSettings(settings);
11
- if (!next.connection)
12
- throw new Error("Connect with barndog init --server <url> first");
13
- const matches = (await catalog(next.connection, home)).filter((skill) => skill.name === name &&
14
- matchesOrigin(skill.origin, origin, next.connection));
15
- if (matches.length !== 1)
16
- throw new Error(`Skill not found or ambiguous: ${origin}/${name}`);
17
- const skill = matches[0];
18
- if (next.skills.some((entry) => entry.id === skill.id && entry.kind !== "api"))
19
- throw new Error("Skill ID conflicts with a local selection");
20
- next.skills = next.skills.filter((entry) => entry.id !== skill.id);
21
- next.skills.push({ kind: "api", id: skill.id, enabled: true });
22
- const events = await sync(undefined, home, next);
23
- await saveSettings(next, home);
24
- return events;
25
- }
@@ -1,177 +0,0 @@
1
- import { hasRemoteSelections } from "../../config/environment.js";
2
- import { normalizeServer, serverFetch } from "../auth/transport.js";
3
- import { contextSchema, listOutputSchema, createApiClient, } from "@barndog-ai/api-contract";
4
- import { directoryFingerprint, packageFingerprint, parsePackage, packageMetadata, writePackage, defaultLimits, } from "@barndog-ai/api-contract/package";
5
- import { createHash, randomUUID } from "node:crypto";
6
- import { mkdir, readFile, readdir, rename, rm, writeFile, lstat, } from "node:fs/promises";
7
- import { join } from "node:path";
8
- import { homedir } from "node:os";
9
- import { readSettings, saveSettings, upgradeSettings, SetupRequiredError, } from "../../config/settings.js";
10
- import { resolveAssets } from "../asset-selection/index.js";
11
- export { normalizeServer } from "../auth/transport.js";
12
- export function apiClient(server, home = homedir()) {
13
- return createApiClient({
14
- baseUrl: normalizeServer(server),
15
- fetch: serverFetch(server, home),
16
- });
17
- }
18
- export async function connectionContext(server, home = homedir()) {
19
- server = normalizeServer(server);
20
- const context = contextSchema.parse((await apiClient(server, home).GET("/v1/context")).data);
21
- return {
22
- server,
23
- organizationId: context.organization.id,
24
- developerId: context.developer.id,
25
- };
26
- }
27
- export async function connect(server, home = homedir()) {
28
- const connection = await connectionContext(server, home);
29
- const settings = await readSettings(home);
30
- if (!settings)
31
- throw new SetupRequiredError();
32
- const next = upgradeSettings(settings);
33
- if (hasRemoteSelections(next) &&
34
- next.connection &&
35
- (next.connection.server !== connection.server ||
36
- next.connection.organizationId !== connection.organizationId ||
37
- next.connection.developerId !== connection.developerId))
38
- throw new Error("Remove API selections before switching server, organization, or developer");
39
- await saveSettings({ ...next, connection }, home);
40
- }
41
- export async function catalog(connection, home = homedir()) {
42
- const client = apiClient(connection.server, home);
43
- const context = contextSchema.parse((await client.GET("/v1/context")).data);
44
- if (context.organization.id !== connection.organizationId ||
45
- context.developer.id !== connection.developerId)
46
- throw new Error("Server organization or developer changed; run initialization again");
47
- const skills = [];
48
- const cursors = new Set();
49
- let cursor;
50
- do {
51
- const page = listOutputSchema.parse((await client.GET("/v1/skills", {
52
- params: { query: { cursor, limit: 100 } },
53
- })).data);
54
- if (page.skills.some((skill) => skill.organizationId !== connection.organizationId))
55
- throw new Error("Invalid catalog organization");
56
- skills.push(...page.skills);
57
- if (page.nextCursor && cursors.has(page.nextCursor))
58
- throw new Error("Invalid catalog pagination");
59
- if (page.nextCursor)
60
- cursors.add(page.nextCursor);
61
- cursor = page.nextCursor ?? undefined;
62
- } while (cursor);
63
- if (new Set(skills.map((skill) => skill.id)).size !== skills.length)
64
- throw new Error("Duplicate catalog Skill");
65
- return skills;
66
- }
67
- export async function listSkills(home = homedir()) {
68
- const settings = await readSettings(home);
69
- if (!settings || settings.version !== 2 || !settings.connection)
70
- throw new Error("Connect with barndog init --server <url> first");
71
- return catalog(settings.connection, home);
72
- }
73
- async function fingerprintMatches(root, name) {
74
- const saved = JSON.parse(await readFile(join(root, "manifest.json"), "utf8"));
75
- if ((await directoryFingerprint(join(root, name))) !== saved.fingerprint)
76
- throw new Error(`Cached Skill was modified locally: ${name}`);
77
- }
78
- async function download(skill, connection, home) {
79
- const serverKey = createHash("sha256")
80
- .update(connection.server)
81
- .digest("hex");
82
- const root = join(home, ".barndog", "packages", serverKey, connection.organizationId, connection.developerId, skill.id);
83
- await mkdir(root, { recursive: true });
84
- // Verify previous cached versions too: a new publication must not silently hide local edits.
85
- for (const commit of await readdir(root)) {
86
- if (/^[0-9a-f]{40}$/.test(commit))
87
- await fingerprintMatches(join(root, commit), skill.name);
88
- }
89
- const target = join(root, skill.version.commit);
90
- try {
91
- await lstat(target);
92
- await fingerprintMatches(target, skill.name);
93
- return join(target, skill.name);
94
- }
95
- catch (error) {
96
- if (error.code !== "ENOENT")
97
- throw error;
98
- }
99
- const response = await serverFetch(connection.server, home)(`${connection.server}/v1/skills/${skill.id}/versions/${skill.version.number}/package`, { signal: AbortSignal.timeout(30000) });
100
- if (!response.ok)
101
- throw new Error(`Package download failed (${response.status}): ${skill.name}`);
102
- if (Number(response.headers.get("content-length")) > defaultLimits.compressed)
103
- throw new Error("Package download too large");
104
- const chunks = [];
105
- let size = 0;
106
- if (!response.body)
107
- throw new Error("Missing package body");
108
- for await (const chunk of response.body) {
109
- size += chunk.length;
110
- if (size > defaultLimits.compressed) {
111
- throw new Error("Package download too large");
112
- }
113
- chunks.push(chunk);
114
- }
115
- const entries = await parsePackage(Buffer.concat(chunks));
116
- if (packageMetadata(entries).name !== skill.name)
117
- throw new Error("Package name does not match catalog");
118
- if (response.headers.get("etag") !== `"${skill.version.commit}"`)
119
- throw new Error("Package revision does not match catalog");
120
- const stage = join(root, `.stage-${randomUUID()}`);
121
- try {
122
- await writePackage(join(stage, skill.name), entries);
123
- await writeFile(join(stage, "manifest.json"), JSON.stringify({ fingerprint: packageFingerprint(entries) }));
124
- try {
125
- await rename(stage, target);
126
- }
127
- catch (error) {
128
- if (!["EEXIST", "ENOTEMPTY"].includes(error.code ?? ""))
129
- throw error;
130
- await fingerprintMatches(target, skill.name);
131
- }
132
- return join(target, skill.name);
133
- }
134
- finally {
135
- await rm(stage, { recursive: true, force: true });
136
- }
137
- }
138
- export async function prepareSources(settings, home) {
139
- if (settings.version === 1)
140
- return settings.skills;
141
- const remote = settings.skills.filter((skill) => skill.kind === "api");
142
- const result = settings.skills.filter((skill) => skill.kind === "local");
143
- if (!remote.length)
144
- return result;
145
- const connection = settings.connection;
146
- const skills = await catalog(connection, home);
147
- const resolved = resolveAssets({
148
- assets: skills.map((skill) => ({
149
- kind: "skill",
150
- id: skill.id,
151
- name: skill.name,
152
- origin: skill.origin,
153
- publishedVersion: skill.version.id,
154
- })),
155
- distributions: [],
156
- }, {
157
- subscriptions: [],
158
- individualAssetIds: remote.map((skill) => skill.id),
159
- disabledAssetIds: remote
160
- .filter((skill) => !skill.enabled)
161
- .map((skill) => skill.id),
162
- excludedAssetIds: [],
163
- });
164
- if (resolved.diagnostics.length)
165
- throw new Error("Selected Skill is missing from the server; installation was preserved");
166
- for (const effective of resolved.assets) {
167
- const skill = skills.find((skill) => skill.id === effective.asset.id);
168
- result.push({
169
- id: skill.id,
170
- enabled: effective.enabled,
171
- source: effective.enabled
172
- ? await download(skill, connection, home)
173
- : "unused-disabled-api-source",
174
- });
175
- }
176
- return result;
177
- }