barndog 0.1.0 → 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 +11 -10
  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 +24 -11
  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,27 +1,28 @@
1
1
  import { onboardingEnvironment, selectedEnvironment, } from "./environment.js";
2
2
  import { hasRemoteSelections, selectionState, withSelection, } from "../../config/environment.js";
3
- import { withLocalSubscription } from "../git-workspace/overlay.js";
4
- import { localRepoSource } from "../git-workspace/source.js";
5
- import { openRepoSource } from "../environment/workspace-source.js";
3
+ import { withLocalSubscription } from "../workspace/overlay.js";
4
+ import { localRepoSource } from "../workspace/repo-source.js";
5
+ import { openRepoSource } from "../workspace/workspace-source.js";
6
6
  import { locked } from "../environment/transaction.js";
7
- import { homedir } from "node:os";
7
+ import { readSettings, saveSettings, } from "../../config/settings.js";
8
8
  import { detectHarnesses } from "../../harnesses/detect.js";
9
- import { readSettings, saveSettings, settingsPath, upgradeSettings, } from "../../config/settings.js";
10
- import { connectionContext } from "../skills/remote.js";
9
+ import { connectionContext } from "../auth/session.js";
10
+ import { defined } from "../../shared/lookup.js";
11
+ import { CliError } from "../../errors.js";
12
+ import { barndogPaths } from "../../config/paths.js";
11
13
  /** Only one source can be active, and API selections mean nothing without cloud. */
12
14
  function withoutSource(settings) {
13
15
  const { connection, gitWorkspace, localWorkspace, ...rest } = settings;
14
16
  void connection;
15
17
  void gitWorkspace;
16
18
  void localWorkspace;
17
- return { ...rest, skills: rest.skills.filter((s) => s.kind === "local") };
19
+ return rest;
18
20
  }
19
21
  function applyWorkspace(settings, chosen) {
20
- const upgraded = upgradeSettings(settings);
21
- const previousId = (upgraded.gitWorkspace ?? upgraded.localWorkspace)
22
+ const previousId = (settings.gitWorkspace ?? settings.localWorkspace)
22
23
  ?.workspaceId;
23
24
  const next = {
24
- ...withoutSource(upgraded),
25
+ ...withoutSource(settings),
25
26
  ...(chosen.kind === "git"
26
27
  ? { gitWorkspace: chosen.git }
27
28
  : { localWorkspace: chosen.local }),
@@ -36,10 +37,11 @@ function applyWorkspace(settings, chosen) {
36
37
  }
37
38
  /** Resolve saved selections and persist only after the caller supplies an explicit choice. */
38
39
  export async function initialize(options) {
39
- const home = options.home ?? homedir();
40
- return locked(home, async () => {
40
+ const { runtime } = options;
41
+ const { home } = runtime;
42
+ return locked(options.runtime, async () => {
41
43
  const previous = await readSettings(home);
42
- const detected = options.detected ?? (await detectHarnesses({ home }));
44
+ const detected = options.detected ?? (await detectHarnesses(runtime));
43
45
  const choices = detected.map((harness) => ({
44
46
  value: harness.id,
45
47
  name: harness.name,
@@ -49,14 +51,14 @@ export async function initialize(options) {
49
51
  const selected = await options.choose(choices);
50
52
  let next = previous
51
53
  ? { ...previous, harnesses: selected }
52
- : { version: 1, harnesses: selected, skills: [] };
54
+ : { harnesses: selected };
53
55
  if (options.workspace) {
54
56
  next = applyWorkspace(next, options.workspace);
55
57
  const model = next.environment === undefined && options.workspace.kind === "local"
56
- ? await openRepoSource(next, home).model()
58
+ ? await defined(openRepoSource(next, options.runtime), "A local workspace always has a source").model()
57
59
  : undefined;
58
60
  // One developer's folder has nothing to choose between: everything installs.
59
- if (model)
61
+ if (model) {
60
62
  next = withSelection(next, {
61
63
  subscriptions: [
62
64
  {
@@ -69,55 +71,56 @@ export async function initialize(options) {
69
71
  excludedAssetIds: [],
70
72
  disabledAssetIds: [],
71
73
  });
74
+ }
72
75
  }
73
76
  if (options.server) {
74
- const connection = await connectionContext(options.server, home);
75
- const upgraded = upgradeSettings(next);
76
- if (hasRemoteSelections(upgraded) &&
77
- upgraded.connection &&
78
- (upgraded.connection.server !== connection.server ||
79
- upgraded.connection.organizationId !== connection.organizationId ||
80
- upgraded.connection.developerId !== connection.developerId))
81
- throw new Error("Remove API selections before switching server, organization, or developer");
82
- if (upgraded.gitWorkspace || upgraded.localWorkspace) {
77
+ const connection = await connectionContext(options.server, options.runtime);
78
+ if (hasRemoteSelections(next) &&
79
+ next.connection &&
80
+ (next.connection.server !== connection.server ||
81
+ next.connection.organizationId !== connection.organizationId ||
82
+ next.connection.developerId !== connection.developerId)) {
83
+ throw new CliError("You have assets selected from the current server. Remove them before switching server, organization or developer.", "barndog status");
84
+ }
85
+ if (next.gitWorkspace || next.localWorkspace) {
83
86
  // Repo asset IDs mean nothing to a server, so those choices can't carry over.
84
- const { environment, localNames, ...cleared } = withoutSource(upgraded);
87
+ const { environment, localNames, ...cleared } = withoutSource(next);
85
88
  void environment;
86
89
  void localNames;
87
90
  next = { ...cleared, connection };
88
91
  }
89
- else
90
- next = { ...upgraded, connection };
92
+ else {
93
+ next = { ...next, connection };
94
+ }
91
95
  }
92
- if (options.chooseEnvironment &&
93
- next.version === 2 &&
94
- (next.connection || next.gitWorkspace)) {
95
- const choices = await onboardingEnvironment(next, home);
96
+ if (options.chooseEnvironment && (next.connection || next.gitWorkspace)) {
97
+ const choices = await onboardingEnvironment(next, options.runtime);
96
98
  next = selectedEnvironment(next, choices, await options.chooseEnvironment(choices));
97
99
  }
98
100
  if (options.keepLocal) {
99
- const kept = await localRepoSource(options.keepLocal, home).model();
101
+ const kept = await localRepoSource(options.keepLocal, options.runtime).model();
100
102
  const settings = {
101
- ...upgradeSettings(next),
103
+ ...next,
102
104
  localWorkspace: options.keepLocal,
103
105
  };
104
106
  next = withSelection(settings, withLocalSubscription(selectionState(settings), kept));
105
107
  }
106
- if (next.version === 2 &&
107
- (next.connection || next.gitWorkspace || next.localWorkspace)) {
108
+ if (next.connection || next.gitWorkspace || next.localWorkspace) {
108
109
  next = { ...next, knowledge: next.knowledge ?? true };
109
110
  }
110
111
  if (options.confirm && !(await options.confirm(next))) {
111
112
  return {
112
- configPath: settingsPath(home),
113
+ configPath: barndogPaths(home).settings,
113
114
  harnesses: selected,
114
115
  cancelled: true,
115
116
  };
116
117
  }
117
- if (options.apply)
118
+ if (options.apply) {
118
119
  await options.apply(next);
119
- else
120
+ }
121
+ else {
120
122
  await saveSettings(next, home);
121
- return { configPath: settingsPath(home), harnesses: selected };
123
+ }
124
+ return { configPath: barndogPaths(home).settings, harnesses: selected };
122
125
  });
123
126
  }
@@ -1,14 +1,22 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { promisify } from "node:util";
3
- import { homedir } from "node:os";
4
3
  import { z } from "zod";
5
4
  import { normalizeRepositoryRemote, repositorySchema, teamSchema, } from "@barndog-ai/api-contract";
6
- import { connection } from "../collaboration/remote.js";
7
- import { request } from "../environment/remote.js";
5
+ import { connection } from "../server/connection.js";
6
+ import { parsed } from "../server/client.js";
7
+ import { errorCode } from "../../shared/values.js";
8
+ import { only } from "../../shared/lookup.js";
9
+ import { apiClient } from "../auth/transport.js";
8
10
  const execute = promisify(execFile);
9
- export async function localRepository(cwd = process.cwd()) {
11
+ /**
12
+ * Inspects the Git root and normalized fetch remotes at cwd without contacting
13
+ * hosts; missing Git or repository yields no root.
14
+ */
15
+ export async function localRepository(runtime) {
16
+ const { cwd } = runtime;
10
17
  const git = async (...args) => (await execute("git", ["-C", cwd, ...args], {
11
18
  timeout: 5000,
19
+ env: { ...runtime.env },
12
20
  maxBuffer: 65536,
13
21
  })).stdout.trim();
14
22
  let root;
@@ -16,9 +24,12 @@ export async function localRepository(cwd = process.cwd()) {
16
24
  root = await git("rev-parse", "--show-toplevel");
17
25
  }
18
26
  catch (error) {
19
- if (error.code === "ENOENT" ||
20
- /not a git repository/.test(String(error.stderr)))
27
+ if (errorCode(error) === "ENOENT" ||
28
+ (error instanceof Error &&
29
+ "stderr" in error &&
30
+ /not a git repository/.test(String(error.stderr)))) {
21
31
  return { root: null, remotes: [] };
32
+ }
22
33
  throw error;
23
34
  }
24
35
  const names = (await git("remote")).split("\n").filter(Boolean);
@@ -27,20 +38,26 @@ export async function localRepository(cwd = process.cwd()) {
27
38
  // Read configured fetch URLs without contacting a Git host or running hooks.
28
39
  for (const url of (await git("remote", "get-url", "--all", name)).split("\n")) {
29
40
  const key = normalizeRepositoryRemote(url);
30
- if (key)
41
+ if (key) {
31
42
  remotes.add(key);
43
+ }
32
44
  }
33
45
  }
34
46
  return { root, remotes: [...remotes] };
35
47
  }
36
- export async function repositoryContext(home = homedir(), cwd = process.cwd(), expected) {
37
- const local = await localRepository(cwd);
38
- const conn = expected ?? (await connection(home));
39
- const repositories = await request(conn, "/v1/repositories", z.array(repositorySchema), home);
48
+ /**
49
+ * Matches local remotes to server repositories and returns owning team and
50
+ * policy scopes; multiple matches remain ambiguous.
51
+ */
52
+ export async function repositoryContext(runtime, expected) {
53
+ const local = await localRepository(runtime);
54
+ const conn = expected ?? (await connection(runtime));
55
+ const client = apiClient(conn.server, runtime);
56
+ const repositories = await parsed(z.array(repositorySchema), client.GET("/v1/repositories"));
40
57
  const matches = repositories.filter((repo) => repo.gitRemote && local.remotes.includes(repo.gitRemote));
41
- const repository = matches.length === 1 ? matches[0] : null;
58
+ const repository = only(matches) ?? null;
42
59
  const teams = repository
43
- ? await request(conn, "/v1/teams", z.array(teamSchema), home)
60
+ ? await parsed(z.array(teamSchema), client.GET("/v1/teams"))
44
61
  : [];
45
62
  return {
46
63
  ...local,
@@ -0,0 +1,58 @@
1
+ import { z } from "zod";
2
+ import { environmentCatalogSchema } from "@barndog-ai/api-contract";
3
+ import { connection } from "./connection.js";
4
+ import { connectionContext } from "../auth/session.js";
5
+ import { assetKinds, assetNotFound, } from "../asset-kinds/index.js";
6
+ import { only } from "../../shared/lookup.js";
7
+ import { matchesOrigin } from "./origin.js";
8
+ import { apiClient } from "../auth/transport.js";
9
+ import { parsed, responseData } from "./client.js";
10
+ import { CliError } from "../../errors.js";
11
+ /**
12
+ * Fetches the environment catalog and authenticated connection, rejecting a
13
+ * mismatch with an expected saved identity.
14
+ */
15
+ export async function environmentCatalog(runtime, expected) {
16
+ const conn = expected
17
+ ? await connectionContext(expected.server, runtime)
18
+ : await connection(runtime);
19
+ if (expected &&
20
+ (conn.organizationId !== expected.organizationId ||
21
+ conn.developerId !== expected.developerId)) {
22
+ throw new CliError("You're signed in as a different organization or developer than this machine was set up with.", "barndog login");
23
+ }
24
+ return {
25
+ connection: conn,
26
+ catalog: await parsed(environmentCatalogSchema, apiClient(conn.server, runtime).GET("/v1/environment/catalog")),
27
+ };
28
+ }
29
+ export async function getAsset(kind, id, conn, runtime) {
30
+ return assetKinds[kind].schema.parse(responseData(await assetRoutes[kind](apiClient(conn.server, runtime),
31
+ // Only a UUID may reach the URL.
32
+ z.uuidv4().parse(id))));
33
+ }
34
+ /** The route that returns one published asset of each kind. */
35
+ const assetRoutes = {
36
+ skill: (client, id) => client.GET("/v1/skills/{id}", { params: { path: { id } } }),
37
+ hook: (client, id) => client.GET("/v1/hooks/{id}", { params: { path: { id } } }),
38
+ mcp: (client, id) => client.GET("/v1/mcps/{id}", { params: { path: { id } } }),
39
+ };
40
+ /**
41
+ * Resolves one catalog asset by name or ID and origin, then fetches its
42
+ * published content; ambiguous matches fail.
43
+ */
44
+ export async function selectAsset(kind, name, origin, runtime) {
45
+ const { connection: conn, catalog } = await environmentCatalog(runtime);
46
+ const matches = catalog.assets.filter((a) => a.kind === kind &&
47
+ (a.id === name || a.name === name) &&
48
+ matchesOrigin(a.origin, origin, conn));
49
+ const reference = only(matches);
50
+ if (!reference) {
51
+ throw assetNotFound(kind, name, origin);
52
+ }
53
+ return {
54
+ connection: conn,
55
+ reference,
56
+ asset: await getAsset(kind, reference.id, conn, runtime),
57
+ };
58
+ }
@@ -0,0 +1,13 @@
1
+ import { defined } from "../../shared/lookup.js";
2
+ /** The body of a successful response; the client throws ApiError for failures. */
3
+ export function responseData(response) {
4
+ return defined(response.data, "The server sent an empty response");
5
+ }
6
+ /**
7
+ * Awaits a typed-client call and validates its body. The client's types come
8
+ * from the server's OpenAPI document and check the request; the schema checks
9
+ * what this server actually sent.
10
+ */
11
+ export async function parsed(schema, call) {
12
+ return schema.parse(responseData(await call));
13
+ }
@@ -0,0 +1,37 @@
1
+ import { contextSchema } from "@barndog-ai/api-contract";
2
+ import { readSettings } from "../../config/settings.js";
3
+ import { CliError } from "../../errors.js";
4
+ import { apiClient } from "../auth/transport.js";
5
+ /**
6
+ * The saved Cloud connection, after asking the server who is signed in and
7
+ * checking it is still that organization and developer. Pass `expected` to also
8
+ * require a particular connection, such as the one a working copy was made
9
+ * with. Fails with a fix in a Git or local workspace, which has no server.
10
+ */
11
+ export async function connection(runtime, expected) {
12
+ const { home } = runtime;
13
+ const settings = await readSettings(home);
14
+ if (settings &&
15
+ !settings.connection &&
16
+ (settings.gitWorkspace || settings.localWorkspace)) {
17
+ throw new CliError(`This needs a BarnDog Cloud Workspace. This machine keeps its assets in ${settings.gitWorkspace ? "a Git repo" : "a local folder"}.`, settings.gitWorkspace
18
+ ? "barndog migrate --to <server>"
19
+ : "barndog init --server <url>");
20
+ }
21
+ if (!settings || !settings.connection) {
22
+ throw new CliError("This machine isn't connected to a BarnDog workspace.", "barndog init");
23
+ }
24
+ const saved = settings.connection;
25
+ if (expected &&
26
+ (expected.server !== saved.server ||
27
+ expected.organizationId !== saved.organizationId ||
28
+ expected.developerId !== saved.developerId)) {
29
+ throw new CliError("This working copy belongs to another server, organization or developer than the one you're signed in to.", "barndog whoami");
30
+ }
31
+ const actor = contextSchema.parse((await apiClient(saved.server, runtime).GET("/v1/context")).data);
32
+ if (actor.organization.id !== saved.organizationId ||
33
+ actor.developer.id !== saved.developerId) {
34
+ throw new CliError("You're signed in as a different organization or developer than this machine was set up with.", "barndog login");
35
+ }
36
+ return saved;
37
+ }
@@ -0,0 +1,74 @@
1
+ import { z } from "zod";
2
+ import { contextSchema, memberSchema, scopeSchema, } from "@barndog-ai/api-contract";
3
+ import { CliError } from "../../errors.js";
4
+ import { only } from "../../shared/lookup.js";
5
+ import { splitOrigin } from "../../shared/patterns.js";
6
+ import { apiClient } from "../auth/transport.js";
7
+ import { parsed } from "./client.js";
8
+ /**
9
+ * Whether an asset or scope belongs to the origin `selector` names: `org`,
10
+ * `me`, `local`, `team/<slug>`, `repo/<slug>`, `dev/<slug>`, or a type with an
11
+ * ID instead of a slug.
12
+ */
13
+ export function matchesOrigin(origin, selector, conn) {
14
+ if (selector === "local") {
15
+ return origin.localOnly === true;
16
+ }
17
+ if (selector === "org") {
18
+ return origin.type === "org" && origin.id === conn.organizationId;
19
+ }
20
+ if (selector === "me") {
21
+ return origin.type === "dev" && origin.id === conn.developerId;
22
+ }
23
+ const { type, value = "" } = splitOrigin(selector);
24
+ return origin.type === type && [origin.id, origin.slug].includes(value);
25
+ }
26
+ /** The scopes the developer can see: the organization, teams, repositories and their own. */
27
+ export function scopes(conn, runtime) {
28
+ return parsed(z.array(scopeSchema), apiClient(conn.server, runtime).GET("/v1/scopes"));
29
+ }
30
+ /**
31
+ * The scope an origin selector names, among those the developer can use.
32
+ * Organization admins can also name any member's personal scope.
33
+ */
34
+ export async function selectOrigin(selector, conn, runtime) {
35
+ const visible = await scopes(conn, runtime);
36
+ const matches = visible.filter((s) => matchesOrigin(s, selector, conn));
37
+ const personal = splitOrigin(selector);
38
+ if (!matches.length &&
39
+ personal.type === "dev" &&
40
+ personal.value !== undefined) {
41
+ const actor = contextSchema.parse((await apiClient(conn.server, runtime).GET("/v1/context")).data);
42
+ if (actor.developer.role === "organization_admin") {
43
+ const members = z
44
+ .array(memberSchema)
45
+ .parse((await apiClient(conn.server, runtime).GET("/v1/organization/members")).data);
46
+ for (const member of members) {
47
+ const origin = {
48
+ type: "dev",
49
+ id: member.id,
50
+ slug: member.slug,
51
+ name: member.name,
52
+ canPublish: true,
53
+ };
54
+ if (matchesOrigin(origin, selector, conn)) {
55
+ matches.push(origin);
56
+ }
57
+ }
58
+ }
59
+ }
60
+ const match = only(matches);
61
+ if (!match) {
62
+ throw new CliError(`No scope named ${selector} that you can use.`, "barndog sets list");
63
+ }
64
+ return match;
65
+ }
66
+ /** Human scope label such as local, org, team/engineering, repo/web or dev/john. */
67
+ export function originLabel(origin) {
68
+ if (origin.localOnly || origin.type === "local") {
69
+ return "local";
70
+ }
71
+ return origin.type === "org"
72
+ ? "org"
73
+ : `${origin.type}/${origin.slug ?? origin.id ?? "unknown"}`;
74
+ }
@@ -0,0 +1,24 @@
1
+ /** The largest page the server's list routes return. */
2
+ export const PAGE_SIZE = 100;
3
+ /**
4
+ * Every item of a cursor-paginated list, fetching pages until the server stops
5
+ * returning a cursor. A cursor the server already returned means it would loop
6
+ * forever, so that fails as a broken server response.
7
+ */
8
+ export async function allPages(fetchPage) {
9
+ const items = [];
10
+ const seen = new Set();
11
+ let cursor;
12
+ do {
13
+ const page = await fetchPage(cursor);
14
+ items.push(...page.items);
15
+ if (page.nextCursor && seen.has(page.nextCursor)) {
16
+ throw new Error("The server sent an invalid page of results");
17
+ }
18
+ if (page.nextCursor) {
19
+ seen.add(page.nextCursor);
20
+ }
21
+ cursor = page.nextCursor ?? undefined;
22
+ } while (cursor);
23
+ return items;
24
+ }
@@ -0,0 +1,42 @@
1
+ import { contextSchema, listOutputSchema, } from "@barndog-ai/api-contract";
2
+ import { apiClient } from "../auth/transport.js";
3
+ import { CliError } from "../../errors.js";
4
+ import { allPages } from "../server/pages.js";
5
+ /**
6
+ * Every published Skill the developer can see, page by page. Throws when the
7
+ * server now reports another organization or developer than `connection`, or
8
+ * answers with a broken page.
9
+ */
10
+ export async function publishedSkills(connection, runtime) {
11
+ const client = apiClient(connection.server, runtime);
12
+ const context = contextSchema.parse((await client.GET("/v1/context")).data);
13
+ if (context.organization.id !== connection.organizationId ||
14
+ context.developer.id !== connection.developerId) {
15
+ throw new CliError("The server's organization or developer changed since this machine was set up.", "barndog init");
16
+ }
17
+ const skills = await allPages(async (cursor) => {
18
+ const page = listOutputSchema.parse((await client.GET("/v1/skills", {
19
+ params: { query: { cursor, limit: 100 } },
20
+ })).data);
21
+ if (page.skills.some((skill) => skill.organizationId !== connection.organizationId)) {
22
+ throw new Error("The server sent a catalog page for another organization");
23
+ }
24
+ return { items: page.skills, nextCursor: page.nextCursor };
25
+ });
26
+ if (new Set(skills.map((skill) => skill.id)).size !== skills.length) {
27
+ throw new Error("The server sent the same Skill twice in its catalog");
28
+ }
29
+ return skills;
30
+ }
31
+ export async function skillCatalog(connection, runtime) {
32
+ return (await publishedSkills(connection, runtime)).map((skill) => ({
33
+ id: skill.id,
34
+ kind: "skill",
35
+ name: skill.name,
36
+ origin: skill.origin,
37
+ version: {
38
+ number: skill.version.number,
39
+ description: skill.version.description,
40
+ },
41
+ }));
42
+ }
@@ -0,0 +1,57 @@
1
+ import { localPath } from "../../platform.js";
2
+ import { hookMetadata } from "@barndog-ai/api-contract/package";
3
+ import { CliError } from "../../errors.js";
4
+ import { matchesOrigin } from "../server/origin.js";
5
+ import { originLabel } from "../server/origin.js";
6
+ import { loadWorkspace, } from "./format.js";
7
+ import { folderSnapshot } from "./snapshot.js";
8
+ import { openRepoSource } from "./workspace-source.js";
9
+ import { LOCAL_ORIGIN, localOverlay } from "./overlay.js";
10
+ import { assetNotFound } from "../asset-kinds/index.js";
11
+ import { only } from "../../shared/lookup.js";
12
+ /** The repo-backed source that answers for an origin, if any. */
13
+ export function repoForOrigin(settings, runtime, origin) {
14
+ const overlay = localOverlay(settings, runtime);
15
+ return origin === LOCAL_ORIGIN && overlay
16
+ ? overlay
17
+ : openRepoSource(settings, runtime, { refresh: "auto" });
18
+ }
19
+ /** Finds one asset by name and origin, the way cloud commands address assets. */
20
+ export function selectRepoAsset(model, kind, name, origin) {
21
+ const matches = model.assets.filter((asset) => asset.kind === kind &&
22
+ (asset.id === name || asset.name === name) &&
23
+ (origin === LOCAL_ORIGIN || matchesOrigin(asset.origin, origin, model)));
24
+ const asset = only(matches);
25
+ if (!asset) {
26
+ throw assetNotFound(kind, name, origin);
27
+ }
28
+ if (asset.invalid) {
29
+ throw new CliError(`${asset.path} is invalid: ${asset.invalid}`);
30
+ }
31
+ return asset;
32
+ }
33
+ export function showRepoAsset(asset) {
34
+ return {
35
+ id: asset.id,
36
+ kind: asset.kind,
37
+ name: asset.name,
38
+ origin: originLabel(asset.origin),
39
+ path: asset.path,
40
+ version: asset.publishedVersion,
41
+ description: asset.description,
42
+ ...(asset.definition ? { definition: asset.definition } : {}),
43
+ ...(asset.kind === "hook" ? { manifest: hookMetadata(asset.entries) } : {}),
44
+ };
45
+ }
46
+ /** Checks a workspace folder without installing anything, for use in repo CI. */
47
+ export async function validateFolder(directory, runtime) {
48
+ const model = await loadWorkspace(await folderSnapshot(localPath(directory, runtime), runtime));
49
+ if (model.problems.length) {
50
+ throw new CliError(`${model.problems.length} problem${model.problems.length === 1 ? "" : "s"} found:\n${model.problems.map((problem) => ` ${problem.path}: ${problem.reason}`).join("\n")}`, "Fix the files listed, then validate again");
51
+ }
52
+ return {
53
+ workspace: model.config.name,
54
+ assets: model.assets.length,
55
+ knowledge: model.knowledge.length,
56
+ };
57
+ }
@@ -0,0 +1,34 @@
1
+ import { mcpSchema } from "@barndog-ai/api-contract";
2
+ import { assetKinds } from "../asset-kinds/index.js";
3
+ import { cacheKey, cachedPackage } from "./packages.js";
4
+ import { environmentCatalog, getAsset } from "../server/catalog.js";
5
+ import { CliError } from "../../errors.js";
6
+ async function currentAsset(kind, reference, conn, runtime) {
7
+ const data = await getAsset(kind, reference.id, conn, runtime);
8
+ if (data.id !== reference.id ||
9
+ data.version.id !== reference.publishedVersion ||
10
+ data.name !== reference.name ||
11
+ data.organizationId !== conn.organizationId) {
12
+ throw new CliError("The catalog changed while syncing.", "barndog sync");
13
+ }
14
+ return data;
15
+ }
16
+ /**
17
+ * Adapts an authenticated cloud connection to lazy catalog, package-cache and
18
+ * MCP reads for synchronization.
19
+ */
20
+ export function cloudSource(conn, runtime) {
21
+ return {
22
+ cacheKey: cacheKey(conn),
23
+ journal: conn,
24
+ catalog: async () => (await environmentCatalog(runtime, conn)).catalog,
25
+ packageFolder: async (kind, reference) => {
26
+ const data = await currentAsset(kind, reference, conn, runtime);
27
+ return cachedPackage(kind, assetKinds[kind].schema.parse(data), conn, runtime);
28
+ },
29
+ mcpDefinition: async (reference) => mcpSchema.parse(await currentAsset("mcp", reference, conn, runtime))
30
+ .version.definition,
31
+ invalidAssets: () => Promise.resolve(new Map()),
32
+ notices: () => [],
33
+ };
34
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Package folders on disk: reading one to submit, writing one BarnDog
3
+ * fetched. Package paths always use `/`; local paths only appear at the
4
+ * filesystem calls.
5
+ */
6
+ import { lstat } from "node:fs/promises";
7
+ import { join } from "node:path";
8
+ import { readDirectory as readPackageDirectory } from "@barndog-ai/api-contract/collaboration";
9
+ import { writePackage as writePackageFiles, packageFingerprint, } from "@barndog-ai/api-contract/package";
10
+ import { assertPackagePaths, fileExecutable, isWindows, } from "../../platform.js";
11
+ import { readTree } from "./tree.js";
12
+ /**
13
+ * A package folder's files. Windows keeps no executable bit, so there a
14
+ * file's flag comes from the same path in `known`, the files BarnDog last wrote
15
+ * here (see `fileExecutable()`).
16
+ */
17
+ export async function readDirectory(directory, runtime, known = []) {
18
+ const entries = await readPackageDirectory(directory);
19
+ if (!isWindows(runtime.platform)) {
20
+ return entries;
21
+ }
22
+ const flags = new Map(known.map((entry) => [entry.path, entry.executable]));
23
+ return Promise.all(entries.map(async (entry) => {
24
+ const path = join(directory, entry.path);
25
+ return {
26
+ ...entry,
27
+ executable: await fileExecutable(path, (await lstat(path)).mode, runtime, flags.get(entry.path)),
28
+ };
29
+ }));
30
+ }
31
+ export async function writePackage(directory, entries, runtime) {
32
+ assertPackagePaths(entries, runtime.platform);
33
+ await writePackageFiles(directory, entries);
34
+ }
35
+ /** What `readTree()` sees in the folder, so compare it only with another one. */
36
+ export async function directoryFingerprint(directory, runtime) {
37
+ return packageFingerprint(await readTree(directory, runtime));
38
+ }