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
@@ -0,0 +1,32 @@
1
+ import { homedir } from "node:os";
2
+ import { adapters, isHarness } from "../harnesses/registry.js";
3
+ import { knowledgeList, knowledgeIndexText, } from "../features/knowledge/index.js";
4
+ /** Keep knowledge delivery from blocking harness startup beyond five seconds. */
5
+ const STARTUP_KNOWLEDGE_TIMEOUT_MS = 5000;
6
+ // BarnDog-owned integration, independent from developer-authored Hook packages.
7
+ // Failure to retrieve an index must never block starting a coding session.
8
+ const timer = setTimeout(() => {
9
+ console.error("BarnDog knowledge index timed out; use barndog knowledge list.");
10
+ process.exit(0);
11
+ }, STARTUP_KNOWLEDGE_TIMEOUT_MS);
12
+ const runtime = {
13
+ home: process.argv[3] ?? homedir(),
14
+ cwd: process.cwd(),
15
+ env: { ...process.env },
16
+ platform: process.platform,
17
+ };
18
+ try {
19
+ const text = knowledgeIndexText(await knowledgeList(true, runtime));
20
+ const harness = process.argv[2];
21
+ if (text && isHarness(harness)) {
22
+ // A plugin (OpenCode's) adds the plain text itself; a hook prints the tool's JSON.
23
+ const { hooks } = adapters[harness];
24
+ console.log(hooks ? JSON.stringify(hooks.sessionContext(text)) : text);
25
+ }
26
+ }
27
+ catch {
28
+ console.error("BarnDog knowledge index is unavailable; use barndog knowledge list after reconnecting.");
29
+ }
30
+ finally {
31
+ clearTimeout(timer);
32
+ }
@@ -0,0 +1,71 @@
1
+ import { homedir } from "node:os";
2
+ import crossSpawn from "cross-spawn";
3
+ import { isWindows, stopProcessTree } from "../platform.js";
4
+ import { mcpDefinitionSchema } from "@barndog-ai/api-contract";
5
+ import { CliError } from "../errors.js";
6
+ /** Allow two seconds for the MCP child to exit before forcing shutdown. */
7
+ const MCP_SHUTDOWN_GRACE_MS = 2000;
8
+ // This process runs only when the native harness starts a selected stdio MCP.
9
+ // Definitions contain references, never credential values. No shell is involved.
10
+ try {
11
+ const definition = mcpDefinitionSchema.parse(JSON.parse(Buffer.from(process.argv[2] ?? "", "base64url").toString("utf8")));
12
+ if (definition.transport !== "stdio") {
13
+ throw new Error("A stdio configuration is required");
14
+ }
15
+ const runtime = {
16
+ home: homedir(),
17
+ cwd: process.cwd(),
18
+ env: { ...process.env },
19
+ platform: process.platform,
20
+ };
21
+ const env = { ...runtime.env };
22
+ for (const [name, reference] of Object.entries(definition.environment)) {
23
+ if (!runtime.env[reference.secretRef]) {
24
+ throw new CliError(`${reference.secretRef} isn't set in your environment. Set it, then restart your coding tool.`);
25
+ }
26
+ env[name] = runtime.env[reference.secretRef];
27
+ }
28
+ // cross-spawn finds the command on PATH and also starts Windows .cmd shims
29
+ // (such as npx) with safely quoted arguments.
30
+ const child = crossSpawn(definition.command, definition.args, {
31
+ env,
32
+ stdio: "inherit",
33
+ detached: !isWindows(runtime.platform),
34
+ cwd: runtime.cwd,
35
+ windowsHide: true,
36
+ });
37
+ for (const signal of ["SIGINT", "SIGTERM"]) {
38
+ process.on(signal, () => {
39
+ const { pid } = child;
40
+ if (!pid) {
41
+ return;
42
+ }
43
+ try {
44
+ stopProcessTree(child, runtime, signal);
45
+ const timer = setTimeout(() => {
46
+ try {
47
+ stopProcessTree(child, runtime);
48
+ }
49
+ catch {
50
+ /* exited */
51
+ }
52
+ }, MCP_SHUTDOWN_GRACE_MS);
53
+ timer.unref();
54
+ }
55
+ catch {
56
+ /* already exited */
57
+ }
58
+ });
59
+ }
60
+ child.once("error", () => {
61
+ console.error("Unable to start the configured MCP command");
62
+ process.exitCode = 1;
63
+ });
64
+ child.once("exit", (code) => {
65
+ process.exitCode = code ?? 1;
66
+ });
67
+ }
68
+ catch (error) {
69
+ console.error(error instanceof Error ? error.message : "Invalid MCP configuration.");
70
+ process.exitCode = 1;
71
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * BarnDog's OpenCode plugin. OpenCode has no command hooks, so the module sync
3
+ * writes to `~/.config/opencode/plugins/barndog.js` imports `barndog` from
4
+ * here and hands it the command lines a session-start hook would run in other
5
+ * tools. OpenCode runs plugins in its own process, so this file only starts
6
+ * BarnDog's other entry scripts and never imports the CLI.
7
+ */
8
+ import { execFile } from "node:child_process";
9
+ /** OpenCode's event for a new session, the counterpart of other tools' SessionStart. */
10
+ const SESSION_CREATED = "session.created";
11
+ /** knowledge-startup gives up after five seconds; this covers starting Node too. */
12
+ const COMMAND_TIMEOUT_MS = 10_000;
13
+ /** The index lists names and descriptions only; anything longer is broken. */
14
+ const OUTPUT_LIMIT_BYTES = 1_048_576;
15
+ /** A command's trimmed stdout; empty when it fails, so a session never does. */
16
+ function output([program, ...args]) {
17
+ return new Promise((resolve) => {
18
+ if (!program) {
19
+ resolve("");
20
+ return;
21
+ }
22
+ execFile(program, args, {
23
+ timeout: COMMAND_TIMEOUT_MS,
24
+ maxBuffer: OUTPUT_LIMIT_BYTES,
25
+ windowsHide: true,
26
+ }, (error, stdout) => {
27
+ resolve(error ? "" : stdout.trim());
28
+ });
29
+ });
30
+ }
31
+ /**
32
+ * At each new session, starts the background workspace sync and reads the
33
+ * knowledge index afresh; every request of that session gets the index added
34
+ * to its system prompt.
35
+ */
36
+ export function barndog(options) {
37
+ // OpenCode awaits what a plugin returns, so a plain object will do.
38
+ return () => {
39
+ let index;
40
+ return {
41
+ event: async ({ event }) => {
42
+ if (event.type !== SESSION_CREATED) {
43
+ return;
44
+ }
45
+ index = undefined;
46
+ if (options.sync) {
47
+ await output(options.sync);
48
+ }
49
+ },
50
+ "experimental.chat.system.transform": async (_input, result) => {
51
+ if (!options.knowledge) {
52
+ return;
53
+ }
54
+ index ??= output(options.knowledge);
55
+ const text = await index;
56
+ if (text) {
57
+ result.system.push(text);
58
+ }
59
+ },
60
+ };
61
+ };
62
+ }
@@ -3,10 +3,15 @@ import { fileURLToPath } from "node:url";
3
3
  // Runs at session start. It must return at once and can never fail the session,
4
4
  // so the real sync happens in a detached process that outlives this one.
5
5
  try {
6
- const child = spawn(process.execPath, [fileURLToPath(new URL("../../cli.js", import.meta.url)), "sync", "--auto"], {
6
+ const child = spawn(process.execPath, [fileURLToPath(new URL("../cli.js", import.meta.url)), "sync", "--auto"], {
7
7
  detached: true,
8
+ windowsHide: true,
8
9
  stdio: "ignore",
9
- env: { ...process.env, HOME: process.argv[2] },
10
+ env: {
11
+ ...process.env,
12
+ HOME: process.argv[2],
13
+ USERPROFILE: process.argv[2],
14
+ },
10
15
  });
11
16
  child.on("error", () => { });
12
17
  child.unref();
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,120 @@
1
+ import { hookManifestSchema, hookSchema, mcpSchema, skillSchema, } from "@barndog-ai/api-contract";
2
+ import { packageMetadata, } from "@barndog-ai/api-contract/package";
3
+ import { parse } from "yaml";
4
+ import { assetFolders, packageKindList, } from "../../config/selection.js";
5
+ import { CliError, PackageError } from "../../errors.js";
6
+ import { only } from "../../shared/lookup.js";
7
+ /** In the order commands list them. */
8
+ export const assetKindList = [
9
+ "skill",
10
+ "mcp",
11
+ "hook",
12
+ ];
13
+ export const isAssetKind = (value) => assetKindList.some((kind) => kind === value);
14
+ const file = (path, text, executable = false) => ({
15
+ path,
16
+ data: Buffer.from(text),
17
+ executable,
18
+ });
19
+ const hookManifest = (name) => `name: ${name}
20
+ description: Describe this Hook
21
+ implementations:
22
+ claude:
23
+ compatibility: supported
24
+ scripts: [scripts/hook.sh]
25
+ requirements:
26
+ commands: [sh]
27
+ events:
28
+ SessionStart:
29
+ - hooks:
30
+ - type: command
31
+ command: '\${BARNDOG_HOOK_ROOT}/scripts/hook.sh'
32
+ `;
33
+ /**
34
+ * What differs between asset kinds. Code that needs a kind's word, route, folder
35
+ * or schema reads it here instead of comparing `kind`.
36
+ */
37
+ export const assetKinds = {
38
+ skill: {
39
+ one: "Skill",
40
+ a: "a Skill",
41
+ many: "Skills",
42
+ /** `barndog skills …` */
43
+ command: "skills",
44
+ /** `/v1/skills/…` */
45
+ route: "skills",
46
+ /** Inside a workspace scope and `~/.barndog/installed/`. */
47
+ folder: assetFolders.skill,
48
+ schema: skillSchema,
49
+ manifest: "SKILL.md",
50
+ scaffold: (name) => [
51
+ file("SKILL.md", `---\nname: ${name}\ndescription: Describe this Skill\n---\n\nAdd instructions here.\n`),
52
+ ],
53
+ },
54
+ mcp: {
55
+ one: "MCP server",
56
+ a: "an MCP server",
57
+ many: "MCP servers",
58
+ command: "mcp",
59
+ route: "mcps",
60
+ folder: assetFolders.mcp,
61
+ schema: mcpSchema,
62
+ },
63
+ hook: {
64
+ one: "Hook",
65
+ a: "a Hook",
66
+ many: "Hooks",
67
+ command: "hooks",
68
+ route: "hooks",
69
+ folder: assetFolders.hook,
70
+ schema: hookSchema,
71
+ manifest: "hook.yaml",
72
+ scaffold: (name) => [
73
+ file("hook.yaml", hookManifest(name)),
74
+ file("scripts/hook.sh", "#!/bin/sh\n# Read native input; implement the desired behavior here.\ncat >/dev/null\n", true),
75
+ ],
76
+ },
77
+ };
78
+ export const assetNotFound = (kind, name, origin) => new CliError(`No ${assetKinds[kind].one} named ${name} in ${origin}.`, `barndog ${assetKinds[kind].command} search ${name}`);
79
+ /**
80
+ * Which kind of package a folder holds, from the one manifest file it has at
81
+ * its root (`SKILL.md` or `hook.yaml`). Throws when it has neither or both, or
82
+ * when the command that asked (`expected`) is for the other kind.
83
+ */
84
+ export function packageKindOf(entries, expected) {
85
+ const kinds = packageKindList.filter((kind) => entries.some((entry) => entry.path === assetKinds[kind].manifest));
86
+ const kind = only(kinds);
87
+ if (!kind) {
88
+ throw new CliError(kinds.length
89
+ ? `This folder has both ${kinds.map((k) => assetKinds[k].manifest).join(" and ")}, so it isn't clear what to push.`
90
+ : `This folder has no ${packageKindList.map((k) => assetKinds[k].manifest).join(" or ")}, so there is nothing to push.`, `Keep exactly one of ${packageKindList.map((k) => `${assetKinds[k].manifest} for ${assetKinds[k].a}`).join(" or ")}.`);
91
+ }
92
+ if (expected && expected !== kind) {
93
+ throw new CliError(`This folder holds ${assetKinds[kind].a}, not ${assetKinds[expected].a}.`, `barndog ${assetKinds[kind].command} push --origin <origin>`);
94
+ }
95
+ return kind;
96
+ }
97
+ /**
98
+ * A package's metadata: the `SKILL.md` front matter, or the parsed `hook.yaml`
99
+ * manifest. Throws when the manifest is missing or invalid, or a Hook script it
100
+ * names is missing.
101
+ */
102
+ export function metadata(entries, kind) {
103
+ if (kind === "skill") {
104
+ return packageMetadata(entries);
105
+ }
106
+ if (!entries.some((e) => e.path === "hook.yaml")) {
107
+ throw new PackageError("MISSING_PACKAGE_MANIFEST", "hook.yaml");
108
+ }
109
+ const manifest = hookManifestSchema.parse(parse(entries.find((e) => e.path === "hook.yaml")?.data.toString("utf8") ?? ""));
110
+ for (const implementation of Object.values(manifest.implementations)) {
111
+ if (implementation) {
112
+ for (const script of implementation.scripts) {
113
+ if (!entries.some((e) => e.path === script)) {
114
+ throw new PackageError("MISSING_HOOK_SCRIPT", script);
115
+ }
116
+ }
117
+ }
118
+ }
119
+ return manifest;
120
+ }