barndog 0.1.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/README.md +31 -28
  2. package/dist/cli.js +11 -7
  3. package/dist/commands/add.js +34 -21
  4. package/dist/commands/adopt.js +91 -0
  5. package/dist/commands/arguments.js +12 -0
  6. package/dist/commands/asset-install.js +161 -0
  7. package/dist/commands/asset-list.js +126 -0
  8. package/dist/commands/asset-share.js +94 -0
  9. package/dist/commands/auth.js +4 -0
  10. package/dist/commands/availability.js +72 -27
  11. package/dist/commands/capabilities.js +79 -417
  12. package/dist/commands/collaboration.js +212 -108
  13. package/dist/commands/environment.js +18 -411
  14. package/dist/commands/github.js +200 -0
  15. package/dist/commands/harnesses.js +74 -0
  16. package/dist/commands/helpers.js +39 -0
  17. package/dist/commands/hooks.js +87 -0
  18. package/dist/commands/init.js +4 -2
  19. package/dist/commands/knowledge.js +73 -0
  20. package/dist/commands/mcp-env.js +78 -0
  21. package/dist/commands/mcp.js +64 -0
  22. package/dist/commands/origin.js +21 -23
  23. package/dist/commands/people.js +51 -0
  24. package/dist/commands/sets.js +141 -0
  25. package/dist/commands/status.js +36 -25
  26. package/dist/commands/sync.js +13 -5
  27. package/dist/commands/workspace.js +75 -23
  28. package/dist/config/environment.js +13 -27
  29. package/dist/config/paths.js +81 -0
  30. package/dist/config/selection.js +30 -0
  31. package/dist/config/settings.js +99 -108
  32. package/dist/config/state.js +67 -55
  33. package/dist/entry/knowledge-startup.js +32 -0
  34. package/dist/entry/mcp-launch.js +71 -0
  35. package/dist/entry/opencode-plugin.js +62 -0
  36. package/dist/{features/git-workspace/startup.js → entry/workspace-startup.js} +7 -2
  37. package/dist/errors.js +198 -55
  38. package/dist/features/adoption/adopt.js +234 -0
  39. package/dist/features/adoption/copies.js +29 -0
  40. package/dist/features/adoption/originals.js +116 -0
  41. package/dist/features/adoption/record.js +120 -0
  42. package/dist/features/adoption/restore.js +28 -0
  43. package/dist/features/adoption/scan.js +482 -0
  44. package/dist/features/adoption/undo.js +42 -0
  45. package/dist/features/asset-kinds/index.js +129 -0
  46. package/dist/features/asset-selection/index.js +51 -19
  47. package/dist/features/auth/credentials.js +80 -54
  48. package/dist/features/auth/session.js +83 -49
  49. package/dist/features/auth/transport.js +69 -17
  50. package/dist/features/catalog/index.js +32 -61
  51. package/dist/features/collaboration/api.js +160 -0
  52. package/dist/features/collaboration/index.js +321 -233
  53. package/dist/features/collaboration/remote.js +35 -115
  54. package/dist/features/collaboration/results.js +2 -0
  55. package/dist/features/collaboration/workspace-git.js +242 -152
  56. package/dist/features/collaboration/workspace-github.js +118 -54
  57. package/dist/features/collaboration/workspace-store.js +157 -97
  58. package/dist/features/collaboration/workspace.js +278 -173
  59. package/dist/features/discovery/index.js +68 -57
  60. package/dist/features/doctor/index.js +56 -26
  61. package/dist/features/environment/auto-sync.js +28 -27
  62. package/dist/features/environment/harnesses.js +36 -0
  63. package/dist/features/environment/moves.js +171 -0
  64. package/dist/features/environment/names.js +73 -49
  65. package/dist/features/environment/operations.js +322 -229
  66. package/dist/features/environment/own-entries.js +89 -0
  67. package/dist/features/environment/settle-names.js +91 -0
  68. package/dist/features/environment/stage.js +202 -0
  69. package/dist/features/environment/sync.js +127 -487
  70. package/dist/features/environment/transaction.js +179 -147
  71. package/dist/features/environment/writes.js +243 -0
  72. package/dist/features/github/account.js +25 -0
  73. package/dist/features/github/connections.js +119 -0
  74. package/dist/features/github/pulls.js +118 -0
  75. package/dist/features/hooks/adapt.js +32 -25
  76. package/dist/features/hooks/catalog.js +28 -0
  77. package/dist/features/hooks/compatibility.js +55 -0
  78. package/dist/features/hooks/divergence.js +36 -12
  79. package/dist/features/hooks/test.js +91 -66
  80. package/dist/features/hooks/types.js +1 -0
  81. package/dist/features/imports/discover.js +133 -60
  82. package/dist/features/imports/folder.js +48 -14
  83. package/dist/features/imports/local.js +127 -135
  84. package/dist/features/imports/remote.js +46 -26
  85. package/dist/features/inspection/index.js +17 -17
  86. package/dist/features/inventory/index.js +111 -111
  87. package/dist/features/inventory/show.js +74 -0
  88. package/dist/features/knowledge/index.js +69 -49
  89. package/dist/features/mcps/catalog.js +31 -0
  90. package/dist/features/mcps/import.js +369 -0
  91. package/dist/features/mcps/index.js +104 -50
  92. package/dist/features/mcps/values.js +33 -0
  93. package/dist/features/migration/migrate.js +263 -0
  94. package/dist/features/migration/move.js +448 -0
  95. package/dist/features/migration/promote.js +26 -0
  96. package/dist/features/native/adapters.js +69 -96
  97. package/dist/features/native/configuration.js +134 -84
  98. package/dist/features/native/hook-shell.js +55 -0
  99. package/dist/features/native/plugin-module.js +56 -0
  100. package/dist/features/native/secret-values.js +74 -0
  101. package/dist/features/onboarding/environment.js +67 -34
  102. package/dist/features/onboarding/setup.js +43 -40
  103. package/dist/features/repositories/context.js +30 -13
  104. package/dist/features/secrets/index.js +77 -0
  105. package/dist/features/server/catalog.js +58 -0
  106. package/dist/features/server/client.js +13 -0
  107. package/dist/features/server/connection.js +37 -0
  108. package/dist/features/server/origin.js +74 -0
  109. package/dist/features/server/pages.js +24 -0
  110. package/dist/features/skills/catalog.js +42 -0
  111. package/dist/features/workspace/assets.js +57 -0
  112. package/dist/features/workspace/cloud-source.js +34 -0
  113. package/dist/features/workspace/directory.js +38 -0
  114. package/dist/features/{git-workspace → workspace}/format.js +121 -54
  115. package/dist/features/workspace/git.js +221 -0
  116. package/dist/features/workspace/installed.js +92 -0
  117. package/dist/features/{git-workspace → workspace}/overlay.js +53 -46
  118. package/dist/features/workspace/packages.js +173 -0
  119. package/dist/features/{git-workspace → workspace}/publish.js +120 -64
  120. package/dist/features/workspace/repo-source.js +193 -0
  121. package/dist/features/{git-workspace → workspace}/setup.js +72 -45
  122. package/dist/features/{git-workspace → workspace}/snapshot.js +60 -19
  123. package/dist/features/workspace/source.js +1 -0
  124. package/dist/features/workspace/tree.js +52 -0
  125. package/dist/features/workspace/workspace-source.js +27 -0
  126. package/dist/harnesses/claude.js +23 -1
  127. package/dist/harnesses/codex.js +67 -1
  128. package/dist/harnesses/cursor.js +22 -1
  129. package/dist/harnesses/detect.js +6 -50
  130. package/dist/harnesses/formats.js +52 -0
  131. package/dist/harnesses/opencode.js +108 -0
  132. package/dist/harnesses/registry.js +35 -2
  133. package/dist/platform.js +403 -0
  134. package/dist/program.js +275 -56
  135. package/dist/runtime.js +1 -0
  136. package/dist/shared/cli-error.js +22 -0
  137. package/dist/shared/constants.js +32 -0
  138. package/dist/shared/files.js +107 -0
  139. package/dist/shared/lock.js +113 -0
  140. package/dist/shared/lookup.js +11 -0
  141. package/dist/shared/patterns.js +102 -0
  142. package/dist/shared/shell.js +20 -0
  143. package/dist/shared/values.js +26 -0
  144. package/dist/ui/add-asset.js +41 -400
  145. package/dist/ui/add-hook.js +219 -0
  146. package/dist/ui/add-mcp.js +170 -0
  147. package/dist/ui/add-prompts.js +47 -0
  148. package/dist/ui/add-skills.js +117 -0
  149. package/dist/ui/adopt.js +197 -0
  150. package/dist/ui/asset-list.js +31 -13
  151. package/dist/ui/assets.js +38 -47
  152. package/dist/ui/auth.js +45 -34
  153. package/dist/ui/clash.js +10 -6
  154. package/dist/ui/collaboration.js +116 -44
  155. package/dist/ui/connection.js +17 -6
  156. package/dist/ui/decision-error.js +24 -0
  157. package/dist/ui/environment-onboarding.js +35 -13
  158. package/dist/ui/format.js +66 -18
  159. package/dist/ui/harness-picker.js +18 -0
  160. package/dist/ui/hook-compatibility.js +14 -6
  161. package/dist/ui/mcp.js +28 -3
  162. package/dist/ui/move.js +57 -6
  163. package/dist/ui/onboarding.js +148 -95
  164. package/dist/ui/options.js +9 -0
  165. package/dist/ui/output.js +108 -43
  166. package/dist/ui/package-details.js +34 -0
  167. package/dist/ui/pick.js +45 -33
  168. package/dist/ui/scope-install.js +18 -7
  169. package/dist/ui/secret-input.js +19 -0
  170. package/dist/ui/selection.js +17 -11
  171. package/dist/ui/theme.js +37 -14
  172. package/dist/version.js +6 -3
  173. package/package.json +13 -3
  174. package/dist/features/capabilities/index.js +0 -106
  175. package/dist/features/collaboration/domain.js +0 -90
  176. package/dist/features/environment/cloud-source.js +0 -27
  177. package/dist/features/environment/installed.js +0 -124
  178. package/dist/features/environment/packages.js +0 -120
  179. package/dist/features/environment/remote.js +0 -71
  180. package/dist/features/environment/workspace-source.js +0 -19
  181. package/dist/features/git-hosts/index.js +0 -148
  182. package/dist/features/git-workspace/assets.js +0 -71
  183. package/dist/features/git-workspace/git.js +0 -135
  184. package/dist/features/git-workspace/migrate.js +0 -188
  185. package/dist/features/git-workspace/move.js +0 -337
  186. package/dist/features/git-workspace/source.js +0 -159
  187. package/dist/features/imports/mcp.js +0 -219
  188. package/dist/features/knowledge/startup.js +0 -25
  189. package/dist/features/native/mcp-launch.js +0 -57
  190. package/dist/features/skills/install.js +0 -25
  191. package/dist/features/skills/remote.js +0 -177
  192. package/dist/features/skills/sync.js +0 -121
  193. package/dist/features/skills/validation.js +0 -34
  194. /package/dist/features/environment/{source.js → events.js} +0 -0
@@ -1,61 +1,17 @@
1
- import { access, stat } from "node:fs/promises";
2
- import { constants } from "node:fs";
3
- import { homedir } from "node:os";
4
- import { delimiter, join } from "node:path";
5
1
  import { harnesses, adapters } from "./registry.js";
6
- async function exists(path, directory = false) {
7
- try {
8
- const info = await stat(path);
9
- if (directory)
10
- return info.isDirectory();
11
- await access(path, constants.X_OK);
12
- return info.isFile();
13
- }
14
- catch (error) {
15
- if (["ENOENT", "ENOTDIR", "EACCES"].includes(error.code ?? ""))
16
- return false;
17
- throw error;
18
- }
19
- }
2
+ import { findExecutable, installedApplication } from "../platform.js";
20
3
  /** Inspect installation evidence; never execute harnesses or infer installation from skill directories. */
21
- export async function detectHarnesses(options = {}) {
22
- const home = options.home ?? homedir();
23
- const platform = options.platform ?? process.platform;
24
- const directories = (options.path ?? process.env.PATH ?? "")
25
- .split(delimiter)
26
- .filter(Boolean);
27
- const appDirectories = options.appDirectories ?? [
28
- "/Applications",
29
- join(home, "Applications"),
30
- ];
31
- const extensions = platform === "win32" ? ["", ".exe", ".cmd", ".bat"] : [""];
4
+ export async function detectHarnesses(runtime, options = {}) {
32
5
  return Promise.all(harnesses.map(async (id) => {
33
6
  const installation = adapters[id];
34
7
  let evidence = null;
35
- for (const directory of directories) {
36
- for (const command of installation.commands) {
37
- for (const extension of extensions) {
38
- const candidate = join(directory, `${command}${extension}`);
39
- if (await exists(candidate)) {
40
- evidence = candidate;
41
- break;
42
- }
43
- }
44
- if (evidence)
45
- break;
46
- }
47
- if (evidence)
8
+ for (const command of installation.commands) {
9
+ evidence = await findExecutable(command, runtime);
10
+ if (evidence) {
48
11
  break;
49
- }
50
- if (!evidence && platform === "darwin") {
51
- for (const directory of appDirectories) {
52
- const candidate = join(directory, installation.macApp);
53
- if (await exists(join(candidate, "Contents", "MacOS"), true)) {
54
- evidence = candidate;
55
- break;
56
- }
57
12
  }
58
13
  }
14
+ evidence ??= await installedApplication(installation.desktopApp, runtime, options.appDirectories);
59
15
  return { id, name: installation.name, evidence };
60
16
  }));
61
17
  }
@@ -0,0 +1,52 @@
1
+ /** The secret references of a definition: environment for stdio, headers for HTTP. */
2
+ export const secretRefs = (definition) => definition.transport === "stdio"
3
+ ? definition.environment
4
+ : definition.headers;
5
+ /**
6
+ * Each environment variable or header of a definition: the kept value when
7
+ * BarnDog keeps one, else the tool's reference to the local variable.
8
+ */
9
+ export function valuesOrReferences(definition, kept, reference) {
10
+ return Object.fromEntries(Object.entries(secretRefs(definition)).map(([name, ref]) => [
11
+ name,
12
+ kept[ref.secretRef] ?? reference(ref.secretRef),
13
+ ]));
14
+ }
15
+ /**
16
+ * A server entry for a tool that keeps `mcpServers` in JSON, as Claude Code and
17
+ * Cursor do. They differ in how a value refers to a local environment variable
18
+ * and in whether an entry must name its transport in `type`.
19
+ */
20
+ export function jsonMcpServer(definition, format, kept) {
21
+ const references = valuesOrReferences(definition, kept, format.reference);
22
+ const type = format.typed ? { type: definition.transport } : {};
23
+ const some = Object.keys(references).length > 0;
24
+ if (definition.transport === "http") {
25
+ return {
26
+ ...type,
27
+ url: definition.url,
28
+ ...(some ? { headers: references } : {}),
29
+ };
30
+ }
31
+ return {
32
+ ...type,
33
+ command: definition.command,
34
+ args: definition.args,
35
+ ...(some ? { env: references } : {}),
36
+ };
37
+ }
38
+ /**
39
+ * A command handler nested under a matcher group, the shape Claude Code and
40
+ * Codex share: `{ matcher, hooks: [{ type: "command", command }] }`.
41
+ */
42
+ export const nestedHookEntry = (command, matcher) => ({
43
+ ...(matcher ? { matcher } : {}),
44
+ hooks: [{ type: "command", command }],
45
+ });
46
+ /** The session-start output Claude Code and Codex read added context from. */
47
+ export const hookSpecificContext = (text) => ({
48
+ hookSpecificOutput: {
49
+ hookEventName: "SessionStart",
50
+ additionalContext: text,
51
+ },
52
+ });
@@ -0,0 +1,108 @@
1
+ import { VARIABLE_NAME } from "../shared/patterns.js";
2
+ import { asRecord, asStrings } from "../shared/values.js";
3
+ import { valuesOrReferences } from "./formats.js";
4
+ /**
5
+ * OpenCode's server entry (`mcp.servers.<name>` in opencode.jsonc): a stdio
6
+ * server is `local` with the program and its arguments in one `command` list,
7
+ * an HTTP server is `remote`. Values refer to a local variable as `{env:NAME}`.
8
+ */
9
+ function mcpServer(definition, _launcher, kept) {
10
+ const references = valuesOrReferences(definition, kept, (variable) => `{env:${variable}}`);
11
+ const some = Object.keys(references).length > 0;
12
+ if (definition.transport === "http") {
13
+ return {
14
+ type: "remote",
15
+ url: definition.url,
16
+ ...(some ? { headers: references } : {}),
17
+ };
18
+ }
19
+ return {
20
+ type: "local",
21
+ command: [definition.command, ...definition.args],
22
+ ...(some ? { environment: references } : {}),
23
+ };
24
+ }
25
+ /** OpenCode's reference to a local variable inside a value: `Bearer {env:TOKEN}`. */
26
+ const OPENCODE_REFERENCE = new RegExp(String.raw `\{env:(${VARIABLE_NAME.source})\}`, "g");
27
+ /**
28
+ * A value with OpenCode's `{env:NAME}` references spelled `${NAME}`, as
29
+ * Claude Code writes them: `Bearer {env:TOKEN}` → `Bearer ${TOKEN}`.
30
+ *
31
+ * @internal Exported for its table test in `src/tests/patterns.test.ts`.
32
+ */
33
+ export const bracedReferences = (value) => value.replaceAll(OPENCODE_REFERENCE, (_, name) => `\${${name}}`);
34
+ /** Every string value of a map, with its references respelled. */
35
+ const respelled = (values) => Object.fromEntries(Object.entries(asRecord(values)).map(([key, value]) => [
36
+ key,
37
+ typeof value === "string" ? bracedReferences(value) : value,
38
+ ]));
39
+ /**
40
+ * An OpenCode entry in Claude Code's shape. A remote server with an `oauth`
41
+ * object signs in; `oauth: false` or none leaves that to its headers.
42
+ */
43
+ function importedServer(entry) {
44
+ if (entry.type === "remote") {
45
+ return {
46
+ url: entry.url,
47
+ headers: respelled(entry.headers),
48
+ ...(entry.oauth ? { oauth: true } : {}),
49
+ };
50
+ }
51
+ const [command, ...args] = asStrings(entry.command);
52
+ return { command, args, env: respelled(entry.environment) };
53
+ }
54
+ /**
55
+ * OpenCode keeps its user settings in `~/.config/opencode` on every platform
56
+ * (or under `XDG_CONFIG_HOME`). It has no command hooks: BarnDog's
57
+ * session-start work runs from a plugin module OpenCode loads from
58
+ * `plugins/`, and Hook assets don't apply to it.
59
+ */
60
+ export const opencode = {
61
+ id: "opencode",
62
+ name: "OpenCode",
63
+ skillRoot: ".config/opencode/skills",
64
+ commands: ["opencode"],
65
+ // OpenCode Desktop's electron-builder build: OpenCode.app; a per-user NSIS
66
+ // install, whose folder is the package name `@opencode-ai/desktop` with the
67
+ // slash dropped; and deb/rpm packages whose entry is named after the app ID.
68
+ desktopApp: {
69
+ name: "OpenCode",
70
+ windowsFolder: "@opencode-aidesktop",
71
+ linuxEntry: "ai.opencode.desktop",
72
+ },
73
+ plugin: {
74
+ file: ".config/opencode/plugins/barndog.js",
75
+ entryScript: "opencode-plugin",
76
+ // OpenCode's plugin loader takes a default export of `{ id, server }`.
77
+ module: (entry, options) => [
78
+ "// Written by barndog sync, which rewrites or removes it. Sync stops if this file is edited by hand.",
79
+ `import { barndog } from ${JSON.stringify(entry)};`,
80
+ "",
81
+ `export default { id: "barndog", server: barndog(${JSON.stringify(options)}) };`,
82
+ "",
83
+ ].join("\n"),
84
+ },
85
+ mcp: {
86
+ // The file OpenCode creates on first run and reads last, so it wins.
87
+ file: ".config/opencode/opencode.jsonc",
88
+ // Known limitation: BarnDog supports only the latest OpenCode, so it reads
89
+ // and writes `mcp.servers` alone. OpenCode still accepts a server written
90
+ // straight under `mcp` (the older shape), and BarnDog neither imports those
91
+ // nor notices one with the same name as a server it installs.
92
+ path: ["mcp", "servers"],
93
+ // OpenCode merges these in this order, a later file winning.
94
+ files: [
95
+ ".config/opencode/config.json",
96
+ ".config/opencode/opencode.json",
97
+ ".config/opencode/opencode.jsonc",
98
+ ],
99
+ server: mcpServer,
100
+ imported: importedServer,
101
+ login: { command: ["opencode", "mcp", "auth"] },
102
+ },
103
+ configHome: {
104
+ variable: "XDG_CONFIG_HOME",
105
+ directory: ".config",
106
+ defaultIsSupported: true,
107
+ },
108
+ };
@@ -1,16 +1,49 @@
1
- import { resolve } from "node:path";
2
1
  import { claude } from "./claude.js";
3
2
  import { codex } from "./codex.js";
4
3
  import { cursor } from "./cursor.js";
5
- export const harnesses = ["claude", "codex", "cursor"];
4
+ import { opencode } from "./opencode.js";
5
+ import { join, resolve } from "node:path";
6
+ export const harnesses = ["claude", "codex", "cursor", "opencode"];
7
+ /** The tools with command hooks, in the order `harnesses` lists them. */
8
+ export const hookHarnesses = ["claude", "codex", "cursor"];
6
9
  export const adapters = {
7
10
  claude,
8
11
  codex,
9
12
  cursor,
13
+ opencode,
10
14
  };
11
15
  export function isHarness(value) {
12
16
  return (typeof value === "string" && harnesses.some((harness) => harness === value));
13
17
  }
18
+ export function isHookHarness(value) {
19
+ return (typeof value === "string" &&
20
+ hookHarnesses.some((harness) => harness === value));
21
+ }
22
+ /**
23
+ * The harness whose hook settings live at a repository path, such as
24
+ * `.claude/settings.json` (Claude Code) or `.codex/config.toml` (Codex);
25
+ * undefined for any other file.
26
+ */
27
+ export function hookSettingsOwner(path) {
28
+ return hookHarnesses.find((harness) => adapters[harness].hooks.settings.some((pattern) => pattern.test(path)));
29
+ }
14
30
  export function skillDirectory(harness, home) {
15
31
  return resolve(home, adapters[harness].skillRoot);
16
32
  }
33
+ /**
34
+ * What BarnDog writes into a coding tool's own settings files: MCP servers,
35
+ * Hooks, the knowledge index and the sync reminder.
36
+ */
37
+ export const nativeKinds = ["mcp", "hook", "knowledge", "sync"];
38
+ /**
39
+ * Resolves the native settings file under the supplied home. MCP entries go to
40
+ * the tool's MCP file; the rest to its hook settings, or for a tool without
41
+ * command hooks, to BarnDog's plugin module.
42
+ */
43
+ export function nativeFile(harness, kind, home) {
44
+ const adapter = adapters[harness];
45
+ if (kind === "mcp") {
46
+ return join(home, adapter.mcp.file);
47
+ }
48
+ return join(home, adapter.hooks ? adapter.hooks.file : adapter.plugin.file);
49
+ }
@@ -0,0 +1,403 @@
1
+ import { access, readFile, stat } from "node:fs/promises";
2
+ import { constants } from "node:fs";
3
+ import { posix, win32 } from "node:path";
4
+ import { execFile, spawn } from "node:child_process";
5
+ import crossSpawn from "cross-spawn";
6
+ import { promisify } from "node:util";
7
+ import { CliError } from "./errors.js";
8
+ import { POSIX_MODE } from "./shared/constants.js";
9
+ import { ifExists, isInside } from "./shared/files.js";
10
+ import { PLAIN_WORD, posixQuote, powershellQuote } from "./shared/shell.js";
11
+ import { errorCode } from "./shared/values.js";
12
+ const execute = promisify(execFile);
13
+ /**
14
+ * Environment variables the operating system defines, read through
15
+ * `environmentValue()` (Windows names are case-insensitive).
16
+ */
17
+ const OS_VARIABLES = {
18
+ path: "PATH",
19
+ /** Windows: extensions PATH lookup tries, such as `.EXE;.CMD`. */
20
+ pathExtensions: "PATHEXT",
21
+ /** Windows: `C:\Program Files` and its 32-bit twin. */
22
+ programFiles: "ProgramFiles",
23
+ programFilesX86: "ProgramFiles(x86)",
24
+ /** Windows: `C:\Windows`, which holds WSL's `bash.exe` launcher. */
25
+ systemRoot: "SystemRoot",
26
+ /** Windows: `C:\Users\<you>\AppData\Local`, where per-user apps install. */
27
+ localAppData: "LOCALAPPDATA",
28
+ /** Linux: XDG Base Directory specification. */
29
+ dataHome: "XDG_DATA_HOME",
30
+ dataDirectories: "XDG_DATA_DIRS",
31
+ };
32
+ /** cmd.exe's own PATHEXT when the variable is unset. */
33
+ const DEFAULT_PATH_EXTENSIONS = ".COM;.EXE;.BAT;.CMD";
34
+ /** XDG Base Directory specification default for `XDG_DATA_DIRS`. */
35
+ const DEFAULT_DATA_DIRECTORIES = "/usr/local/share:/usr/share";
36
+ /** Error codes meaning "not there" while probing a path that may not exist. */
37
+ const ABSENT = ["ENOENT", "ENOTDIR", "EACCES"];
38
+ export const isWindows = (platform) => platform === "win32";
39
+ export const pathsFor = (platform) => isWindows(platform) ? win32 : posix;
40
+ export const directoryLinkType = (platform) => isWindows(platform) ? "junction" : "dir";
41
+ /** Windows environment variable names are case insensitive. */
42
+ export function environmentValue(runtime, name) {
43
+ const key = isWindows(runtime.platform)
44
+ ? Object.keys(runtime.env).find((key) => key.toLowerCase() === name.toLowerCase())
45
+ : name;
46
+ return key ? runtime.env[key] : undefined;
47
+ }
48
+ function executableNames(command, extensions, windows) {
49
+ if (windows && !win32.extname(command)) {
50
+ return extensions.map((extension) => command + extension.toLowerCase());
51
+ }
52
+ return [command];
53
+ }
54
+ /** Searches only the supplied PATH; tests can exercise Windows PATHEXT on any host. */
55
+ export async function findExecutable(command, runtime) {
56
+ const paths = pathsFor(runtime.platform);
57
+ const windows = isWindows(runtime.platform);
58
+ const extensions = windows
59
+ ? (environmentValue(runtime, OS_VARIABLES.pathExtensions) ??
60
+ DEFAULT_PATH_EXTENSIONS).split(";")
61
+ : [""];
62
+ const names = executableNames(command, extensions, windows);
63
+ const locations = command.includes("/") || command.includes("\\")
64
+ ? [""]
65
+ : (environmentValue(runtime, OS_VARIABLES.path) ?? "")
66
+ .split(windows ? ";" : ":")
67
+ .filter(Boolean);
68
+ for (const directory of locations) {
69
+ for (const name of names) {
70
+ const candidate = paths.resolve(runtime.cwd, directory.replaceAll('"', ""), name);
71
+ try {
72
+ if (!(await stat(candidate)).isFile()) {
73
+ continue;
74
+ }
75
+ await access(candidate, windows ? constants.F_OK : constants.X_OK);
76
+ return candidate;
77
+ }
78
+ catch (error) {
79
+ if (!ABSENT.includes(errorCode(error) ?? "")) {
80
+ throw error;
81
+ }
82
+ }
83
+ }
84
+ }
85
+ return null;
86
+ }
87
+ /** Quotes for the shell people type fix hints into: PowerShell on Windows. */
88
+ const shellQuote = (value, platform) => isWindows(platform) ? powershellQuote(value) : posixQuote(value);
89
+ /**
90
+ * Fix hints name commands for the shell people type into: Bash or zsh on
91
+ * macOS and Linux, PowerShell on Windows. Each step runs only when the one
92
+ * before it succeeded; Windows PowerShell 5 has no `&&`, so there each later
93
+ * step goes inside `if ($?) { … }`.
94
+ */
95
+ export function fixSteps(steps, platform) {
96
+ if (!isWindows(platform)) {
97
+ return steps.join(" && ");
98
+ }
99
+ return steps.reduceRight((rest, step) => (rest ? `${step}; if ($?) { ${rest} }` : step), "");
100
+ }
101
+ export function removeCommand(path, platform) {
102
+ return isWindows(platform)
103
+ ? `Remove-Item -Recurse -Force ${shellQuote(path, platform)}`
104
+ : `rm -rf ${shellQuote(path, platform)}`;
105
+ }
106
+ /** One word for the platform's shell, quoted only when it needs to be. */
107
+ export function shellWord(value, platform) {
108
+ return PLAIN_WORD.test(value) ? value : shellQuote(value, platform);
109
+ }
110
+ /** Checks that the user's Git credentials can read `url`; clones nothing. */
111
+ export function gitAccessCommand(url, platform) {
112
+ return `git ls-remote ${shellQuote(url, platform)}`;
113
+ }
114
+ export function unsetCommand(variable, platform) {
115
+ return isWindows(platform)
116
+ ? `Remove-Item Env:${variable}`
117
+ : `unset ${variable}`;
118
+ }
119
+ /**
120
+ * Windows PowerShell running `script`, passed encoded so no character in it
121
+ * needs quoting as a program argument.
122
+ */
123
+ export function encodedPowerShell(script) {
124
+ return {
125
+ command: "powershell.exe",
126
+ args: [
127
+ "-NoLogo",
128
+ "-NoProfile",
129
+ "-NonInteractive",
130
+ "-EncodedCommand",
131
+ // -EncodedCommand takes Base64 of UTF-16LE text.
132
+ Buffer.from("[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new($false); $OutputEncoding=[Console]::OutputEncoding; " +
133
+ script, "utf16le").toString("base64"),
134
+ ],
135
+ };
136
+ }
137
+ /**
138
+ * A program run from a PowerShell line, keeping its exit code. A program that
139
+ * can't be found sets no `$LASTEXITCODE`, and `exit $null` would report
140
+ * success, so that case exits 1.
141
+ */
142
+ export const powershellCall = (args) => `& ${args.map(powershellQuote).join(" ")}; if ($null -eq $LASTEXITCODE) { exit 1 }; exit $LASTEXITCODE`;
143
+ /**
144
+ * A program's stdout. Starts through cross-spawn, which also runs Windows
145
+ * `.cmd` and `.bat` shims (such as npm-installed tools) with safely quoted
146
+ * arguments. Fails when the program exits non-zero, runs past `timeoutMs` or
147
+ * prints more than `maxBytes`.
148
+ */
149
+ export function programOutput(command, args, runtime, limits) {
150
+ return new Promise((resolve, reject) => {
151
+ const child = crossSpawn(command, [...args], {
152
+ env: { ...runtime.env },
153
+ cwd: runtime.cwd,
154
+ stdio: ["ignore", "pipe", "ignore"],
155
+ windowsHide: true,
156
+ });
157
+ // Decoded once at the end, so a character split across chunks survives.
158
+ const chunks = [];
159
+ let length = 0;
160
+ const fail = (reason) => {
161
+ child.kill();
162
+ reject(new Error(`${command} ${reason}`));
163
+ };
164
+ const timer = setTimeout(() => fail("timed out"), limits.timeoutMs);
165
+ child.stdout?.on("data", (chunk) => {
166
+ length += chunk.length;
167
+ if (length > limits.maxBytes) {
168
+ fail("printed too much");
169
+ }
170
+ else {
171
+ chunks.push(chunk);
172
+ }
173
+ });
174
+ child.once("error", (error) => {
175
+ clearTimeout(timer);
176
+ reject(error);
177
+ });
178
+ child.once("close", (code) => {
179
+ clearTimeout(timer);
180
+ if (code === 0) {
181
+ resolve(Buffer.concat(chunks).toString("utf8"));
182
+ }
183
+ else {
184
+ reject(new Error(`${command} exited with code ${code}`));
185
+ }
186
+ });
187
+ });
188
+ }
189
+ /**
190
+ * Bash for a tool that runs hook commands in it: `/bin/sh` on macOS and
191
+ * Linux, Git for Windows' Bash on Windows (where Claude Code finds it too).
192
+ */
193
+ export async function bashShell(runtime) {
194
+ if (!isWindows(runtime.platform)) {
195
+ return { command: "/bin/sh", args: ["-c"] };
196
+ }
197
+ const paths = pathsFor(runtime.platform);
198
+ for (const root of [
199
+ environmentValue(runtime, OS_VARIABLES.programFiles),
200
+ environmentValue(runtime, OS_VARIABLES.programFilesX86),
201
+ ]) {
202
+ // Git for Windows' default install folder.
203
+ const candidate = root && paths.join(root, "Git", "bin", "bash.exe");
204
+ if (candidate && (await ifExists(stat(candidate)))?.isFile()) {
205
+ return { command: candidate, args: ["-c"] };
206
+ }
207
+ }
208
+ // `C:\Windows\System32\bash.exe` starts WSL's Linux, not the Bash tools run
209
+ // hooks in, so a Bash found there doesn't count.
210
+ const bash = await findExecutable("bash", runtime);
211
+ const system = environmentValue(runtime, OS_VARIABLES.systemRoot);
212
+ if (bash &&
213
+ !(system && isInside(system.toLowerCase(), bash.toLowerCase(), paths))) {
214
+ return { command: bash, args: ["-c"] };
215
+ }
216
+ throw new CliError("This Hook runs in Bash, which isn't installed.", "Install Git for Windows from https://gitforwindows.org, then try again.");
217
+ }
218
+ /** POSIX Hook runtime declarations also recognize the Bash supplied by Git for Windows. */
219
+ export async function runtimeExecutable(command, runtime) {
220
+ const executable = await findExecutable(command, runtime);
221
+ if (executable ||
222
+ !isWindows(runtime.platform) ||
223
+ !["sh", "bash"].includes(command)) {
224
+ return executable;
225
+ }
226
+ try {
227
+ return (await bashShell(runtime)).command;
228
+ }
229
+ catch (error) {
230
+ if (error instanceof CliError) {
231
+ return null;
232
+ }
233
+ throw error;
234
+ }
235
+ }
236
+ /** Kill the whole Hook/MCP process tree, including grandchildren on Windows. */
237
+ export function stopProcessTree(child, runtime, signal = "SIGKILL") {
238
+ if (!child.pid) {
239
+ return;
240
+ }
241
+ try {
242
+ if (isWindows(runtime.platform)) {
243
+ const killer = spawn("taskkill.exe",
244
+ // /T ends the process's children too, /F forces it.
245
+ ["/pid", String(child.pid), "/T", "/F"], {
246
+ stdio: "ignore",
247
+ windowsHide: true,
248
+ env: { ...runtime.env },
249
+ cwd: runtime.cwd,
250
+ });
251
+ killer.on("error", () => child.kill(signal));
252
+ }
253
+ else {
254
+ process.kill(-child.pid, signal);
255
+ }
256
+ }
257
+ catch {
258
+ /* The child has already exited. */
259
+ }
260
+ }
261
+ /** Windows DACLs replace POSIX modes: only the current user receives access. */
262
+ export async function protectPrivate(path, runtime) {
263
+ if (!isWindows(runtime.platform)) {
264
+ return;
265
+ }
266
+ const script = `$ErrorActionPreference='Stop'; $path=${shellQuote(path, runtime.platform)}; $sid=[Security.Principal.WindowsIdentity]::GetCurrent().User; $acl=Get-Acl -LiteralPath $path; $acl.SetOwner($sid); $acl.SetAccessRuleProtection($true,$false); foreach($rule in @($acl.Access)){$acl.RemoveAccessRuleSpecific($rule)}; $inherit=if((Get-Item -LiteralPath $path).PSIsContainer){[Security.AccessControl.InheritanceFlags]'ContainerInherit,ObjectInherit'}else{[Security.AccessControl.InheritanceFlags]::None}; $rule=New-Object Security.AccessControl.FileSystemAccessRule($sid,'FullControl',$inherit,'None','Allow'); $acl.AddAccessRule($rule); Set-Acl -LiteralPath $path -AclObject $acl`;
267
+ const invocation = encodedPowerShell(script);
268
+ await execute(invocation.command, invocation.args, {
269
+ env: { ...runtime.env },
270
+ cwd: runtime.cwd,
271
+ windowsHide: true,
272
+ });
273
+ }
274
+ /**
275
+ * Whether a file's POSIX mode keeps it private. On Windows the ACL that
276
+ * `protectPrivate()` sets on every write does that, and checking it would start
277
+ * PowerShell on every command, so any mode passes.
278
+ */
279
+ export function privatePermissions(mode, platform) {
280
+ return isWindows(platform) || !(mode & POSIX_MODE.groupAndOtherBits);
281
+ }
282
+ /**
283
+ * Where a desktop app would be installed, as `[path to check, evidence to report]`:
284
+ * a macOS bundle counts only when it has a `Contents/MacOS` folder.
285
+ */
286
+ function applicationCandidates(app, runtime, macRoots) {
287
+ const path = pathsFor(runtime.platform);
288
+ if (runtime.platform === "darwin") {
289
+ return macRoots.map((root) => {
290
+ const bundle = path.join(root, `${app.name}.app`);
291
+ return [path.join(bundle, "Contents", "MacOS"), bundle];
292
+ });
293
+ }
294
+ if (isWindows(runtime.platform)) {
295
+ const local = environmentValue(runtime, OS_VARIABLES.localAppData);
296
+ const programFiles = environmentValue(runtime, OS_VARIABLES.programFiles);
297
+ const executable = `${app.name}.exe`;
298
+ const folder = app.windowsFolder ?? app.name;
299
+ const paths = [
300
+ ...(local
301
+ ? [
302
+ path.join(local, "Programs", folder, executable),
303
+ path.join(local, folder, executable),
304
+ ]
305
+ : []),
306
+ ...(programFiles ? [path.join(programFiles, folder, executable)] : []),
307
+ ];
308
+ return paths.map((candidate) => [candidate, candidate]);
309
+ }
310
+ const dataHome = environmentValue(runtime, OS_VARIABLES.dataHome) ??
311
+ path.join(runtime.home, ".local", "share");
312
+ const dataDirectories = environmentValue(runtime, OS_VARIABLES.dataDirectories) ??
313
+ DEFAULT_DATA_DIRECTORIES;
314
+ return [dataHome, ...dataDirectories.split(":")].map((root) => {
315
+ const entry = path.join(root, "applications", `${app.linuxEntry ?? app.name.toLowerCase()}.desktop`);
316
+ return [entry, entry];
317
+ });
318
+ }
319
+ /**
320
+ * The installed desktop app, or null. `macRoots` replaces `/Applications` and
321
+ * `~/Applications`, so tests don't see apps installed on the machine.
322
+ */
323
+ export async function installedApplication(app, runtime, macRoots = [
324
+ "/Applications",
325
+ pathsFor(runtime.platform).join(runtime.home, "Applications"),
326
+ ]) {
327
+ for (const [probe, evidence] of applicationCandidates(app, runtime, macRoots)) {
328
+ try {
329
+ await stat(probe);
330
+ return evidence;
331
+ }
332
+ catch (error) {
333
+ if (!ABSENT.includes(errorCode(error) ?? "")) {
334
+ throw error;
335
+ }
336
+ }
337
+ }
338
+ return null;
339
+ }
340
+ /** The `#!` that starts a script the kernel can run directly. */
341
+ const SHEBANG = "#!";
342
+ /**
343
+ * Whether a file is executable. Windows files have no executable bit, so
344
+ * there the flag comes from `known` (what BarnDog last wrote at that path),
345
+ * else from a `#!` first line, as Git for Windows guesses for a new script.
346
+ */
347
+ export async function fileExecutable(path, mode, runtime, known) {
348
+ if (!isWindows(runtime.platform)) {
349
+ return !!(mode & POSIX_MODE.executableBits);
350
+ }
351
+ return (known ??
352
+ (await readFile(path)).subarray(0, SHEBANG.length).toString() === SHEBANG);
353
+ }
354
+ /**
355
+ * DOS device names are reserved even with an extension: `CON`, `con.txt`,
356
+ * `LPT1.log`, but not `console` or `com10`.
357
+ *
358
+ * @internal
359
+ */
360
+ export const WINDOWS_DEVICE_NAME = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i;
361
+ /** A package path can be valid on macOS and Linux yet impossible to store on Windows. */
362
+ export function assertPackagePaths(entries, platform) {
363
+ if (!isWindows(platform)) {
364
+ return;
365
+ }
366
+ const names = new Set(entries.map((entry) => entry.path.toLowerCase()));
367
+ if (names.size !== entries.length) {
368
+ throw new CliError("The package has paths that differ only in case, so it can't be stored on Windows.", "Ask its author to rename one of them.");
369
+ }
370
+ for (const { path } of entries) {
371
+ const parts = path.split("/");
372
+ for (const part of parts) {
373
+ if (invalidWindowsPart(part)) {
374
+ throw new CliError(`The package file ${path} has a name Windows can't store.`, "Ask its author to rename it.");
375
+ }
376
+ }
377
+ for (let depth = 1; depth < parts.length; depth++) {
378
+ if (names.has(parts.slice(0, depth).join("/").toLowerCase())) {
379
+ throw new CliError(`The package file ${path} is inside a folder that differs only in case from a file, so it can't be stored on Windows.`, "Ask its author to rename one of them.");
380
+ }
381
+ }
382
+ }
383
+ }
384
+ function invalidWindowsPart(part) {
385
+ return (!part ||
386
+ part === "." ||
387
+ part === ".." ||
388
+ WINDOWS_DEVICE_NAME.test(part) ||
389
+ [...'<>:"\\|?*'].some((char) => part.includes(char)) ||
390
+ part.endsWith(".") ||
391
+ part.endsWith(" ") ||
392
+ [...part].some((char) => char.charCodeAt(0) < " ".charCodeAt(0)));
393
+ }
394
+ /** Resolve CLI input against the captured cwd; a drive-relative path must not consult Windows' hidden per-drive cwd. */
395
+ export function localPath(value, runtime) {
396
+ const paths = pathsFor(runtime.platform);
397
+ if (isWindows(runtime.platform) &&
398
+ value[1] === ":" &&
399
+ !paths.isAbsolute(value)) {
400
+ throw new CliError(`${value} is relative to the current folder of drive ${value.slice(0, 2)}, which BarnDog can't see.`, `Use an absolute path such as ${value.slice(0, 2)}\\${value.slice(2)}.`);
401
+ }
402
+ return paths.resolve(runtime.cwd, value);
403
+ }