barndog 0.0.0-stage → 0.1.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 (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +117 -2
  3. package/dist/cli.js +40 -0
  4. package/dist/commands/add.js +99 -0
  5. package/dist/commands/auth.js +25 -0
  6. package/dist/commands/availability.js +87 -0
  7. package/dist/commands/capabilities.js +488 -0
  8. package/dist/commands/collaboration.js +203 -0
  9. package/dist/commands/context.js +1 -0
  10. package/dist/commands/environment.js +416 -0
  11. package/dist/commands/init.js +20 -0
  12. package/dist/commands/origin.js +48 -0
  13. package/dist/commands/status.js +66 -0
  14. package/dist/commands/sync.js +30 -0
  15. package/dist/commands/workspace.js +84 -0
  16. package/dist/config/build.js +2 -0
  17. package/dist/config/environment.js +41 -0
  18. package/dist/config/settings.js +127 -0
  19. package/dist/config/state.js +70 -0
  20. package/dist/errors.js +154 -0
  21. package/dist/features/asset-selection/index.js +212 -0
  22. package/dist/features/asset-selection/types.js +1 -0
  23. package/dist/features/auth/credentials.js +62 -0
  24. package/dist/features/auth/session.js +120 -0
  25. package/dist/features/auth/transport.js +44 -0
  26. package/dist/features/capabilities/index.js +106 -0
  27. package/dist/features/catalog/index.js +102 -0
  28. package/dist/features/collaboration/domain.js +90 -0
  29. package/dist/features/collaboration/index.js +254 -0
  30. package/dist/features/collaboration/remote.js +121 -0
  31. package/dist/features/collaboration/workspace-git.js +362 -0
  32. package/dist/features/collaboration/workspace-github.js +130 -0
  33. package/dist/features/collaboration/workspace-store.js +256 -0
  34. package/dist/features/collaboration/workspace.js +391 -0
  35. package/dist/features/discovery/index.js +66 -0
  36. package/dist/features/doctor/index.js +154 -0
  37. package/dist/features/environment/auto-sync.js +96 -0
  38. package/dist/features/environment/cloud-source.js +27 -0
  39. package/dist/features/environment/installed.js +124 -0
  40. package/dist/features/environment/names.js +153 -0
  41. package/dist/features/environment/operations.js +277 -0
  42. package/dist/features/environment/packages.js +120 -0
  43. package/dist/features/environment/remote.js +71 -0
  44. package/dist/features/environment/source.js +1 -0
  45. package/dist/features/environment/sync.js +547 -0
  46. package/dist/features/environment/transaction.js +284 -0
  47. package/dist/features/environment/workspace-source.js +19 -0
  48. package/dist/features/git-hosts/index.js +148 -0
  49. package/dist/features/git-workspace/assets.js +71 -0
  50. package/dist/features/git-workspace/format.js +310 -0
  51. package/dist/features/git-workspace/git.js +135 -0
  52. package/dist/features/git-workspace/migrate.js +188 -0
  53. package/dist/features/git-workspace/move.js +337 -0
  54. package/dist/features/git-workspace/overlay.js +131 -0
  55. package/dist/features/git-workspace/publish.js +172 -0
  56. package/dist/features/git-workspace/setup.js +135 -0
  57. package/dist/features/git-workspace/snapshot.js +105 -0
  58. package/dist/features/git-workspace/source.js +159 -0
  59. package/dist/features/git-workspace/startup.js +16 -0
  60. package/dist/features/hooks/adapt.js +103 -0
  61. package/dist/features/hooks/divergence.js +38 -0
  62. package/dist/features/hooks/test.js +114 -0
  63. package/dist/features/imports/discover.js +249 -0
  64. package/dist/features/imports/folder.js +52 -0
  65. package/dist/features/imports/local.js +242 -0
  66. package/dist/features/imports/mcp.js +219 -0
  67. package/dist/features/imports/remote.js +85 -0
  68. package/dist/features/inspection/index.js +42 -0
  69. package/dist/features/inventory/index.js +224 -0
  70. package/dist/features/knowledge/index.js +118 -0
  71. package/dist/features/knowledge/startup.js +25 -0
  72. package/dist/features/mcps/index.js +102 -0
  73. package/dist/features/native/adapters.js +143 -0
  74. package/dist/features/native/configuration.js +196 -0
  75. package/dist/features/native/mcp-launch.js +57 -0
  76. package/dist/features/onboarding/environment.js +160 -0
  77. package/dist/features/onboarding/setup.js +123 -0
  78. package/dist/features/repositories/context.js +55 -0
  79. package/dist/features/skills/install.js +25 -0
  80. package/dist/features/skills/remote.js +177 -0
  81. package/dist/features/skills/sync.js +121 -0
  82. package/dist/features/skills/validation.js +34 -0
  83. package/dist/harnesses/claude.js +57 -0
  84. package/dist/harnesses/codex.js +46 -0
  85. package/dist/harnesses/cursor.js +44 -0
  86. package/dist/harnesses/detect.js +61 -0
  87. package/dist/harnesses/registry.js +16 -0
  88. package/dist/harnesses/types.js +1 -0
  89. package/dist/program.js +272 -0
  90. package/dist/ui/add-asset.js +440 -0
  91. package/dist/ui/asset-list.js +50 -0
  92. package/dist/ui/assets.js +142 -0
  93. package/dist/ui/auth.js +138 -0
  94. package/dist/ui/clash.js +43 -0
  95. package/dist/ui/collaboration.js +142 -0
  96. package/dist/ui/connection.js +102 -0
  97. package/dist/ui/environment-onboarding.js +125 -0
  98. package/dist/ui/format.js +154 -0
  99. package/dist/ui/hook-compatibility.js +33 -0
  100. package/dist/ui/mcp.js +40 -0
  101. package/dist/ui/move.js +22 -0
  102. package/dist/ui/onboarding.js +293 -0
  103. package/dist/ui/output.js +155 -0
  104. package/dist/ui/pick.js +153 -0
  105. package/dist/ui/scope-install.js +47 -0
  106. package/dist/ui/selection.js +51 -0
  107. package/dist/ui/theme.js +37 -0
  108. package/dist/version.js +12 -0
  109. package/package.json +73 -4
@@ -0,0 +1,212 @@
1
+ const uuidV4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
2
+ function id(value) {
3
+ if (!uuidV4.test(value))
4
+ throw new Error(`Expected UUIDv4: ${value}`);
5
+ return value.toLowerCase();
6
+ }
7
+ function origin(value) {
8
+ return { ...value, id: id(value.id) };
9
+ }
10
+ function scopeKey(scope) {
11
+ return `${scope.type}:${scope.id}`;
12
+ }
13
+ function compare(a, b) {
14
+ return a < b ? -1 : a > b ? 1 : 0;
15
+ }
16
+ function ids(values) {
17
+ return [...new Set(values.map(id))].sort(compare);
18
+ }
19
+ function normalizeState(state) {
20
+ const subscriptions = state.subscriptions.map((subscription) => ({
21
+ ...subscription,
22
+ scope: origin(subscription.scope),
23
+ }));
24
+ const keys = subscriptions.map((subscription) => scopeKey(subscription.scope));
25
+ if (new Set(keys).size !== keys.length)
26
+ throw new Error("Only one subscription per scope is allowed");
27
+ return {
28
+ subscriptions: subscriptions.sort((a, b) => compare(scopeKey(a.scope), scopeKey(b.scope))),
29
+ individualAssetIds: ids(state.individualAssetIds),
30
+ excludedAssetIds: ids(state.excludedAssetIds),
31
+ disabledAssetIds: ids(state.disabledAssetIds),
32
+ };
33
+ }
34
+ function prepare(catalog, input) {
35
+ const assets = new Map();
36
+ for (const asset of catalog.assets) {
37
+ const assetId = id(asset.id);
38
+ if (assets.has(assetId))
39
+ throw new Error(`Duplicate catalogue asset ID: ${assetId}`);
40
+ assets.set(assetId, {
41
+ ...asset,
42
+ id: assetId,
43
+ origin: origin(asset.origin),
44
+ });
45
+ }
46
+ const distributions = new Map();
47
+ for (const distribution of catalog.distributions) {
48
+ const scope = origin(distribution.scope);
49
+ const key = scopeKey(scope);
50
+ if (distributions.has(key))
51
+ throw new Error(`Duplicate distribution scope: ${key}`);
52
+ const entries = new Map();
53
+ for (const entry of distribution.assets) {
54
+ const assetId = id(entry.assetId);
55
+ const previous = entries.get(assetId);
56
+ if (previous && previous !== entry.mode)
57
+ throw new Error(`Conflicting recommendation modes: ${assetId} in ${key}`);
58
+ entries.set(assetId, entry.mode);
59
+ }
60
+ distributions.set(key, {
61
+ scope,
62
+ assets: [...entries]
63
+ .sort(([a], [b]) => compare(a, b))
64
+ .map(([assetId, mode]) => ({ assetId, mode })),
65
+ });
66
+ }
67
+ return { assets, distributions, state: normalizeState(input) };
68
+ }
69
+ function matches(mode, entryMode) {
70
+ return mode === "all" || mode === entryMode;
71
+ }
72
+ /** Calculate desired local installation and activation without changing saved choices. */
73
+ export function resolveAssets(catalog, input) {
74
+ const { assets, distributions, state } = prepare(catalog, input);
75
+ const excluded = new Set(state.excludedAssetIds);
76
+ const disabled = new Set(state.disabledAssetIds);
77
+ const contributions = new Map();
78
+ const diagnostics = [];
79
+ const missingAssets = new Set();
80
+ function contribute(assetId, contribution) {
81
+ if (!assets.has(assetId)) {
82
+ missingAssets.add(assetId);
83
+ return;
84
+ }
85
+ if (excluded.has(assetId))
86
+ return;
87
+ const sources = contributions.get(assetId) ?? [];
88
+ sources.push(contribution);
89
+ contributions.set(assetId, sources);
90
+ }
91
+ for (const subscription of state.subscriptions) {
92
+ const distribution = distributions.get(scopeKey(subscription.scope));
93
+ if (!distribution) {
94
+ diagnostics.push({ type: "missing-scope", scope: subscription.scope });
95
+ continue;
96
+ }
97
+ for (const entry of distribution.assets) {
98
+ if (matches(subscription.mode, entry.mode))
99
+ contribute(entry.assetId, { type: "subscription", ...subscription });
100
+ }
101
+ }
102
+ for (const assetId of state.individualAssetIds)
103
+ contribute(assetId, { type: "individual" });
104
+ for (const assetId of [...missingAssets].sort(compare))
105
+ diagnostics.push({ type: "missing-asset", assetId });
106
+ const effective = [...contributions]
107
+ .sort(([a], [b]) => compare(a, b))
108
+ .map(([assetId, sources]) => ({
109
+ asset: assets.get(assetId),
110
+ enabled: !disabled.has(assetId) &&
111
+ sources.some((source) => source.type === "individual" || source.enabled),
112
+ individuallyDisabled: disabled.has(assetId),
113
+ contributions: sources,
114
+ }));
115
+ return { assets: effective, diagnostics };
116
+ }
117
+ /** Apply an explicit user action atomically; unresolved overrides never partially apply. */
118
+ export function applySelectionAction(catalog, input, action, resolution) {
119
+ const { assets, distributions, state } = prepare(catalog, input);
120
+ let subscriptions = [...state.subscriptions];
121
+ const individual = new Set(state.individualAssetIds);
122
+ const excluded = new Set(state.excludedAssetIds);
123
+ const disabled = new Set(state.disabledAssetIds);
124
+ if ("scope" in action) {
125
+ const scope = origin(action.scope);
126
+ const key = scopeKey(scope);
127
+ if (action.type === "install-scope" ||
128
+ action.type === "switch-team" ||
129
+ action.type === "switch-scope") {
130
+ const distribution = distributions.get(key);
131
+ if (!distribution)
132
+ throw new Error(`Unknown scope: ${key}`);
133
+ const conflicts = distribution.assets
134
+ .filter((entry) => matches(action.mode, entry.mode))
135
+ .filter((entry) => excluded.has(entry.assetId) || disabled.has(entry.assetId))
136
+ .map((entry) => {
137
+ const asset = assets.get(entry.assetId);
138
+ if (!asset)
139
+ throw new Error(`Cannot resolve overrides for missing asset: ${entry.assetId}`);
140
+ return {
141
+ asset,
142
+ excluded: excluded.has(entry.assetId),
143
+ individuallyDisabled: disabled.has(entry.assetId),
144
+ };
145
+ });
146
+ const decisions = new Map();
147
+ if (resolution?.type === "per-asset") {
148
+ for (const decision of resolution.decisions) {
149
+ const assetId = id(decision.assetId);
150
+ if (decisions.has(assetId))
151
+ throw new Error(`Duplicate override decision: ${assetId}`);
152
+ decisions.set(assetId, decision.choice);
153
+ }
154
+ }
155
+ if (conflicts.length &&
156
+ (!resolution ||
157
+ (resolution.type === "per-asset" &&
158
+ conflicts.some(({ asset }) => !decisions.has(asset.id)))))
159
+ return { status: "decision-required", conflicts };
160
+ for (const { asset } of conflicts) {
161
+ if (resolution?.type === "clear-all" ||
162
+ decisions.get(asset.id) === "clear") {
163
+ excluded.delete(asset.id);
164
+ disabled.delete(asset.id);
165
+ }
166
+ }
167
+ subscriptions = subscriptions.filter((subscription) => action.type === "switch-team" || action.type === "switch-scope"
168
+ ? subscription.scope.type !== scope.type
169
+ : scopeKey(subscription.scope) !== key);
170
+ subscriptions.push({ scope, mode: action.mode, enabled: true });
171
+ }
172
+ else if (action.type === "remove-scope") {
173
+ subscriptions = subscriptions.filter((subscription) => scopeKey(subscription.scope) !== key);
174
+ }
175
+ else {
176
+ if (!subscriptions.some((subscription) => scopeKey(subscription.scope) === key))
177
+ throw new Error(`Scope is not selected: ${key}`);
178
+ subscriptions = subscriptions.map((subscription) => scopeKey(subscription.scope) === key
179
+ ? { ...subscription, enabled: action.enabled }
180
+ : subscription);
181
+ }
182
+ }
183
+ else {
184
+ const assetId = id(action.assetId);
185
+ if (action.type === "install-asset") {
186
+ if (!assets.has(assetId))
187
+ throw new Error(`Unknown asset: ${assetId}`);
188
+ individual.add(assetId);
189
+ excluded.delete(assetId);
190
+ disabled.delete(assetId);
191
+ }
192
+ else if (action.type === "remove-asset") {
193
+ individual.delete(assetId);
194
+ excluded.add(assetId);
195
+ }
196
+ else if (action.enabled) {
197
+ disabled.delete(assetId);
198
+ }
199
+ else {
200
+ disabled.add(assetId);
201
+ }
202
+ }
203
+ return {
204
+ status: "applied",
205
+ state: normalizeState({
206
+ subscriptions,
207
+ individualAssetIds: [...individual],
208
+ excludedAssetIds: [...excluded],
209
+ disabledAssetIds: [...disabled],
210
+ }),
211
+ };
212
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,62 @@
1
+ import { chmod, lstat, mkdir, readFile, rename, rm, writeFile, } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ import { contextSchema } from "@barndog-ai/api-contract";
6
+ export async function readCredentials(home = homedir()) {
7
+ const path = join(home, ".barndog", "credentials.json");
8
+ try {
9
+ const info = await lstat(path);
10
+ if (!info.isFile() || (process.platform !== "win32" && info.mode & 0o077))
11
+ throw new Error("Credentials file must be a regular file accessible only to its owner");
12
+ const value = JSON.parse(await readFile(path, "utf8"));
13
+ if (value.version !== 1 ||
14
+ !value.servers ||
15
+ typeof value.servers !== "object" ||
16
+ Array.isArray(value.servers) ||
17
+ (value.selectedServer !== undefined &&
18
+ typeof value.selectedServer !== "string"))
19
+ throw new Error("Invalid credentials file");
20
+ for (const entry of Object.values(value.servers)) {
21
+ if (!entry ||
22
+ !/^[A-Za-z0-9_-]{43}$/.test(entry.token) ||
23
+ !Number.isFinite(Date.parse(entry.expiresAt)))
24
+ throw new Error("Invalid credentials file");
25
+ contextSchema.parse(entry.context);
26
+ }
27
+ return value;
28
+ }
29
+ catch (error) {
30
+ if (error.code === "ENOENT")
31
+ return { version: 1, servers: {} };
32
+ throw error;
33
+ }
34
+ }
35
+ export async function updateCredentials(home, update) {
36
+ const root = join(home, ".barndog");
37
+ await mkdir(root, { recursive: true, mode: 0o700 });
38
+ const info = await lstat(root);
39
+ if (!info.isDirectory())
40
+ throw new Error("Credentials directory must be a regular directory");
41
+ await chmod(root, 0o700);
42
+ const lock = join(root, "credentials.lock");
43
+ await mkdir(lock, { mode: 0o700 }).catch((error) => {
44
+ if (error.code === "EEXIST")
45
+ throw new Error("Another login or logout is running");
46
+ throw error;
47
+ });
48
+ const temporary = join(root, `credentials.${randomUUID()}.tmp`);
49
+ try {
50
+ const credentials = await readCredentials(home);
51
+ update(credentials);
52
+ await writeFile(temporary, JSON.stringify(credentials, null, 2) + "\n", {
53
+ mode: 0o600,
54
+ flag: "wx",
55
+ });
56
+ await rename(temporary, join(root, "credentials.json"));
57
+ }
58
+ finally {
59
+ await rm(temporary, { force: true });
60
+ await rm(lock, { recursive: true });
61
+ }
62
+ }
@@ -0,0 +1,120 @@
1
+ import { hasRemoteSelections } from "../../config/environment.js";
2
+ import { homedir } from "node:os";
3
+ import { setTimeout } from "node:timers/promises";
4
+ import { createApiClient, contextSchema, loginPollSchema, loginStartSchema, } from "@barndog-ai/api-contract";
5
+ import { readSettings } from "../../config/settings.js";
6
+ import { readCredentials, updateCredentials } from "./credentials.js";
7
+ import { LoginRequiredError, normalizeServer, serverFetch, } from "./transport.js";
8
+ export async function configuredServer(home = homedir()) {
9
+ const settings = await readSettings(home);
10
+ const credentials = await readCredentials(home);
11
+ const value = (settings?.version === 2 ? settings.connection?.server : undefined) ??
12
+ credentials.selectedServer;
13
+ return value ? normalizeServer(value) : undefined;
14
+ }
15
+ async function selectedServer(server, home) {
16
+ const value = server ?? (await configuredServer(home));
17
+ if (!value)
18
+ throw new Error("Specify the server for your first login with barndog login --server <url>");
19
+ return normalizeServer(value);
20
+ }
21
+ export async function login(options) {
22
+ const home = options.home ?? homedir();
23
+ const server = await selectedServer(options.server, home);
24
+ const client = createApiClient({
25
+ baseUrl: server,
26
+ fetch: serverFetch(server, home, false),
27
+ });
28
+ const started = loginStartSchema.parse((await client.POST("/v1/auth/cli/start", { signal: options.signal })).data);
29
+ await options.verification({
30
+ userCode: started.userCode,
31
+ url: started.verificationUri,
32
+ browserUrl: started.verificationUriComplete,
33
+ });
34
+ const signal = AbortSignal.any([
35
+ ...(options.signal ? [options.signal] : []),
36
+ AbortSignal.timeout(Math.max(1, Date.parse(started.expiresAt) - Date.now())),
37
+ ]);
38
+ let interval = started.interval;
39
+ while (true) {
40
+ await setTimeout(interval * 1000, undefined, { signal });
41
+ const result = loginPollSchema.parse((await client.POST("/v1/auth/cli/poll", {
42
+ body: { pollingToken: started.pollingToken },
43
+ signal,
44
+ })).data);
45
+ if (result.status !== "complete") {
46
+ interval = result.interval;
47
+ continue;
48
+ }
49
+ const revoke = () => fetch(`${server}/v1/auth/cli/session`, {
50
+ method: "DELETE",
51
+ headers: { Authorization: `Bearer ${result.token}` },
52
+ redirect: "error",
53
+ signal: AbortSignal.timeout(10000),
54
+ });
55
+ try {
56
+ const settings = await readSettings(home);
57
+ if (settings?.version === 2 &&
58
+ hasRemoteSelections(settings) &&
59
+ settings.connection &&
60
+ (settings.connection.server !== server ||
61
+ settings.connection.organizationId !==
62
+ result.context.organization.id ||
63
+ settings.connection.developerId !== result.context.developer.id))
64
+ throw new Error("Remove API selections before switching server, organization, or developer");
65
+ await updateCredentials(home, (credentials) => {
66
+ credentials.servers[server] = {
67
+ token: result.token,
68
+ expiresAt: result.expiresAt,
69
+ context: result.context,
70
+ };
71
+ credentials.selectedServer = server;
72
+ });
73
+ }
74
+ catch (error) {
75
+ await revoke().catch(() => { });
76
+ throw error;
77
+ }
78
+ return { server, context: result.context, expiresAt: result.expiresAt };
79
+ }
80
+ }
81
+ export async function logout(home = homedir()) {
82
+ const server = await selectedServer(undefined, home);
83
+ const credential = (await readCredentials(home)).servers[server];
84
+ let revoked = true;
85
+ if (credential) {
86
+ try {
87
+ const response = await fetch(`${server}/v1/auth/cli/session`, {
88
+ method: "DELETE",
89
+ headers: { Authorization: `Bearer ${credential.token}` },
90
+ redirect: "error",
91
+ signal: AbortSignal.timeout(10000),
92
+ });
93
+ revoked = response.ok;
94
+ }
95
+ catch {
96
+ revoked = false;
97
+ }
98
+ }
99
+ await updateCredentials(home, (credentials) => {
100
+ delete credentials.servers[server];
101
+ if (credentials.selectedServer === server)
102
+ delete credentials.selectedServer;
103
+ });
104
+ return { server, revoked };
105
+ }
106
+ export async function authStatus(home = homedir(), explicitServer) {
107
+ let server;
108
+ try {
109
+ server = await selectedServer(explicitServer, home);
110
+ }
111
+ catch {
112
+ throw new LoginRequiredError();
113
+ }
114
+ const client = createApiClient({
115
+ baseUrl: server,
116
+ fetch: serverFetch(server, home),
117
+ });
118
+ const context = contextSchema.parse((await client.GET("/v1/context")).data);
119
+ return { server, context };
120
+ }
@@ -0,0 +1,44 @@
1
+ import { homedir } from "node:os";
2
+ import { readCredentials } from "./credentials.js";
3
+ export class LoginRequiredError extends Error {
4
+ constructor() {
5
+ super("Authentication required. Run barndog login.");
6
+ }
7
+ }
8
+ export function normalizeServer(value) {
9
+ const url = new URL(value);
10
+ if (!["http:", "https:"].includes(url.protocol) ||
11
+ url.username ||
12
+ url.password ||
13
+ url.search ||
14
+ url.hash ||
15
+ url.pathname !== "/")
16
+ throw new Error("Server must be an HTTP(S) origin");
17
+ if (url.protocol !== "https:" &&
18
+ !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))
19
+ throw new Error("Server must use HTTPS outside loopback");
20
+ return url.origin;
21
+ }
22
+ export function serverFetch(server, home = homedir(), authenticated = true) {
23
+ const origin = normalizeServer(server);
24
+ return async (input, init) => {
25
+ const request = new Request(input, init);
26
+ if (new URL(request.url).origin !== origin)
27
+ throw new Error("Refusing to send credentials to another server");
28
+ const headers = new Headers(request.headers);
29
+ if (authenticated) {
30
+ const credential = (await readCredentials(home)).servers[origin];
31
+ if (!credential || Date.parse(credential.expiresAt) <= Date.now())
32
+ throw new LoginRequiredError();
33
+ headers.set("Authorization", `Bearer ${credential.token}`);
34
+ }
35
+ const response = await fetch(request, {
36
+ headers,
37
+ redirect: "error",
38
+ signal: AbortSignal.any([request.signal, AbortSignal.timeout(30000)]),
39
+ });
40
+ if (response.status === 401 && authenticated)
41
+ throw new LoginRequiredError();
42
+ return response;
43
+ };
44
+ }
@@ -0,0 +1,106 @@
1
+ import { inspect } from "../inspection/index.js";
2
+ import { doctor } from "../doctor/index.js";
3
+ import { environmentOperation } from "../environment/operations.js";
4
+ import { hookSchema } from "@barndog-ai/api-contract";
5
+ import { runtimeRequirements } from "../native/adapters.js";
6
+ import { homedir } from "node:os";
7
+ import { knowledgeGet, knowledgeList, knowledgeProblems, } from "../knowledge/index.js";
8
+ import { writeMcp, authenticateMcp, mcpVersions } from "../mcps/index.js";
9
+ import { developerAssets, developers, promote } from "../discovery/index.js";
10
+ import { selectAsset } from "../environment/remote.js";
11
+ import { testHook } from "../hooks/test.js";
12
+ import { gitOperation } from "../git-hosts/index.js";
13
+ import { readSettings } from "../../config/settings.js";
14
+ import { repoForOrigin, repoHookCompatibility, selectRepoAsset, showRepoAsset, validateFolder, } from "../git-workspace/assets.js";
15
+ import { migrate } from "../git-workspace/migrate.js";
16
+ import { listLocalAssets, moveLocalAssets } from "../git-workspace/move.js";
17
+ import { LOCAL_ORIGIN } from "../git-workspace/overlay.js";
18
+ import { updateImported } from "../imports/local.js";
19
+ import { adaptHook } from "../hooks/adapt.js";
20
+ export async function capability(action, options = {}, home = homedir()) {
21
+ if (action === "validate")
22
+ return validateFolder(options.directory ?? ".");
23
+ if (action === "local-list")
24
+ return listLocalAssets(home);
25
+ if (action === "local-move")
26
+ return moveLocalAssets({
27
+ names: options.names,
28
+ to: options.to,
29
+ as: options.as,
30
+ repo: options.repo,
31
+ server: options.server,
32
+ }, home);
33
+ if (action === "imports-update")
34
+ return updateImported(options.kind, options.name, { force: options.force, dryRun: options.dryRun }, home);
35
+ if (action === "promote" && options.origin === LOCAL_ORIGIN)
36
+ return moveLocalAssets({
37
+ names: [options.name],
38
+ kind: options.kind,
39
+ to: options.target,
40
+ as: options.newName === options.name ? undefined : options.newName,
41
+ }, home);
42
+ if (action === "migrate")
43
+ return migrate({ server: options.server, dryRun: options.dryRun }, home);
44
+ if (action === "show" || action === "hooks-compatibility") {
45
+ const settings = await readSettings(home);
46
+ const repo = settings && repoForOrigin(settings, home, options.origin);
47
+ if (repo) {
48
+ const asset = selectRepoAsset(await repo.model(), action === "show" ? options.kind : "hook", options.name, options.origin);
49
+ return action === "show"
50
+ ? showRepoAsset(asset)
51
+ : repoHookCompatibility(asset);
52
+ }
53
+ }
54
+ if (["whoami", "open", "repo-status"].includes(action))
55
+ return inspect(action, home);
56
+ if (action === "doctor")
57
+ return doctor(home);
58
+ if (action.startsWith("github-"))
59
+ return gitOperation(action.slice(7), options, home);
60
+ if (action === "knowledge-enable" || action === "knowledge-disable")
61
+ return environmentOperation(action, {}, home);
62
+ if (action === "knowledge-list")
63
+ return knowledgeList(home, options.always);
64
+ if (action === "knowledge-problems")
65
+ return knowledgeProblems(home);
66
+ if (action === "knowledge-get")
67
+ return knowledgeGet(options.name, home);
68
+ if (action === "mcp-create" || action === "mcp-update")
69
+ return writeMcp(options.name, options.origin, options.file, home, options.key, action === "mcp-update" ? options.expectedVersion : undefined);
70
+ if (action === "mcp-auth")
71
+ return authenticateMcp(options.name, options.origin, options.harness, home);
72
+ if (action === "mcp-versions")
73
+ return mcpVersions(options.name, options.origin, home);
74
+ if (action === "show")
75
+ return (await selectAsset(options.kind, options.name, options.origin, home)).asset;
76
+ if (action === "hooks-compatibility") {
77
+ const selected = await selectAsset("hook", options.name, options.origin, home);
78
+ const asset = hookSchema.parse(selected.asset);
79
+ return {
80
+ version: asset.version.number,
81
+ compatibility: await Promise.all(asset.compatibility.map(async (row) => ({
82
+ ...row,
83
+ runtimeIssue: row.implementation
84
+ ? await runtimeRequirements(row.harness, row.implementation.requirements)
85
+ : "No implementation for this harness",
86
+ }))),
87
+ };
88
+ }
89
+ if (action === "hooks-adapt")
90
+ return adaptHook(options.name, options.origin, options.targets, home);
91
+ if (action === "hooks-test")
92
+ return testHook(options.name, options.origin, {
93
+ harness: options.harness,
94
+ input: options.input,
95
+ event: options.event,
96
+ handler: options.handler,
97
+ timeout: options.timeout,
98
+ }, home);
99
+ if (action === "developers-list")
100
+ return developers(options.search, home);
101
+ if (action === "developers-assets")
102
+ return developerAssets(options.name, options.search, home);
103
+ if (action === "promote" || action === "fork")
104
+ return promote(options.kind, options.name, options.origin, options.target, options.newName, home, action === "fork", options.key);
105
+ throw new Error(`Unknown capability: ${action}`);
106
+ }
@@ -0,0 +1,102 @@
1
+ import { homedir } from "node:os";
2
+ import { mcpListSchema } from "@barndog-ai/api-contract";
3
+ import { readSettings } from "../../config/settings.js";
4
+ import { CliError } from "../../errors.js";
5
+ import { catalog as skillCatalog } from "../skills/remote.js";
6
+ import { hookCatalog } from "../collaboration/remote.js";
7
+ import { request } from "../environment/remote.js";
8
+ import { openRepoSource } from "../environment/workspace-source.js";
9
+ import { activeLocal, localOverlay } from "../git-workspace/overlay.js";
10
+ async function mcpCatalog(conn, home) {
11
+ const rows = [];
12
+ const seen = new Set();
13
+ let cursor;
14
+ do {
15
+ const page = await request(conn, `/v1/mcps?limit=100${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`, mcpListSchema, home);
16
+ for (const mcp of page.mcps) {
17
+ if (mcp.organizationId !== conn.organizationId)
18
+ throw new Error("Invalid catalog organization");
19
+ rows.push({
20
+ id: mcp.id,
21
+ kind: "mcp",
22
+ name: mcp.name,
23
+ origin: mcp.origin,
24
+ version: {
25
+ number: mcp.version.number,
26
+ description: mcp.version.definition.description,
27
+ },
28
+ });
29
+ }
30
+ if (page.nextCursor && seen.has(page.nextCursor))
31
+ throw new Error("Invalid catalog pagination");
32
+ if (page.nextCursor)
33
+ seen.add(page.nextCursor);
34
+ cursor = page.nextCursor ?? undefined;
35
+ } while (cursor);
36
+ return rows;
37
+ }
38
+ export async function searchCatalog(kind, home = homedir()) {
39
+ const shared = await sharedCatalog(kind, home);
40
+ const settings = await readSettings(home);
41
+ const overlay = settings && localOverlay(settings, home);
42
+ if (!overlay)
43
+ return shared;
44
+ const { model, assets } = await activeLocal(overlay, shared);
45
+ return [
46
+ ...shared,
47
+ ...assets
48
+ .filter((asset) => asset.kind === kind && !asset.invalid)
49
+ .map((asset) => ({
50
+ id: asset.id,
51
+ kind,
52
+ name: asset.name,
53
+ origin: {
54
+ type: "dev",
55
+ id: model.organizationId,
56
+ slug: "local",
57
+ localOnly: true,
58
+ },
59
+ version: {
60
+ number: 0,
61
+ description: asset.description,
62
+ label: asset.publishedVersion.slice(0, 7),
63
+ },
64
+ })),
65
+ ];
66
+ }
67
+ async function sharedCatalog(kind, home) {
68
+ const settings = await readSettings(home);
69
+ const repo = settings && openRepoSource(settings, home, { refresh: "auto" });
70
+ if (repo)
71
+ return (await repo.model()).assets
72
+ .filter((asset) => asset.kind === kind && !asset.invalid)
73
+ .map((asset) => ({
74
+ id: asset.id,
75
+ kind,
76
+ name: asset.name,
77
+ origin: asset.origin,
78
+ version: {
79
+ number: 0,
80
+ description: asset.description,
81
+ label: asset.publishedVersion.slice(0, 7),
82
+ },
83
+ }));
84
+ if (!settings || settings.version !== 2 || !settings.connection)
85
+ throw new CliError("This machine isn't connected to a BarnDog workspace.", "barndog init");
86
+ const conn = settings.connection;
87
+ if (kind === "mcp")
88
+ return mcpCatalog(conn, home);
89
+ const packages = kind === "skill"
90
+ ? await skillCatalog(conn, home)
91
+ : await hookCatalog(conn, home);
92
+ return packages.map((item) => ({
93
+ id: item.id,
94
+ kind,
95
+ name: item.name,
96
+ origin: item.origin,
97
+ version: {
98
+ number: item.version.number,
99
+ description: item.version.description,
100
+ },
101
+ }));
102
+ }