barndog 0.1.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/README.md +31 -28
  2. package/dist/cli.js +11 -7
  3. package/dist/commands/add.js +34 -21
  4. package/dist/commands/adopt.js +91 -0
  5. package/dist/commands/arguments.js +12 -0
  6. package/dist/commands/asset-install.js +161 -0
  7. package/dist/commands/asset-list.js +126 -0
  8. package/dist/commands/asset-share.js +94 -0
  9. package/dist/commands/auth.js +4 -0
  10. package/dist/commands/availability.js +72 -27
  11. package/dist/commands/capabilities.js +79 -417
  12. package/dist/commands/collaboration.js +212 -108
  13. package/dist/commands/environment.js +18 -411
  14. package/dist/commands/github.js +200 -0
  15. package/dist/commands/harnesses.js +74 -0
  16. package/dist/commands/helpers.js +39 -0
  17. package/dist/commands/hooks.js +87 -0
  18. package/dist/commands/init.js +4 -2
  19. package/dist/commands/knowledge.js +73 -0
  20. package/dist/commands/mcp-env.js +78 -0
  21. package/dist/commands/mcp.js +64 -0
  22. package/dist/commands/origin.js +21 -23
  23. package/dist/commands/people.js +51 -0
  24. package/dist/commands/sets.js +141 -0
  25. package/dist/commands/status.js +36 -25
  26. package/dist/commands/sync.js +13 -5
  27. package/dist/commands/workspace.js +75 -23
  28. package/dist/config/environment.js +13 -27
  29. package/dist/config/paths.js +81 -0
  30. package/dist/config/selection.js +30 -0
  31. package/dist/config/settings.js +99 -108
  32. package/dist/config/state.js +67 -55
  33. package/dist/entry/knowledge-startup.js +32 -0
  34. package/dist/entry/mcp-launch.js +71 -0
  35. package/dist/entry/opencode-plugin.js +62 -0
  36. package/dist/{features/git-workspace/startup.js → entry/workspace-startup.js} +7 -2
  37. package/dist/errors.js +198 -55
  38. package/dist/features/adoption/adopt.js +234 -0
  39. package/dist/features/adoption/copies.js +29 -0
  40. package/dist/features/adoption/originals.js +116 -0
  41. package/dist/features/adoption/record.js +120 -0
  42. package/dist/features/adoption/restore.js +28 -0
  43. package/dist/features/adoption/scan.js +482 -0
  44. package/dist/features/adoption/undo.js +42 -0
  45. package/dist/features/asset-kinds/index.js +129 -0
  46. package/dist/features/asset-selection/index.js +51 -19
  47. package/dist/features/auth/credentials.js +80 -54
  48. package/dist/features/auth/session.js +83 -49
  49. package/dist/features/auth/transport.js +69 -17
  50. package/dist/features/catalog/index.js +32 -61
  51. package/dist/features/collaboration/api.js +160 -0
  52. package/dist/features/collaboration/index.js +321 -233
  53. package/dist/features/collaboration/remote.js +35 -115
  54. package/dist/features/collaboration/results.js +2 -0
  55. package/dist/features/collaboration/workspace-git.js +242 -152
  56. package/dist/features/collaboration/workspace-github.js +118 -54
  57. package/dist/features/collaboration/workspace-store.js +157 -97
  58. package/dist/features/collaboration/workspace.js +278 -173
  59. package/dist/features/discovery/index.js +68 -57
  60. package/dist/features/doctor/index.js +56 -26
  61. package/dist/features/environment/auto-sync.js +28 -27
  62. package/dist/features/environment/harnesses.js +36 -0
  63. package/dist/features/environment/moves.js +171 -0
  64. package/dist/features/environment/names.js +73 -49
  65. package/dist/features/environment/operations.js +322 -229
  66. package/dist/features/environment/own-entries.js +89 -0
  67. package/dist/features/environment/settle-names.js +91 -0
  68. package/dist/features/environment/stage.js +202 -0
  69. package/dist/features/environment/sync.js +127 -487
  70. package/dist/features/environment/transaction.js +179 -147
  71. package/dist/features/environment/writes.js +243 -0
  72. package/dist/features/github/account.js +25 -0
  73. package/dist/features/github/connections.js +119 -0
  74. package/dist/features/github/pulls.js +118 -0
  75. package/dist/features/hooks/adapt.js +32 -25
  76. package/dist/features/hooks/catalog.js +28 -0
  77. package/dist/features/hooks/compatibility.js +55 -0
  78. package/dist/features/hooks/divergence.js +36 -12
  79. package/dist/features/hooks/test.js +91 -66
  80. package/dist/features/hooks/types.js +1 -0
  81. package/dist/features/imports/discover.js +133 -60
  82. package/dist/features/imports/folder.js +48 -14
  83. package/dist/features/imports/local.js +127 -135
  84. package/dist/features/imports/remote.js +46 -26
  85. package/dist/features/inspection/index.js +17 -17
  86. package/dist/features/inventory/index.js +111 -111
  87. package/dist/features/inventory/show.js +74 -0
  88. package/dist/features/knowledge/index.js +69 -49
  89. package/dist/features/mcps/catalog.js +31 -0
  90. package/dist/features/mcps/import.js +369 -0
  91. package/dist/features/mcps/index.js +104 -50
  92. package/dist/features/mcps/values.js +33 -0
  93. package/dist/features/migration/migrate.js +263 -0
  94. package/dist/features/migration/move.js +448 -0
  95. package/dist/features/migration/promote.js +26 -0
  96. package/dist/features/native/adapters.js +69 -96
  97. package/dist/features/native/configuration.js +134 -84
  98. package/dist/features/native/hook-shell.js +55 -0
  99. package/dist/features/native/plugin-module.js +56 -0
  100. package/dist/features/native/secret-values.js +74 -0
  101. package/dist/features/onboarding/environment.js +67 -34
  102. package/dist/features/onboarding/setup.js +43 -40
  103. package/dist/features/repositories/context.js +30 -13
  104. package/dist/features/secrets/index.js +77 -0
  105. package/dist/features/server/catalog.js +58 -0
  106. package/dist/features/server/client.js +13 -0
  107. package/dist/features/server/connection.js +37 -0
  108. package/dist/features/server/origin.js +74 -0
  109. package/dist/features/server/pages.js +24 -0
  110. package/dist/features/skills/catalog.js +42 -0
  111. package/dist/features/workspace/assets.js +57 -0
  112. package/dist/features/workspace/cloud-source.js +34 -0
  113. package/dist/features/workspace/directory.js +38 -0
  114. package/dist/features/{git-workspace → workspace}/format.js +121 -54
  115. package/dist/features/workspace/git.js +221 -0
  116. package/dist/features/workspace/installed.js +92 -0
  117. package/dist/features/{git-workspace → workspace}/overlay.js +53 -46
  118. package/dist/features/workspace/packages.js +173 -0
  119. package/dist/features/{git-workspace → workspace}/publish.js +120 -64
  120. package/dist/features/workspace/repo-source.js +193 -0
  121. package/dist/features/{git-workspace → workspace}/setup.js +72 -45
  122. package/dist/features/{git-workspace → workspace}/snapshot.js +60 -19
  123. package/dist/features/workspace/source.js +1 -0
  124. package/dist/features/workspace/tree.js +52 -0
  125. package/dist/features/workspace/workspace-source.js +27 -0
  126. package/dist/harnesses/claude.js +23 -1
  127. package/dist/harnesses/codex.js +67 -1
  128. package/dist/harnesses/cursor.js +22 -1
  129. package/dist/harnesses/detect.js +6 -50
  130. package/dist/harnesses/formats.js +52 -0
  131. package/dist/harnesses/opencode.js +108 -0
  132. package/dist/harnesses/registry.js +35 -2
  133. package/dist/platform.js +403 -0
  134. package/dist/program.js +275 -56
  135. package/dist/runtime.js +1 -0
  136. package/dist/shared/cli-error.js +22 -0
  137. package/dist/shared/constants.js +32 -0
  138. package/dist/shared/files.js +107 -0
  139. package/dist/shared/lock.js +113 -0
  140. package/dist/shared/lookup.js +11 -0
  141. package/dist/shared/patterns.js +102 -0
  142. package/dist/shared/shell.js +20 -0
  143. package/dist/shared/values.js +26 -0
  144. package/dist/ui/add-asset.js +41 -400
  145. package/dist/ui/add-hook.js +219 -0
  146. package/dist/ui/add-mcp.js +170 -0
  147. package/dist/ui/add-prompts.js +47 -0
  148. package/dist/ui/add-skills.js +117 -0
  149. package/dist/ui/adopt.js +197 -0
  150. package/dist/ui/asset-list.js +31 -13
  151. package/dist/ui/assets.js +38 -47
  152. package/dist/ui/auth.js +45 -34
  153. package/dist/ui/clash.js +10 -6
  154. package/dist/ui/collaboration.js +116 -44
  155. package/dist/ui/connection.js +17 -6
  156. package/dist/ui/decision-error.js +24 -0
  157. package/dist/ui/environment-onboarding.js +35 -13
  158. package/dist/ui/format.js +66 -18
  159. package/dist/ui/harness-picker.js +18 -0
  160. package/dist/ui/hook-compatibility.js +14 -6
  161. package/dist/ui/mcp.js +28 -3
  162. package/dist/ui/move.js +57 -6
  163. package/dist/ui/onboarding.js +148 -95
  164. package/dist/ui/options.js +9 -0
  165. package/dist/ui/output.js +108 -43
  166. package/dist/ui/package-details.js +34 -0
  167. package/dist/ui/pick.js +45 -33
  168. package/dist/ui/scope-install.js +18 -7
  169. package/dist/ui/secret-input.js +19 -0
  170. package/dist/ui/selection.js +17 -11
  171. package/dist/ui/theme.js +37 -14
  172. package/dist/version.js +6 -3
  173. package/package.json +13 -3
  174. package/dist/features/capabilities/index.js +0 -106
  175. package/dist/features/collaboration/domain.js +0 -90
  176. package/dist/features/environment/cloud-source.js +0 -27
  177. package/dist/features/environment/installed.js +0 -124
  178. package/dist/features/environment/packages.js +0 -120
  179. package/dist/features/environment/remote.js +0 -71
  180. package/dist/features/environment/workspace-source.js +0 -19
  181. package/dist/features/git-hosts/index.js +0 -148
  182. package/dist/features/git-workspace/assets.js +0 -71
  183. package/dist/features/git-workspace/git.js +0 -135
  184. package/dist/features/git-workspace/migrate.js +0 -188
  185. package/dist/features/git-workspace/move.js +0 -337
  186. package/dist/features/git-workspace/source.js +0 -159
  187. package/dist/features/imports/mcp.js +0 -219
  188. package/dist/features/knowledge/startup.js +0 -25
  189. package/dist/features/native/mcp-launch.js +0 -57
  190. package/dist/features/skills/install.js +0 -25
  191. package/dist/features/skills/remote.js +0 -177
  192. package/dist/features/skills/sync.js +0 -121
  193. package/dist/features/skills/validation.js +0 -34
  194. /package/dist/features/environment/{source.js → events.js} +0 -0
@@ -1,10 +1,21 @@
1
1
  import { z } from "zod";
2
- import { scopeSchema, teamMemberSchema, } from "@barndog-ai/api-contract";
3
- import { environmentCatalog, request } from "../environment/remote.js";
4
- import { openRepoSource } from "../environment/workspace-source.js";
5
- import { selectionState, withSelection, selectionStateSchema, } from "../../config/environment.js";
6
- export async function onboardingEnvironment(settings, home) {
7
- const repo = openRepoSource(settings, home, { refresh: "none" });
2
+ import { teamMemberSchema } from "@barndog-ai/api-contract";
3
+ import { environmentCatalog, } from "../server/catalog.js";
4
+ import { parsed } from "../server/client.js";
5
+ import { openRepoSource } from "../workspace/workspace-source.js";
6
+ import { selectionState, withSelection } from "../../config/environment.js";
7
+ import { selectionStateSchema, } from "../../config/selection.js";
8
+ import { CliError } from "../../errors.js";
9
+ import { apiClient } from "../auth/transport.js";
10
+ import { scopes } from "../server/origin.js";
11
+ /** Limit onboarding team requests to six concurrent operations. */
12
+ const TEAM_FETCH_CONCURRENCY = 6;
13
+ /**
14
+ * Gathers what setup offers, from the Git or local workspace as last fetched
15
+ * (without fetching again) or from the server.
16
+ */
17
+ export async function onboardingEnvironment(settings, runtime) {
18
+ const repo = openRepoSource(settings, runtime, { refresh: "none" });
8
19
  if (repo) {
9
20
  const model = await repo.model();
10
21
  return {
@@ -19,16 +30,19 @@ export async function onboardingEnvironment(settings, home) {
19
30
  previous: selectionState(settings),
20
31
  };
21
32
  }
22
- if (!settings.connection)
33
+ if (!settings.connection) {
23
34
  throw new Error("A connected identity is required");
24
- const { connection, catalog } = await environmentCatalog(home, settings.connection);
25
- const scopes = await request(connection, "/v1/scopes", z.array(scopeSchema), home);
26
- const teams = scopes.filter((scope) => scope.type === "team");
35
+ }
36
+ const { connection, catalog } = await environmentCatalog(runtime, settings.connection);
37
+ const visible = await scopes(connection, runtime);
38
+ const teams = visible.filter((scope) => scope.type === "team");
27
39
  const memberTeamIds = [];
28
40
  // Bound concurrent requests when using servers with the existing membership API.
29
- for (let offset = 0; offset < teams.length; offset += 6) {
30
- const memberships = await Promise.all(teams.slice(offset, offset + 6).map(async (team) => {
31
- const members = await request(connection, `/v1/teams/${team.id}/members`, z.array(teamMemberSchema), home);
41
+ for (let offset = 0; offset < teams.length; offset += TEAM_FETCH_CONCURRENCY) {
42
+ const memberships = await Promise.all(teams.slice(offset, offset + TEAM_FETCH_CONCURRENCY).map(async (team) => {
43
+ const members = await parsed(z.array(teamMemberSchema), apiClient(connection.server, runtime).GET("/v1/teams/{id}/members", {
44
+ params: { path: { id: team.id } },
45
+ }));
32
46
  return members.some((member) => member.id === connection.developerId)
33
47
  ? team.id
34
48
  : undefined;
@@ -37,11 +51,10 @@ export async function onboardingEnvironment(settings, home) {
37
51
  }
38
52
  return {
39
53
  catalog,
40
- scopes,
54
+ scopes: visible,
41
55
  memberTeamIds,
42
56
  developerId: connection.developerId,
43
- firstSetup: settings.environment === undefined &&
44
- !settings.skills.some((s) => s.kind === "api"),
57
+ firstSetup: settings.environment === undefined,
45
58
  previous: selectionState(settings),
46
59
  };
47
60
  }
@@ -49,6 +62,25 @@ export async function onboardingEnvironment(settings, home) {
49
62
  * Setup offers the organization, membership teams, scopes already subscribed to,
50
63
  * and the developer's own assets. Whatever is left unchecked is removed.
51
64
  */
65
+ /**
66
+ * The mode setup offers first for a source: a saved subscription's mode, then
67
+ * custom when individual picks or an optional subscription exist, then all of
68
+ * your own assets or the recommended ones of a shared scope.
69
+ */
70
+ function initialMode(savedMode, pickedIndividually, scopeType) {
71
+ if (savedMode === "all" || savedMode === "recommended") {
72
+ return savedMode;
73
+ }
74
+ if (pickedIndividually || savedMode === "optional") {
75
+ return "custom";
76
+ }
77
+ return scopeType === "dev" ? "all" : "recommended";
78
+ }
79
+ /**
80
+ * Builds setup choices from visible scopes, catalog and previous selections.
81
+ * Saved all/recommended modes are retained; optional subscriptions are
82
+ * presented as custom picks.
83
+ */
52
84
  export function onboardingSources(choices) {
53
85
  const { catalog, previous, developerId, memberTeamIds, firstSetup } = choices;
54
86
  const subscribed = (scope) => previous.subscriptions.some((s) => s.scope.type === scope.type && s.scope.id === scope.id);
@@ -108,13 +140,7 @@ export function onboardingSources(choices) {
108
140
  (firstSetup &&
109
141
  (scope.type === "org" ||
110
142
  (scope.type === "team" && memberTeamIds.length === 1)))),
111
- mode: saved?.mode === "all" || saved?.mode === "recommended"
112
- ? saved.mode
113
- : independent.length || saved?.mode === "optional"
114
- ? "custom"
115
- : scope.type === "dev"
116
- ? "all"
117
- : "recommended",
143
+ mode: initialMode(saved?.mode, independent.length > 0, scope.type),
118
144
  };
119
145
  });
120
146
  }
@@ -131,13 +157,14 @@ export function selectOnboardingSources(selections) {
131
157
  });
132
158
  }
133
159
  else {
134
- const ids = mode === "custom"
135
- ? (assetIds ?? [])
136
- : mode === "recommended"
137
- ? source.recommendedIds
138
- : source.assets.map((a) => a.id);
139
- if (ids.some((id) => !source.assets.some((a) => a.id === id)))
140
- throw new Error("Selection contains an asset outside this source");
160
+ const ids = {
161
+ custom: assetIds ?? [],
162
+ recommended: source.recommendedIds,
163
+ all: source.assets.map((a) => a.id),
164
+ }[mode];
165
+ if (ids.some((id) => !source.assets.some((a) => a.id === id))) {
166
+ throw new CliError("The selection includes an asset that isn't in this workspace.");
167
+ }
141
168
  ids.forEach((id) => individualAssetIds.add(id));
142
169
  }
143
170
  }
@@ -148,13 +175,19 @@ export function selectOnboardingSources(selections) {
148
175
  disabledAssetIds: [],
149
176
  };
150
177
  }
178
+ /**
179
+ * The settings with their selection replaced by `selection`, after checking it
180
+ * names only scopes and assets setup offered. Writes nothing.
181
+ */
151
182
  export function selectedEnvironment(settings, choices, selection) {
152
183
  const parsed = selectionStateSchema.parse(selection);
153
184
  if (parsed.subscriptions.some((s) => !choices.scopes.some((scope) => scope.type === s.scope.type && scope.id === s.scope.id)) ||
154
- parsed.individualAssetIds.some((id) => !choices.catalog.assets.some((asset) => asset.id === id)))
155
- throw new Error("Selection contains an unavailable scope or asset");
185
+ parsed.individualAssetIds.some((id) => !choices.catalog.assets.some((asset) => asset.id === id))) {
186
+ throw new CliError("The selection includes a set or asset that isn't available.");
187
+ }
156
188
  if (new Set(parsed.subscriptions.map((s) => `${s.scope.type}:${s.scope.id}`))
157
- .size !== parsed.subscriptions.length)
158
- throw new Error("Duplicate scope selection");
189
+ .size !== parsed.subscriptions.length) {
190
+ throw new CliError("The selection lists the same set twice.");
191
+ }
159
192
  return withSelection(settings, parsed);
160
193
  }
@@ -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,77 @@
1
+ import { chmod, lstat, mkdir, readFile } from "node:fs/promises";
2
+ import { z } from "zod";
3
+ import { barndogPaths } from "../../config/paths.js";
4
+ import { CliError } from "../../errors.js";
5
+ import { privatePermissions, protectPrivate, removeCommand, } from "../../platform.js";
6
+ import { POSIX_MODE } from "../../shared/constants.js";
7
+ import { ifExists, writeAtomic } from "../../shared/files.js";
8
+ import { withPidLock } from "../../shared/lock.js";
9
+ import { VARIABLE_NAME } from "../../shared/patterns.js";
10
+ import { posixQuote } from "../../shared/shell.js";
11
+ const variable = z.string().regex(new RegExp(`^${VARIABLE_NAME.source}$`));
12
+ const secretsSchema = z.strictObject({
13
+ version: z.literal(1),
14
+ values: z.record(variable, z.string()),
15
+ });
16
+ /** The kept values; empty when there's no file yet. */
17
+ export async function readSecrets(runtime) {
18
+ const path = barndogPaths(runtime.home).secrets;
19
+ const info = await ifExists(lstat(path));
20
+ if (!info) {
21
+ return {};
22
+ }
23
+ if (!info.isFile()) {
24
+ throw new CliError(`${path} isn't a regular file, so BarnDog can't read the MCP values it keeps.`, "Delete it, then set the values again with barndog mcp env set.", { command: removeCommand(path, runtime.platform) });
25
+ }
26
+ // Always passes on Windows, where the ACL set on every write keeps it private.
27
+ if (!privatePermissions(info.mode, runtime.platform)) {
28
+ throw new CliError(`${path} can be read by other users on this machine.`, "Make it readable and writable only by you.", { command: `chmod 600 ${posixQuote(path)}` });
29
+ }
30
+ const parsed = secretsSchema.safeParse(parseJson(await readFile(path, "utf8")));
31
+ if (!parsed.success) {
32
+ throw new CliError(`${path} is damaged, so BarnDog can't read the MCP values it keeps.`, "Delete it, then set the values again with barndog mcp env set.", { command: removeCommand(path, runtime.platform) });
33
+ }
34
+ return parsed.data.values;
35
+ }
36
+ function parseJson(text) {
37
+ try {
38
+ return JSON.parse(text);
39
+ }
40
+ catch {
41
+ return undefined;
42
+ }
43
+ }
44
+ /** Saves `changes` (a value, or null to forget it) under a lock; returns the file's path. */
45
+ export async function updateSecrets(changes, runtime) {
46
+ const paths = barndogPaths(runtime.home);
47
+ for (const name of Object.keys(changes)) {
48
+ if (!variable.safeParse(name).success) {
49
+ throw new CliError(`${name} isn't an environment variable name.`, "Use letters, digits and underscores, not starting with a digit.");
50
+ }
51
+ }
52
+ await mkdir(paths.root, {
53
+ recursive: true,
54
+ mode: POSIX_MODE.privateDirectory,
55
+ });
56
+ await chmod(paths.root, POSIX_MODE.privateDirectory);
57
+ await protectPrivate(paths.root, runtime);
58
+ await withPidLock(paths.secretsLock, {
59
+ starting: "Another change to the kept MCP values is starting. Wait for it to finish, then try again.",
60
+ running: "Another change to the kept MCP values is running. Wait for it to finish, then try again.",
61
+ }, async () => {
62
+ const values = {
63
+ ...(await readSecrets(runtime)),
64
+ };
65
+ for (const [name, value] of Object.entries(changes)) {
66
+ if (value === null) {
67
+ delete values[name];
68
+ }
69
+ else {
70
+ values[name] = value;
71
+ }
72
+ }
73
+ await writeAtomic(paths.secrets, JSON.stringify({ version: 1, values }, null, 2) + "\n");
74
+ await protectPrivate(paths.secrets, runtime);
75
+ });
76
+ return paths.secrets;
77
+ }
@@ -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
+ }