barndog 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/README.md +11 -10
  2. package/dist/cli.js +11 -7
  3. package/dist/commands/add.js +33 -21
  4. package/dist/commands/arguments.js +12 -0
  5. package/dist/commands/asset-install.js +160 -0
  6. package/dist/commands/asset-list.js +121 -0
  7. package/dist/commands/asset-share.js +94 -0
  8. package/dist/commands/auth.js +4 -0
  9. package/dist/commands/availability.js +54 -26
  10. package/dist/commands/capabilities.js +71 -415
  11. package/dist/commands/collaboration.js +194 -110
  12. package/dist/commands/environment.js +18 -411
  13. package/dist/commands/github.js +200 -0
  14. package/dist/commands/helpers.js +39 -0
  15. package/dist/commands/hooks.js +87 -0
  16. package/dist/commands/init.js +4 -2
  17. package/dist/commands/knowledge.js +73 -0
  18. package/dist/commands/mcp.js +62 -0
  19. package/dist/commands/origin.js +21 -23
  20. package/dist/commands/people.js +51 -0
  21. package/dist/commands/sets.js +141 -0
  22. package/dist/commands/status.js +34 -24
  23. package/dist/commands/sync.js +11 -4
  24. package/dist/commands/workspace.js +33 -19
  25. package/dist/config/environment.js +13 -27
  26. package/dist/config/paths.js +62 -0
  27. package/dist/config/selection.js +30 -0
  28. package/dist/config/settings.js +97 -108
  29. package/dist/config/state.js +57 -57
  30. package/dist/entry/knowledge-startup.js +32 -0
  31. package/dist/entry/mcp-launch.js +71 -0
  32. package/dist/entry/opencode-plugin.js +62 -0
  33. package/dist/{features/git-workspace/startup.js → entry/workspace-startup.js} +7 -2
  34. package/dist/errors.js +198 -55
  35. package/dist/features/asset-kinds/index.js +120 -0
  36. package/dist/features/asset-selection/index.js +51 -19
  37. package/dist/features/auth/credentials.js +80 -47
  38. package/dist/features/auth/session.js +80 -45
  39. package/dist/features/auth/transport.js +66 -15
  40. package/dist/features/catalog/index.js +32 -61
  41. package/dist/features/collaboration/api.js +160 -0
  42. package/dist/features/collaboration/index.js +321 -233
  43. package/dist/features/collaboration/remote.js +35 -115
  44. package/dist/features/collaboration/results.js +2 -0
  45. package/dist/features/collaboration/workspace-git.js +233 -149
  46. package/dist/features/collaboration/workspace-github.js +117 -54
  47. package/dist/features/collaboration/workspace-store.js +140 -100
  48. package/dist/features/collaboration/workspace.js +257 -172
  49. package/dist/features/discovery/index.js +68 -57
  50. package/dist/features/doctor/index.js +32 -24
  51. package/dist/features/environment/auto-sync.js +28 -27
  52. package/dist/features/environment/names.js +67 -47
  53. package/dist/features/environment/operations.js +321 -228
  54. package/dist/features/environment/own-entries.js +89 -0
  55. package/dist/features/environment/settle-names.js +91 -0
  56. package/dist/features/environment/stage.js +178 -0
  57. package/dist/features/environment/sync.js +113 -484
  58. package/dist/features/environment/transaction.js +179 -147
  59. package/dist/features/environment/writes.js +196 -0
  60. package/dist/features/github/account.js +25 -0
  61. package/dist/features/github/connections.js +119 -0
  62. package/dist/features/github/pulls.js +118 -0
  63. package/dist/features/hooks/adapt.js +32 -25
  64. package/dist/features/hooks/catalog.js +28 -0
  65. package/dist/features/hooks/compatibility.js +49 -0
  66. package/dist/features/hooks/divergence.js +9 -6
  67. package/dist/features/hooks/test.js +74 -49
  68. package/dist/features/hooks/types.js +1 -0
  69. package/dist/features/imports/discover.js +134 -61
  70. package/dist/features/imports/folder.js +48 -14
  71. package/dist/features/imports/local.js +113 -134
  72. package/dist/features/imports/remote.js +44 -25
  73. package/dist/features/inspection/index.js +17 -17
  74. package/dist/features/inventory/index.js +99 -110
  75. package/dist/features/knowledge/index.js +69 -49
  76. package/dist/features/mcps/catalog.js +31 -0
  77. package/dist/features/mcps/import.js +316 -0
  78. package/dist/features/mcps/index.js +98 -49
  79. package/dist/features/migration/migrate.js +263 -0
  80. package/dist/features/{git-workspace → migration}/move.js +165 -109
  81. package/dist/features/migration/promote.js +24 -0
  82. package/dist/features/native/adapters.js +53 -94
  83. package/dist/features/native/configuration.js +128 -82
  84. package/dist/features/native/hook-shell.js +55 -0
  85. package/dist/features/native/plugin-module.js +56 -0
  86. package/dist/features/onboarding/environment.js +67 -34
  87. package/dist/features/onboarding/setup.js +43 -40
  88. package/dist/features/repositories/context.js +30 -13
  89. package/dist/features/server/catalog.js +58 -0
  90. package/dist/features/server/client.js +13 -0
  91. package/dist/features/server/connection.js +37 -0
  92. package/dist/features/server/origin.js +74 -0
  93. package/dist/features/server/pages.js +24 -0
  94. package/dist/features/skills/catalog.js +42 -0
  95. package/dist/features/workspace/assets.js +57 -0
  96. package/dist/features/workspace/cloud-source.js +34 -0
  97. package/dist/features/workspace/directory.js +38 -0
  98. package/dist/features/{git-workspace → workspace}/format.js +114 -51
  99. package/dist/features/workspace/git.js +214 -0
  100. package/dist/features/workspace/installed.js +92 -0
  101. package/dist/features/{git-workspace → workspace}/overlay.js +43 -23
  102. package/dist/features/workspace/packages.js +160 -0
  103. package/dist/features/{git-workspace → workspace}/publish.js +120 -64
  104. package/dist/features/workspace/repo-source.js +192 -0
  105. package/dist/features/{git-workspace → workspace}/setup.js +60 -42
  106. package/dist/features/{git-workspace → workspace}/snapshot.js +53 -18
  107. package/dist/features/workspace/source.js +1 -0
  108. package/dist/features/workspace/tree.js +52 -0
  109. package/dist/features/workspace/workspace-source.js +27 -0
  110. package/dist/harnesses/claude.js +23 -1
  111. package/dist/harnesses/codex.js +57 -1
  112. package/dist/harnesses/cursor.js +22 -1
  113. package/dist/harnesses/detect.js +6 -50
  114. package/dist/harnesses/formats.js +45 -0
  115. package/dist/harnesses/opencode.js +111 -0
  116. package/dist/harnesses/registry.js +35 -2
  117. package/dist/platform.js +375 -0
  118. package/dist/program.js +225 -54
  119. package/dist/runtime.js +1 -0
  120. package/dist/shared/cli-error.js +22 -0
  121. package/dist/shared/constants.js +32 -0
  122. package/dist/shared/files.js +72 -0
  123. package/dist/shared/lock.js +49 -0
  124. package/dist/shared/lookup.js +11 -0
  125. package/dist/shared/patterns.js +94 -0
  126. package/dist/shared/shell.js +22 -0
  127. package/dist/shared/values.js +26 -0
  128. package/dist/ui/add-asset.js +41 -400
  129. package/dist/ui/add-hook.js +213 -0
  130. package/dist/ui/add-mcp.js +107 -0
  131. package/dist/ui/add-prompts.js +47 -0
  132. package/dist/ui/add-skills.js +115 -0
  133. package/dist/ui/asset-list.js +31 -13
  134. package/dist/ui/assets.js +33 -44
  135. package/dist/ui/auth.js +43 -33
  136. package/dist/ui/clash.js +11 -6
  137. package/dist/ui/collaboration.js +116 -44
  138. package/dist/ui/connection.js +10 -4
  139. package/dist/ui/decision-error.js +24 -0
  140. package/dist/ui/environment-onboarding.js +35 -13
  141. package/dist/ui/format.js +66 -18
  142. package/dist/ui/hook-compatibility.js +14 -6
  143. package/dist/ui/mcp.js +28 -3
  144. package/dist/ui/move.js +10 -5
  145. package/dist/ui/onboarding.js +113 -73
  146. package/dist/ui/options.js +9 -0
  147. package/dist/ui/output.js +106 -43
  148. package/dist/ui/pick.js +45 -33
  149. package/dist/ui/scope-install.js +15 -7
  150. package/dist/ui/selection.js +15 -11
  151. package/dist/ui/theme.js +37 -14
  152. package/dist/version.js +6 -3
  153. package/package.json +24 -11
  154. package/dist/features/capabilities/index.js +0 -106
  155. package/dist/features/collaboration/domain.js +0 -90
  156. package/dist/features/environment/cloud-source.js +0 -27
  157. package/dist/features/environment/installed.js +0 -124
  158. package/dist/features/environment/packages.js +0 -120
  159. package/dist/features/environment/remote.js +0 -71
  160. package/dist/features/environment/workspace-source.js +0 -19
  161. package/dist/features/git-hosts/index.js +0 -148
  162. package/dist/features/git-workspace/assets.js +0 -71
  163. package/dist/features/git-workspace/git.js +0 -135
  164. package/dist/features/git-workspace/migrate.js +0 -188
  165. package/dist/features/git-workspace/source.js +0 -159
  166. package/dist/features/imports/mcp.js +0 -219
  167. package/dist/features/knowledge/startup.js +0 -25
  168. package/dist/features/native/mcp-launch.js +0 -57
  169. package/dist/features/skills/install.js +0 -25
  170. package/dist/features/skills/remote.js +0 -177
  171. package/dist/features/skills/sync.js +0 -121
  172. package/dist/features/skills/validation.js +0 -34
  173. /package/dist/features/environment/{source.js → events.js} +0 -0
@@ -1,90 +1,116 @@
1
1
  import { parse as parseJson, parseTree, createScanner, findNodeAtLocation, modify, applyEdits, } from "jsonc-parser";
2
2
  import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
3
+ // Two TOML libraries on purpose: smol-toml parses and writes values but keeps no
4
+ // source positions, and toml-eslint-parser (despite the name, a plain TOML parser
5
+ // that doesn't need ESLint) gives each table's range in the text. See tomlEdit().
3
6
  import { parseForESLint } from "toml-eslint-parser";
4
7
  import { isDeepStrictEqual } from "node:util";
5
- import { join } from "node:path";
6
- export const nativeFile = (harness, kind, home) => kind === "mcp"
7
- ? join(home, harness === "claude"
8
- ? ".claude.json"
9
- : harness === "codex"
10
- ? ".codex/config.toml"
11
- : ".cursor/mcp.json")
12
- : join(home, harness === "claude"
13
- ? ".claude/settings.json"
14
- : harness === "codex"
15
- ? ".codex/hooks.json"
16
- : ".cursor/hooks.json");
17
- export function object(value) {
18
- if (!value || typeof value !== "object" || Array.isArray(value))
19
- throw new Error("Native configuration must contain an object");
8
+ import { adapters } from "../../harnesses/registry.js";
9
+ import { isRecord } from "../../shared/values.js";
10
+ import { CliError } from "../../errors.js";
11
+ function object(value, file) {
12
+ if (!isRecord(value)) {
13
+ throw new CliError(`${file} doesn't hold the settings object BarnDog expects, so it was left unchanged. Fix it, then sync again.`, "barndog sync");
14
+ }
20
15
  return value;
21
16
  }
22
17
  function same(left, right) {
23
- if (left === undefined || right === undefined)
18
+ if (left === undefined || right === undefined) {
24
19
  return left === right;
20
+ }
25
21
  return isDeepStrictEqual(JSON.parse(JSON.stringify(left)), JSON.parse(JSON.stringify(right)));
26
22
  }
27
- function json(text) {
23
+ function json(text, file) {
28
24
  const errors = [];
29
- const value = parseJson(text || "{}", errors, { allowTrailingComma: true });
30
- if (errors.length)
31
- throw new Error("Invalid native JSON configuration; installation preserved");
32
- return object(value);
25
+ const value = parseJson(text || "{}", errors, {
26
+ allowTrailingComma: true,
27
+ });
28
+ if (errors.length) {
29
+ throw new CliError(`${file} isn't valid JSON, so BarnDog left it unchanged. Fix it, then sync again.`, "barndog sync");
30
+ }
31
+ return object(value, file);
33
32
  }
33
+ /**
34
+ * Replaces or removes one `[mcp_servers.<key>]` entry in Codex's config.toml by
35
+ * cutting its source range out of the text, so comments and unrelated settings
36
+ * survive. toml-eslint-parser finds the ranges; smol-toml writes the new entry
37
+ * and checks the result still parses. Re-serializing the whole file with
38
+ * smol-toml would drop every comment.
39
+ */
34
40
  function tomlEdit(text, key, value) {
35
41
  const ast = parseForESLint(text).ast;
36
42
  const ranges = [];
37
43
  for (const node of ast.body[0].body) {
38
44
  if (node.type === "TOMLTable") {
39
45
  const path = node.resolvedKey;
40
- if (path[0] === "mcp_servers" && path[1] === key)
46
+ if (path[0] === "mcp_servers" && path[1] === key) {
41
47
  ranges.push(node.range);
48
+ }
42
49
  else if (path.length === 1 && path[0] === "mcp_servers") {
43
- for (const entry of node.body)
50
+ for (const entry of node.body) {
44
51
  if (entry.key.keys[0] &&
45
52
  ("name" in entry.key.keys[0]
46
53
  ? entry.key.keys[0].name
47
- : entry.key.keys[0].value) === key)
54
+ : entry.key.keys[0].value) === key) {
48
55
  ranges.push(entry.range);
56
+ }
57
+ }
49
58
  }
50
59
  }
51
60
  else {
52
61
  const path = node.key.keys.map((k) => ("name" in k ? k.name : k.value));
53
- if (path[0] === "mcp_servers" && path.length === 1)
54
- throw new Error("Codex inline mcp_servers layout cannot be edited safely; installation preserved");
55
- if (path[0] === "mcp_servers" && path[1] === key)
62
+ if (path[0] === "mcp_servers" && path.length === 1) {
63
+ throw new CliError("~/.codex/config.toml lists MCP servers inline (mcp_servers = { ... }), which BarnDog can't edit safely, so it was left unchanged. Give each server its own [mcp_servers.<name>] table, then sync again.", "barndog sync");
64
+ }
65
+ if (path[0] === "mcp_servers" && path[1] === key) {
56
66
  ranges.push(node.range);
67
+ }
57
68
  }
58
69
  }
59
- for (const [start, end] of ranges.sort((a, b) => b[0] - a[0]))
70
+ for (const [start, end] of ranges.sort((a, b) => b[0] - a[0])) {
60
71
  text = text.slice(0, start) + text.slice(end);
61
- if (value)
72
+ }
73
+ if (value) {
62
74
  text =
63
75
  text.trimEnd() +
64
76
  "\n\n" +
65
77
  stringifyToml({ mcp_servers: { [key]: value } });
78
+ }
66
79
  parseToml(text);
67
80
  return text;
68
81
  }
69
82
  /** Modify owned entries only. Unmanaged JSON/TOML text outside those entries is retained. */
70
83
  export function patchNative(text, before, after) {
71
84
  const sample = after[0] ?? before[0];
72
- if (!sample)
73
- throw new Error("Missing native configuration entries");
85
+ if (!sample) {
86
+ throw new Error("patchNative needs at least one entry to know which file it edits");
87
+ }
74
88
  const toml = sample.file.endsWith(".toml");
89
+ // Only the hook settings file carries a version; MCP files never do.
90
+ const version = sample.kind === "mcp"
91
+ ? undefined
92
+ : adapters[sample.harness].hooks?.fileVersion;
75
93
  let output = text ??
76
- (sample.harness === "cursor" && sample.kind !== "mcp"
77
- ? '{\n "version": 1\n}\n'
78
- : "{}\n");
79
- const read = () => toml ? object(parseToml(text === null ? "" : output)) : json(output);
94
+ `${JSON.stringify(version === undefined ? {} : { version }, null, 2)}\n`;
95
+ const read = () => toml
96
+ ? object(parseToml(text === null ? "" : output), sample.file)
97
+ : json(output, sample.file);
80
98
  let data = read();
81
- if (toml && text === null)
99
+ if (toml && text === null) {
82
100
  output = "";
101
+ }
83
102
  const change = (path, value) => {
84
- if (value === undefined && typeof path.at(-1) === "number") {
85
- const parent = findNodeAtLocation(parseTree(output), path.slice(0, -1));
86
- const index = path.at(-1), nodes = parent.children, node = nodes[index];
87
- const previous = nodes[index - 1], next = nodes[index + 1];
103
+ const index = path.at(-1);
104
+ if (value === undefined && typeof index === "number") {
105
+ const tree = parseTree(output);
106
+ const parent = tree && findNodeAtLocation(tree, path.slice(0, -1));
107
+ const nodes = parent?.children;
108
+ const node = nodes?.[index];
109
+ if (!parent || !nodes || !node) {
110
+ throw new CliError(`${sample.file} changed while BarnDog was editing it. Try again.`, "barndog sync");
111
+ }
112
+ const previous = nodes[index - 1];
113
+ const next = nodes[index + 1];
88
114
  const start = previous
89
115
  ? previous.offset + previous.length
90
116
  : node.offset + node.length;
@@ -93,104 +119,124 @@ export function patchNative(text, before, after) {
93
119
  : (next?.offset ?? parent.offset + parent.length - 1);
94
120
  const scanner = createScanner(output.slice(start, end), true);
95
121
  let comma = -1;
96
- while (scanner.scan() !== 17 /* SyntaxKind.EOF */)
122
+ while (scanner.scan() !== 17 /* SyntaxKind.EOF */) {
97
123
  if (scanner.getToken() === 5 /* SyntaxKind.CommaToken */) {
98
124
  comma = start + scanner.getTokenOffset();
99
125
  break;
100
126
  }
127
+ }
101
128
  const edits = [{ offset: node.offset, length: node.length, content: "" }];
102
- if (comma >= 0)
129
+ if (comma >= 0) {
103
130
  edits.push({ offset: comma, length: 1, content: "" });
131
+ }
104
132
  output = applyEdits(output, edits);
105
133
  }
106
- else
134
+ else {
107
135
  output = applyEdits(output, modify(output, path, value, {}));
108
- data = json(output);
136
+ }
137
+ data = json(output, sample.file);
138
+ };
139
+ const table = (key) => data[key] === undefined ? {} : object(data[key], sample.file);
140
+ /** Where the tool keeps its MCP servers, such as `mcpServers` or `mcp.servers`. */
141
+ const serversPath = adapters[sample.harness].mcp.path;
142
+ const servers = () => serversPath.reduce((parent, key) => parent[key] === undefined ? {} : object(parent[key], sample.file), data);
143
+ /** The handlers registered for one hook event. */
144
+ const list = (event) => {
145
+ const handlers = table("hooks")[event];
146
+ return Array.isArray(handlers) ? handlers : [];
109
147
  };
110
- const table = (key) => data[key] === undefined ? {} : object(data[key]);
111
148
  for (const old of before) {
112
149
  if (old.kind === "mcp") {
113
- const parent = toml ? "mcp_servers" : "mcpServers";
114
- if (!same(table(parent)[old.key], old.value))
115
- throw new Error(`Managed MCP was changed externally: ${old.key}`);
150
+ if (!same(servers()[old.key], old.value)) {
151
+ throw new CliError(`The MCP server ${old.key} that BarnDog installed in ${sample.file} was changed by hand. Undo that edit or remove the entry, then sync again.`, "barndog sync");
152
+ }
116
153
  }
117
154
  else {
118
155
  const list = table("hooks")[old.key];
119
156
  if (!Array.isArray(list) ||
120
- list.filter((v) => same(v, old.value)).length !== 1)
121
- throw new Error(`Managed Hook was changed externally: ${old.key}`);
157
+ list.filter((v) => same(v, old.value)).length !== 1) {
158
+ throw new CliError(`The ${old.key} Hook that BarnDog installed in ${sample.file} was changed by hand. Undo that edit or remove the entry, then sync again.`, "barndog sync");
159
+ }
122
160
  }
123
161
  }
124
162
  // Detect collisions before removing anything, including semantically identical unmanaged registrations.
125
163
  for (const next of after) {
126
164
  if (next.kind === "mcp") {
127
- const parent = toml ? "mcp_servers" : "mcpServers";
128
- if (Object.hasOwn(table(parent), next.key) &&
129
- !before.some((old) => old.kind === "mcp" && old.key === next.key))
130
- throw new Error(`Existing unmanaged MCP: ${next.key}`);
131
- if (after.filter((e) => e.kind === "mcp" && e.key === next.key).length > 1)
132
- throw new Error(`Conflicting MCP name: ${next.key}`);
165
+ if (Object.hasOwn(servers(), next.key) &&
166
+ !before.some((old) => old.kind === "mcp" && old.key === next.key)) {
167
+ throw new CliError(`${sample.file} already has an MCP server named ${next.key} that BarnDog didn't add. Remove it, or install BarnDog's under another name.`, `barndog mcp rename ${next.key}`);
168
+ }
169
+ if (after.filter((e) => e.kind === "mcp" && e.key === next.key).length > 1) {
170
+ throw new CliError(`Two MCP servers would both be installed as ${next.key}.`, `barndog mcp rename ${next.key}`);
171
+ }
133
172
  }
134
173
  else {
135
- if (after.filter((e) => e.kind !== "mcp" && e.key === next.key && same(e.value, next.value)).length > 1)
136
- throw new Error(`Duplicate Hook registration: ${next.key}`);
174
+ if (after.filter((e) => e.kind !== "mcp" && e.key === next.key && same(e.value, next.value)).length > 1) {
175
+ throw new Error(`The same ${next.key} Hook handler was planned twice`);
176
+ }
137
177
  const list = table("hooks")[next.key];
138
- if (list !== undefined && !Array.isArray(list))
139
- throw new Error(`Invalid native Hook list: ${next.key}`);
178
+ if (list !== undefined && !Array.isArray(list)) {
179
+ throw new CliError(`hooks.${next.key} in ${sample.file} isn't a list, so BarnDog left the file unchanged. Fix it, then sync again.`, "barndog sync");
180
+ }
140
181
  if (Array.isArray(list) &&
141
182
  list.some((v) => same(v, next.value)) &&
142
- !before.some((old) => old.key === next.key && same(old.value, next.value)))
143
- throw new Error(`Existing unmanaged Hook: ${next.key}`);
183
+ !before.some((old) => old.key === next.key && same(old.value, next.value))) {
184
+ throw new CliError(`${sample.file} already runs this ${next.key} Hook, but BarnDog didn't add it. Remove your copy, then sync again.`, "barndog sync");
185
+ }
144
186
  }
145
187
  }
146
188
  for (const old of before) {
147
189
  if (after.some((next) => next.kind === old.kind &&
148
190
  next.key === old.key &&
149
191
  next.id === old.id &&
150
- same(next.value, old.value)))
192
+ same(next.value, old.value))) {
151
193
  continue;
194
+ }
152
195
  if (old.kind === "mcp") {
153
196
  if (toml) {
154
197
  output = tomlEdit(output, old.key, undefined);
155
- data = object(parseToml(output));
198
+ data = object(parseToml(output), sample.file);
199
+ }
200
+ else {
201
+ change([...serversPath, old.key], undefined);
156
202
  }
157
- else
158
- change(["mcpServers", old.key], undefined);
159
203
  }
160
204
  else {
161
- const list = table("hooks")[old.key];
162
- const index = list.findIndex((v) => same(v, old.value));
205
+ const index = list(old.key).findIndex((v) => same(v, old.value));
163
206
  change(["hooks", old.key, index], undefined);
164
- if (!table("hooks")[old.key].length)
207
+ if (!list(old.key).length) {
165
208
  change(["hooks", old.key], undefined);
209
+ }
166
210
  }
167
211
  }
168
212
  for (const next of after) {
169
213
  if (before.some((old) => old.kind === next.kind &&
170
214
  old.key === next.key &&
171
215
  old.id === next.id &&
172
- same(old.value, next.value)))
216
+ same(old.value, next.value))) {
173
217
  continue;
218
+ }
174
219
  if (next.kind === "mcp") {
175
220
  if (toml) {
176
221
  output = tomlEdit(output, next.key, next.value);
177
- data = object(parseToml(output));
222
+ data = object(parseToml(output), sample.file);
223
+ }
224
+ else {
225
+ change([...serversPath, next.key], next.value);
178
226
  }
179
- else
180
- change(["mcpServers", next.key], next.value);
181
227
  }
182
228
  else {
183
- const list = table("hooks")[next.key];
184
- if (list)
185
- change(["hooks", next.key, list.length], next.value);
186
- else
229
+ const handlers = table("hooks")[next.key];
230
+ if (Array.isArray(handlers)) {
231
+ change(["hooks", next.key, handlers.length], next.value);
232
+ }
233
+ else {
187
234
  change(["hooks", next.key], [next.value]);
235
+ }
188
236
  }
189
237
  }
190
- if (!toml &&
191
- sample.harness === "cursor" &&
192
- sample.kind !== "mcp" &&
193
- data.version !== 1)
194
- throw new Error("Unsupported Cursor Hook configuration version");
238
+ if (version !== undefined && data.version !== version) {
239
+ throw new CliError(`${sample.file} has a version BarnDog doesn't support (it expects "version": ${version}), so it was left unchanged.`);
240
+ }
195
241
  return output;
196
242
  }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Command lines BarnDog registers in a coding tool's hook settings, written
3
+ * for the shell that tool runs them in (`windowsShell` in its hook profile).
4
+ * The tool runs them, so BarnDog only has to get the syntax right.
5
+ */
6
+ import { bashShell, encodedPowerShell, isWindows, powershellCall, } from "../../platform.js";
7
+ import { adapters } from "../../harnesses/registry.js";
8
+ import { posixQuote, posixWord, powershellQuote } from "../../shared/shell.js";
9
+ /** Git Bash reads `C:/x` as `C:\x`, and `/` needs no thought inside quotes. */
10
+ const bashPath = (path, platform) => isWindows(platform) ? path.replaceAll("\\", "/") : path;
11
+ function lineFor(harness, line, platform) {
12
+ if (!isWindows(platform)) {
13
+ return line.posix;
14
+ }
15
+ switch (adapters[harness].hooks.windowsShell) {
16
+ case "bash":
17
+ return line.posix;
18
+ case "powershell":
19
+ return line.powershell;
20
+ }
21
+ }
22
+ /** Starts a program (BarnDog's own entry scripts) from the tool's hook shell. */
23
+ export function programLine(harness, args, platform) {
24
+ return lineFor(harness, {
25
+ posix: args.map((arg) => posixWord(bashPath(arg, platform))).join(" "),
26
+ powershell: powershellCall(args),
27
+ }, platform);
28
+ }
29
+ /**
30
+ * The Hook author's command with `BARNDOG_HOOK_ROOT` and the tool's own root
31
+ * variables set to the installed folder, so a script written for the tool
32
+ * finds its files and recognises where it runs.
33
+ */
34
+ function hookLine(root, command, harness, platform) {
35
+ const variables = [
36
+ "BARNDOG_HOOK_ROOT",
37
+ ...adapters[harness].hooks.rootVariables,
38
+ ];
39
+ const posixRoot = posixQuote(bashPath(root, platform));
40
+ return {
41
+ posix: `export ${variables.map((name) => `${name}=${posixRoot}`).join(" ")}; ${command}`,
42
+ powershell: `${variables.map((name) => `$env:${name}=${powershellQuote(root)}`).join("; ")}; ${command}`,
43
+ };
44
+ }
45
+ export const hookCommand = (root, command, harness, platform) => lineFor(harness, hookLine(root, command, harness, platform), platform);
46
+ /** How `hooks test` runs a Hook: in the shell its tool would use. */
47
+ export async function hookInvocation(root, command, harness, runtime) {
48
+ const line = hookLine(root, command, harness, runtime.platform);
49
+ if (isWindows(runtime.platform) &&
50
+ adapters[harness].hooks.windowsShell !== "bash") {
51
+ return encodedPowerShell(line.powershell);
52
+ }
53
+ const shell = await bashShell(runtime);
54
+ return { command: shell.command, args: [...shell.args, line.posix] };
55
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * BarnDog's plugin module for a coding tool without command hooks (OpenCode).
3
+ * BarnDog owns the whole file: its text is rendered from the session-start
4
+ * entries a sync plans, and a file that differs from what the previous sync
5
+ * wrote was edited by hand.
6
+ */
7
+ import { z } from "zod";
8
+ import { CliError } from "../../errors.js";
9
+ import { adapters } from "../../harnesses/registry.js";
10
+ import { removeCommand } from "../../platform.js";
11
+ import { defined } from "../../shared/lookup.js";
12
+ /** The value of a session-start entry kept in a plugin module (see `startupEntries()`). */
13
+ const pluginEntrySchema = z.object({
14
+ /** BarnDog's plugin entry script, as a file URL. */
15
+ entry: z.string(),
16
+ command: z.array(z.string()),
17
+ });
18
+ /** Whether these entries live in a tool's plugin module rather than a settings file. */
19
+ export function inPluginModule(entries) {
20
+ const sample = entries[0];
21
+ return (sample !== undefined &&
22
+ sample.kind !== "mcp" &&
23
+ adapters[sample.harness].hooks === undefined);
24
+ }
25
+ /** The module's text for `entries`, or null when there are none and the file goes away. */
26
+ function render(entries) {
27
+ const sample = entries[0];
28
+ if (!sample) {
29
+ return null;
30
+ }
31
+ const adapter = adapters[sample.harness];
32
+ const plugin = defined(adapter.plugin, `${adapter.name} has no plugin module`);
33
+ const options = Object.fromEntries([...entries]
34
+ .sort((a, b) => a.key.localeCompare(b.key))
35
+ .map((entry) => [
36
+ entry.key,
37
+ pluginEntrySchema.parse(entry.value).command,
38
+ ]));
39
+ return plugin.module(pluginEntrySchema.parse(sample.value).entry, options);
40
+ }
41
+ /**
42
+ * The plugin module's next text, after checking that `text` (what is on disk,
43
+ * null when absent) is what BarnDog wrote for `before`. Null removes it.
44
+ */
45
+ export function pluginModule(text, change, platform) {
46
+ const { before, after } = change;
47
+ const { file } = defined(after[0] ?? before[0], "pluginModule needs at least one entry to know which file it writes");
48
+ if (text !== render(before)) {
49
+ throw new CliError(before.length
50
+ ? `${file} was changed by hand, so BarnDog left it unchanged.`
51
+ : `${file} already exists, and BarnDog didn't write it.`, before.length
52
+ ? "Delete it, then sync again to write it afresh."
53
+ : "Move it elsewhere if you need it, delete it, then sync again.", { command: removeCommand(file, platform) });
54
+ }
55
+ return render(after);
56
+ }
@@ -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
  }