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
package/dist/errors.js CHANGED
@@ -1,14 +1,9 @@
1
1
  import { ApiError } from "@barndog-ai/api-contract";
2
2
  import { z } from "zod";
3
- /** A user-facing failure with an optional command that fixes it. */
4
- export class CliError extends Error {
5
- hint;
6
- constructor(message, hint, options) {
7
- super(message, options);
8
- this.name = "CliError";
9
- this.hint = hint;
10
- }
11
- }
3
+ import { CliError } from "./shared/cli-error.js";
4
+ import { CONSTANT_CASE } from "./shared/patterns.js";
5
+ import { errorCode } from "./shared/values.js";
6
+ export { CliError };
12
7
  /** Ends a command early when there is nothing to choose; not a failure. */
13
8
  export class NothingToDoError extends CliError {
14
9
  constructor(message) {
@@ -16,26 +11,156 @@ export class NothingToDoError extends CliError {
16
11
  this.name = "NothingToDoError";
17
12
  }
18
13
  }
19
- const packageMessages = {
20
- INVALID_SKILL_MD: "SKILL.md needs front matter with a lowercase hyphenated name and a description",
21
- MISSING_SKILL_MD: "This folder has no SKILL.md",
22
- GITHUB_APP_NOT_CONFIGURED: "GitHub isn't set up on this BarnDog server",
23
- GITHUB_USER_AUTHORIZATION_REQUIRED: "Link your GitHub account first with barndog github auth",
24
- IDEMPOTENCY_KEY_REUSED: "That retry key was already used for different content. Use a new --key",
25
- ORGANIZATION_ADMIN_REQUIRED: "Only organization admins can do that",
26
- UNSAFE_PACKAGE_ENTRY: "It contains a link or an unsafe file path",
27
- CONFLICTING_PACKAGE_PATHS: "A file and a folder share the same path",
28
- PACKAGE_TOO_LARGE: "It's too large to package",
29
- EMPTY_HOOK_EVENTS: "hook.yaml lists no events for one of its coding tools",
30
- CURSOR_COMMAND_HANDLER_REQUIRED: "Cursor events in hook.yaml list commands directly, without a nested hooks list",
31
- NATIVE_MATCHER_GROUP_REQUIRED: "Claude Code and Codex events in hook.yaml need a nested hooks list",
32
- HOOK_COMMAND_MUST_REFERENCE_DECLARED_SCRIPT: "Each command in hook.yaml must run a declared script through ${BARNDOG_HOOK_ROOT}/",
33
- };
14
+ /**
15
+ * Why a folder or archive can't be a package. The CLI throws these as
16
+ * `PackageError`; `@barndog-ai/api-contract`'s package helpers throw the same
17
+ * codes as plain `Error` messages, and the server returns them as `ApiError`s,
18
+ * so `packageError()` translates both at that boundary.
19
+ *
20
+ * @internal Exported for the completeness test in `src/tests/errors.test.ts`.
21
+ */
22
+ export const packageProblemCodes = [
23
+ "CONFLICTING_PACKAGE_PATHS",
24
+ "CURSOR_COMMAND_HANDLER_REQUIRED",
25
+ "EMPTY_HOOK_EVENTS",
26
+ "HOOK_COMMAND_MUST_REFERENCE_DECLARED_SCRIPT",
27
+ "INVALID_SKILL_MD",
28
+ "MISSING_HOOK_SCRIPT",
29
+ "MISSING_PACKAGE_MANIFEST",
30
+ "MISSING_SKILL_MD",
31
+ "MODIFIED_CACHED_PACKAGE",
32
+ "NATIVE_MATCHER_GROUP_REQUIRED",
33
+ "PACKAGE_TOO_LARGE",
34
+ "UNSAFE_PACKAGE_ENTRY",
35
+ ];
36
+ function isPackageProblemCode(value) {
37
+ return packageProblemCodes.some((code) => code === value);
38
+ }
39
+ /**
40
+ * A package the CLI can't read, write or submit. `detail` names the file
41
+ * involved, such as the missing manifest or the unsafe path.
42
+ */
43
+ export class PackageError extends Error {
44
+ code;
45
+ detail;
46
+ constructor(code, detail, options) {
47
+ super(detail ? `${code}: ${detail}` : code, options);
48
+ this.name = "PackageError";
49
+ this.code = code;
50
+ this.detail = detail;
51
+ }
52
+ }
53
+ /**
54
+ * `error` as a `PackageError`: itself, or a package code from the contract's
55
+ * helpers (`Error("MISSING_HOOK_SCRIPT: run.sh")`) or the server. Those two
56
+ * report codes only as message text; this is the one place that reads it.
57
+ */
58
+ function packageError(error) {
59
+ if (error instanceof PackageError) {
60
+ return error;
61
+ }
62
+ if (!(error instanceof Error) || error instanceof CliError) {
63
+ return undefined;
64
+ }
65
+ const separator = error.message.indexOf(": ");
66
+ const code = separator < 0 ? error.message : error.message.slice(0, separator);
67
+ if (!isPackageProblemCode(code)) {
68
+ return undefined;
69
+ }
70
+ const detail = separator < 0 ? undefined : error.message.slice(separator + 2);
71
+ return new PackageError(code, detail, { cause: error });
72
+ }
73
+ /** `text`, followed by the file it's about when there is one. */
74
+ const about = (text, detail) => detail ? `${text}: ${detail}` : text;
75
+ /** What a package problem means to the person whose folder it is. */
76
+ function packageProblem({ code, detail }) {
77
+ switch (code) {
78
+ case "CONFLICTING_PACKAGE_PATHS":
79
+ return "A file and a folder share the same path";
80
+ case "CURSOR_COMMAND_HANDLER_REQUIRED":
81
+ return "Cursor events in hook.yaml list commands directly, without a nested hooks list";
82
+ case "EMPTY_HOOK_EVENTS":
83
+ return "hook.yaml lists no events for one of its coding tools";
84
+ case "HOOK_COMMAND_MUST_REFERENCE_DECLARED_SCRIPT":
85
+ return "Each command in hook.yaml must run a declared script through ${BARNDOG_HOOK_ROOT}/";
86
+ case "INVALID_SKILL_MD":
87
+ return "SKILL.md needs front matter with a lowercase hyphenated name and a description";
88
+ case "MISSING_HOOK_SCRIPT":
89
+ return about("hook.yaml declares a script that isn't in the folder", detail);
90
+ case "MISSING_PACKAGE_MANIFEST":
91
+ return `This folder has no ${detail || "manifest file"}`;
92
+ case "MISSING_SKILL_MD":
93
+ return "This folder has no SKILL.md";
94
+ case "MODIFIED_CACHED_PACKAGE":
95
+ return "A downloaded copy was changed on this machine, so BarnDog won't reuse it";
96
+ case "NATIVE_MATCHER_GROUP_REQUIRED":
97
+ return "Claude Code and Codex events in hook.yaml need a nested hooks list";
98
+ case "PACKAGE_TOO_LARGE":
99
+ return "It's too large to package";
100
+ case "UNSAFE_PACKAGE_ENTRY":
101
+ return about("It contains a link or an unsafe file path", detail);
102
+ }
103
+ }
104
+ /**
105
+ * Server refusal codes the CLI explains; others read as a sentence (see
106
+ * `friendlyMessage`).
107
+ *
108
+ * @internal Exported for the completeness test in `src/tests/errors.test.ts`.
109
+ */
110
+ export const serverProblemCodes = [
111
+ "APPROVALS_REQUIRED",
112
+ "CHANGE_AUTHOR_REQUIRED",
113
+ "CHANGE_CLOSED",
114
+ "CHANGE_CLOSE_FORBIDDEN",
115
+ "CHANGES_REQUESTED",
116
+ "GITHUB_APP_NOT_CONFIGURED",
117
+ "GITHUB_USER_AUTHORIZATION_REQUIRED",
118
+ "IDEMPOTENCY_KEY_REUSED",
119
+ "MCP_NOT_FOUND",
120
+ "MERGE_ADMIN_REQUIRED",
121
+ "MERGE_MEMBERSHIP_REQUIRED",
122
+ "NO_CHANGES",
123
+ "ORGANIZATION_ADMIN_REQUIRED",
124
+ "OUTDATED_SUGGESTION",
125
+ "PERSONAL_OWNER_REQUIRED",
126
+ "PUBLICATION_FORBIDDEN",
127
+ "REVIEW_MEMBERSHIP_REQUIRED",
128
+ "SCOPE_ADMIN_REQUIRED",
129
+ "SCOPE_MEMBERSHIP_REQUIRED",
130
+ "SCOPE_NOT_FOUND",
131
+ "SELF_REVIEW_FORBIDDEN",
132
+ "SKILL_NOT_FOUND",
133
+ "STALE_CHANGE_REVISION",
134
+ "STALE_SKILL_VERSION",
135
+ "SUGGESTION_CONTENT_MISMATCH",
136
+ "THREAD_ACTION_FORBIDDEN",
137
+ ];
138
+ /**
139
+ * The server's specific refusal code, such as `STALE_SKILL_VERSION`. The API
140
+ * sends it in the body's `message` field (its `code` field holds only the HTTP
141
+ * category, such as `CONFLICT`), so `ApiError.message` carries it.
142
+ */
143
+ function serverCode(error) {
144
+ return error.message;
145
+ }
146
+ function serverProblemCode(error) {
147
+ if (!(error instanceof ApiError)) {
148
+ return undefined;
149
+ }
150
+ const code = serverCode(error);
151
+ return serverProblemCodes.find((known) => known === code);
152
+ }
153
+ /**
154
+ * Where to look again after a refusal about a Suggested Change. The server
155
+ * doesn't say which kind the change is, so this names both; a command that
156
+ * knows the kind replaces it with its own (`commands/collaboration.ts`).
157
+ */
158
+ export const CHANGES_LIST_FIX = "barndog skills changes list or barndog hooks changes list";
34
159
  /** Server refusals people run into, with what to do next when there is something to do. */
35
160
  const serverProblems = {
36
161
  APPROVALS_REQUIRED: {
37
162
  message: "This change needs more approvals before it can merge",
38
- fix: "barndog changes list",
163
+ fix: CHANGES_LIST_FIX,
39
164
  },
40
165
  CHANGE_AUTHOR_REQUIRED: {
41
166
  message: "Only the author of this change can revise it",
@@ -50,7 +175,17 @@ const serverProblems = {
50
175
  },
51
176
  CHANGES_REQUESTED: {
52
177
  message: "A reviewer requested changes, so this can't merge yet",
53
- fix: "barndog changes list",
178
+ fix: CHANGES_LIST_FIX,
179
+ },
180
+ GITHUB_APP_NOT_CONFIGURED: {
181
+ message: "GitHub isn't set up on this BarnDog server",
182
+ },
183
+ GITHUB_USER_AUTHORIZATION_REQUIRED: {
184
+ message: "Link your GitHub account first",
185
+ fix: "barndog github auth",
186
+ },
187
+ IDEMPOTENCY_KEY_REUSED: {
188
+ message: "That retry key was already used for different content. Use a new --key",
54
189
  },
55
190
  MCP_NOT_FOUND: {
56
191
  message: "No MCP server matches that name and origin",
@@ -64,9 +199,12 @@ const serverProblems = {
64
199
  message: "Nothing differs from the published version",
65
200
  fix: "barndog status",
66
201
  },
202
+ ORGANIZATION_ADMIN_REQUIRED: {
203
+ message: "Only organization admins can do that",
204
+ },
67
205
  OUTDATED_SUGGESTION: {
68
206
  message: "That suggestion no longer applies to the current revision",
69
- fix: "barndog changes list",
207
+ fix: CHANGES_LIST_FIX,
70
208
  },
71
209
  PERSONAL_OWNER_REQUIRED: { message: "Only its owner can do that" },
72
210
  PUBLICATION_FORBIDDEN: {
@@ -91,7 +229,7 @@ const serverProblems = {
91
229
  },
92
230
  STALE_CHANGE_REVISION: {
93
231
  message: "This change has a newer revision. Review it, then retry",
94
- fix: "barndog changes list",
232
+ fix: CHANGES_LIST_FIX,
95
233
  },
96
234
  STALE_SKILL_VERSION: {
97
235
  message: "A newer version was published after this change was made",
@@ -99,7 +237,7 @@ const serverProblems = {
99
237
  },
100
238
  SUGGESTION_CONTENT_MISMATCH: {
101
239
  message: "--expected-file doesn't match those lines in this revision. Suggestions also need --side new",
102
- fix: "barndog changes list",
240
+ fix: CHANGES_LIST_FIX,
103
241
  },
104
242
  THREAD_ACTION_FORBIDDEN: {
105
243
  message: "Only the discussion's author or an admin can do that",
@@ -107,17 +245,18 @@ const serverProblems = {
107
245
  };
108
246
  /** The next command for a server refusal or a CliError, when one is known. */
109
247
  export function friendlyHint(error) {
110
- if (error instanceof CliError)
248
+ if (error instanceof CliError) {
111
249
  return error.hint;
112
- if (error instanceof ApiError)
113
- return serverProblems[error.message]?.fix;
114
- return undefined;
250
+ }
251
+ const code = serverProblemCode(error);
252
+ return code ? serverProblems[code].fix : undefined;
115
253
  }
116
254
  /** Turns internal codes and validation errors into something a person can act on. */
117
255
  export function friendlyMessage(error) {
118
- if (!(error instanceof Error))
256
+ if (!(error instanceof Error)) {
119
257
  return String(error);
120
- if (error instanceof z.ZodError)
258
+ }
259
+ if (error instanceof z.ZodError) {
121
260
  return error.issues
122
261
  .map((issue) => {
123
262
  const text = issue.code === "invalid_format" && issue.format === "uuid"
@@ -126,29 +265,33 @@ export function friendlyMessage(error) {
126
265
  return issue.path.length ? `${issue.path.join(".")}: ${text}` : text;
127
266
  })
128
267
  .join("; ");
129
- if (error instanceof ApiError && serverProblems[error.message])
130
- return `${serverProblems[error.message].message}.`;
131
- const code = error.code;
132
- const path = error.path;
133
- if (code === "ENOENT" && path)
268
+ }
269
+ const packaged = packageError(error);
270
+ if (packaged) {
271
+ return packageProblem(packaged);
272
+ }
273
+ const server = serverProblemCode(error);
274
+ if (server) {
275
+ return `${serverProblems[server].message}.`;
276
+ }
277
+ // Other server codes, such as KNOWLEDGE_NOT_FOUND, still read as a sentence.
278
+ if (error instanceof ApiError && CONSTANT_CASE.test(serverCode(error))) {
279
+ const code = serverCode(error);
280
+ return `${code[0]}${code.slice(1).toLowerCase().replaceAll("_", " ")}.`;
281
+ }
282
+ const code = errorCode(error);
283
+ const path = "path" in error && typeof error.path === "string" ? error.path : undefined;
284
+ if (code === "ENOENT" && path) {
134
285
  return `Can't find ${path}.`;
135
- if (code === "EACCES" && path)
286
+ }
287
+ if (code === "EACCES" && path) {
136
288
  return `No permission to read ${path}.`;
137
- if (code === "EISDIR" && path)
289
+ }
290
+ if (code === "EISDIR" && path) {
138
291
  return `${path} is a folder, not a file.`;
139
- if (code === "EEXIST" && path)
292
+ }
293
+ if (code === "EEXIST" && path) {
140
294
  return `${path} already exists. Choose another folder or remove it first.`;
141
- const [prefix, detail] = error.message.split(/: (.*)/s);
142
- if (prefix === "MISSING_HOOK_SCRIPT")
143
- return `hook.yaml declares a script that isn't in the folder: ${detail}`;
144
- if (prefix === "MISSING_PACKAGE_MANIFEST")
145
- return `This folder has no ${detail}`;
146
- if (prefix === "UNSAFE_PACKAGE_ENTRY" && detail)
147
- return detail;
148
- if (packageMessages[prefix])
149
- return packageMessages[prefix];
150
- // Server codes such as KNOWLEDGE_NOT_FOUND still read as a sentence.
151
- if (/^[A-Z][A-Z0-9_]+$/.test(error.message))
152
- return `${error.message[0]}${error.message.slice(1).toLowerCase().replace(/_/g, " ")}.`;
295
+ }
153
296
  return error.message;
154
297
  }
@@ -0,0 +1,234 @@
1
+ /**
2
+ * `barndog adopt`: copy assets the user set up in their coding tools into
3
+ * BarnDog's local folder, take the originals out of the tools, and sync so
4
+ * BarnDog's copies install in their place. `undo.ts` puts them back.
5
+ */
6
+ import { randomUUID } from "node:crypto";
7
+ import { copyFile, lstat, mkdir } from "node:fs/promises";
8
+ import { basename, dirname, join } from "node:path";
9
+ import { stringify } from "yaml";
10
+ import { barndogPaths } from "../../config/paths.js";
11
+ import { readSettings } from "../../config/settings.js";
12
+ import { readState } from "../../config/state.js";
13
+ import { CliError, friendlyMessage } from "../../errors.js";
14
+ import { POSIX_MODE } from "../../shared/constants.js";
15
+ import { ifExists, writeAtomic } from "../../shared/files.js";
16
+ import { defined } from "../../shared/lookup.js";
17
+ import { assetKinds } from "../asset-kinds/index.js";
18
+ import { synchronize } from "../environment/sync.js";
19
+ import { locked } from "../environment/transaction.js";
20
+ import { ensureLocalWorkspace } from "../imports/local.js";
21
+ import { literalNotes } from "../mcps/import.js";
22
+ import { readSecrets, updateSecrets } from "../secrets/index.js";
23
+ import { writePackage } from "../workspace/directory.js";
24
+ import { localRepoSource } from "../workspace/repo-source.js";
25
+ import { copyFingerprint, installed } from "./copies.js";
26
+ import { takeOut } from "./originals.js";
27
+ import { restore } from "./restore.js";
28
+ import { readAdoptions, writeAdoption, } from "./record.js";
29
+ import { findNativeAssets, } from "./scan.js";
30
+ /**
31
+ * What adopting `keys` takes over: each chosen asset, plus other tools'
32
+ * Skills and MCP servers of the same name, which BarnDog's one copy replaces.
33
+ */
34
+ export function adoptionPlan(scan, keys) {
35
+ const byKey = new Map(scan.assets.map((asset) => [asset.key, asset]));
36
+ const unknown = keys.filter((key) => !byKey.has(key));
37
+ if (unknown.length) {
38
+ throw new CliError(`${unknown.join(", ")} ${unknown.length === 1 ? "isn't an asset" : "aren't assets"} BarnDog can adopt.`, "barndog adopt --dry-run");
39
+ }
40
+ const planned = new Map();
41
+ for (const key of keys) {
42
+ const asset = byKey.get(key);
43
+ if (!asset || planned.has(key)) {
44
+ continue;
45
+ }
46
+ const group = [key, ...asset.sameName.map((other) => other.key)];
47
+ const chosen = group.filter((other) => keys.includes(other));
48
+ const differing = chosen.find((other) => other !== key && !byKey.get(other)?.identical);
49
+ if (differing) {
50
+ throw new CliError(`${key} and ${differing} are different ${assetKinds[asset.kind].many} with the same name, and BarnDog installs one copy in every tool.`, `barndog adopt --only ${key}`);
51
+ }
52
+ for (const member of group) {
53
+ const found = byKey.get(member);
54
+ if (found) {
55
+ planned.set(member, {
56
+ ...found,
57
+ source: { key, harness: asset.harness },
58
+ });
59
+ }
60
+ }
61
+ }
62
+ return [...planned.values()];
63
+ }
64
+ async function hasSharedWorkspace(home) {
65
+ const settings = await readSettings(home);
66
+ return Boolean(settings?.connection ?? settings?.gitWorkspace);
67
+ }
68
+ /** Same-named copies share one source, so each source's notes appear once. */
69
+ function adoptionNotes(plan, sourceOf, keep) {
70
+ const sources = new Map(plan.map((asset) => [asset.source.key, asset]));
71
+ return [...sources.values()].flatMap((asset) => {
72
+ const source = sourceOf(asset);
73
+ return [...source.notes, ...literalNotes(source.literals, keep)].map((text) => ({ kind: asset.kind, name: asset.name, text }));
74
+ });
75
+ }
76
+ /**
77
+ * Keeps the chosen values before the sync that writes them into the tools,
78
+ * and returns how to put the file back as it was if adopting fails.
79
+ */
80
+ async function keepValues(literals, keep, runtime) {
81
+ const chosen = literals.filter((l) => keep.includes(l.variable));
82
+ if (!chosen.length) {
83
+ return async () => { };
84
+ }
85
+ const before = await readSecrets(runtime);
86
+ await updateSecrets(Object.fromEntries(chosen.map((l) => [l.variable, l.value])), runtime);
87
+ return async () => {
88
+ await updateSecrets(Object.fromEntries(chosen.map((l) => [l.variable, before[l.variable] ?? null])), runtime);
89
+ };
90
+ }
91
+ /** Takes over the chosen assets; on any failure, puts back what it changed. */
92
+ export async function adoptNative(keys,
93
+ /** Variables whose values BarnDog keeps on this machine (see `mcp env`). */
94
+ keep, runtime) {
95
+ const { home } = runtime;
96
+ return locked(runtime, async () => {
97
+ const unfinished = (await readAdoptions(home)).find((record) => record.status === "pending");
98
+ if (unfinished) {
99
+ throw new CliError("An earlier adoption didn't finish. Undo it before adopting more.", `barndog adopt undo ${unfinished.id}`);
100
+ }
101
+ const { found, skipped } = await findNativeAssets(runtime);
102
+ const plan = adoptionPlan({ assets: found, skipped }, keys);
103
+ if (!plan.length) {
104
+ throw new CliError("Choose at least one asset to adopt.", "barndog adopt");
105
+ }
106
+ const workspace = await ensureLocalWorkspace(runtime);
107
+ const id = randomUUID();
108
+ const paths = barndogPaths(home).adoption(id);
109
+ const byKey = new Map(found.map((asset) => [asset.key, asset]));
110
+ const scanned = (key) => defined(byKey.get(key), `The scan found no ${key}`);
111
+ const sourceOf = (asset) => scanned(asset.source.key);
112
+ const record = {
113
+ id,
114
+ createdAt: new Date().toISOString(),
115
+ status: "pending",
116
+ files: [],
117
+ items: plan.map((asset) => {
118
+ const { copy, original } = scanned(asset.key);
119
+ return {
120
+ key: asset.key,
121
+ harness: asset.harness,
122
+ kind: asset.kind,
123
+ name: asset.name,
124
+ description: asset.description,
125
+ copy: join(workspace.path, copy),
126
+ assetId: "",
127
+ fingerprint: "",
128
+ original,
129
+ backup: original.type === "folder"
130
+ ? join(paths.skills, asset.harness, asset.name)
131
+ : undefined,
132
+ undone: false,
133
+ };
134
+ }),
135
+ };
136
+ // Undo removes every copy, so none may be there already.
137
+ for (const item of record.items) {
138
+ if ((await ifExists(lstat(item.copy))) !== null) {
139
+ throw new CliError(`${item.copy} already exists, so ${item.name} can't be adopted.`, "barndog adopt --dry-run");
140
+ }
141
+ }
142
+ // Written before anything changes, so undo can always find what moved.
143
+ await writeAdoption(record, home);
144
+ const sources = [
145
+ ...new Map(plan.map((asset) => [asset.source.key, asset])).values(),
146
+ ].map(sourceOf);
147
+ let forgetValues = async () => { };
148
+ try {
149
+ forgetValues = await keepValues(sources.flatMap((source) => source.literals), keep, runtime);
150
+ const events = await apply({ record, plan, sourceOf, workspace }, runtime);
151
+ return {
152
+ id,
153
+ adopted: plan,
154
+ backup: paths.folder,
155
+ notes: adoptionNotes(plan, sourceOf, keep),
156
+ events,
157
+ canShare: await hasSharedWorkspace(home),
158
+ };
159
+ }
160
+ catch (error) {
161
+ await restore(record, record.items, runtime).catch((undoError) => {
162
+ throw new CliError(`Adopting failed (${friendlyMessage(error)}), and putting things back failed too: ${friendlyMessage(undoError)}`, `barndog adopt undo ${id}`, { cause: error });
163
+ });
164
+ await forgetValues();
165
+ throw error;
166
+ }
167
+ });
168
+ }
169
+ async function apply(input, runtime) {
170
+ const { home } = runtime;
171
+ const { record, plan, sourceOf, workspace } = input;
172
+ // One copy per name: tools that had the same asset share it.
173
+ const written = new Map();
174
+ for (const [index, asset] of plan.entries()) {
175
+ const item = defined(record.items[index], "Each planned asset has an item");
176
+ if (!written.has(item.copy)) {
177
+ await writeCopy(item.copy, sourceOf(asset), runtime);
178
+ written.set(item.copy, defined(await copyFingerprint(item, runtime), "The copy was written"));
179
+ }
180
+ item.fingerprint = defined(written.get(item.copy), "The copy was written");
181
+ }
182
+ const model = await localRepoSource(workspace, runtime).model();
183
+ for (const item of record.items) {
184
+ const asset = model.assets.find((candidate) => join(workspace.path, candidate.path) === item.copy);
185
+ if (!asset || asset.invalid) {
186
+ throw new CliError(`BarnDog couldn't read its copy of ${item.name}: ${asset?.invalid ?? "it's missing"}.`);
187
+ }
188
+ item.assetId = asset.id;
189
+ }
190
+ // A settings file is saved as the user left it, before BarnDog's first change.
191
+ for (const item of record.items) {
192
+ const { original } = item;
193
+ if (original.type === "entry" &&
194
+ !record.files.some((saved) => saved.file === original.file)) {
195
+ const backup = join(barndogPaths(home).adoption(record.id).settings, `${record.files.length + 1}-${basename(original.file)}`);
196
+ await mkdir(dirname(backup), { recursive: true });
197
+ await copyFile(original.file, backup);
198
+ record.files.push({ file: original.file, backup });
199
+ }
200
+ }
201
+ await writeAdoption(record, home);
202
+ for (const item of record.items) {
203
+ await takeOut(item.harness, item.original, item.backup);
204
+ }
205
+ const events = await synchronize(undefined, runtime, undefined, {
206
+ prompt: false,
207
+ });
208
+ const state = await readState(home);
209
+ const missing = record.items.filter((item) => !installed(item, state));
210
+ if (missing.length) {
211
+ const clashes = events.flatMap((event) => event.type === "clash" &&
212
+ missing.some((item) => item.name === event.skipped.name)
213
+ ? [
214
+ `BarnDog already installs ${event.kind === "skill" ? "a Skill" : "an MCP server"} named ${event.installed.name} from ${event.installed.origin}.`,
215
+ ]
216
+ : []);
217
+ throw new CliError(`BarnDog couldn't install ${missing.map((item) => item.key).join(", ")}, so nothing was adopted. ${clashes.join(" ")}`.trim(), "Rename yours in its coding tool, then run barndog adopt again");
218
+ }
219
+ record.status = "applied";
220
+ await writeAdoption(record, home);
221
+ return events;
222
+ }
223
+ async function writeCopy(path, asset, runtime) {
224
+ const { content } = asset;
225
+ // The workspace's own folders keep default permissions; writeAtomic would make them private.
226
+ await mkdir(dirname(path), { recursive: true });
227
+ if (content.kind === "mcp") {
228
+ await writeAtomic(path, stringify(content.definition), {
229
+ mode: POSIX_MODE.regularFile,
230
+ });
231
+ return;
232
+ }
233
+ await writePackage(path, content.entries, runtime);
234
+ }
@@ -0,0 +1,29 @@
1
+ /** BarnDog's copy of an adopted asset: what it holds, and whether sync installed it. */
2
+ import { lstat, readFile } from "node:fs/promises";
3
+ import { basename } from "node:path";
4
+ import { packageFingerprint } from "@barndog-ai/api-contract/package";
5
+ import { ifExists } from "../../shared/files.js";
6
+ import { readDirectory } from "../workspace/directory.js";
7
+ /** What BarnDog's copy holds now, to tell later whether someone edited it. */
8
+ export async function copyFingerprint(item, runtime) {
9
+ if (item.kind === "mcp") {
10
+ const data = await ifExists(readFile(item.copy));
11
+ return data === null
12
+ ? null
13
+ : packageFingerprint([
14
+ { path: basename(item.copy), data, executable: false },
15
+ ]);
16
+ }
17
+ return (await ifExists(lstat(item.copy))) === null
18
+ ? null
19
+ : packageFingerprint(await readDirectory(item.copy, runtime));
20
+ }
21
+ /** Whether the last sync installed an adopted asset in the tool it came from. */
22
+ export function installed(item, state) {
23
+ if (item.kind === "skill") {
24
+ return state.links.some((link) => link.id === item.assetId && link.harness === item.harness);
25
+ }
26
+ return state.native.some((entry) => entry.id === item.assetId &&
27
+ entry.harness === item.harness &&
28
+ entry.kind === item.kind);
29
+ }