barndog 0.2.1 → 0.2.2

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 (53) hide show
  1. package/README.md +19 -0
  2. package/dist/cli.js +27 -1
  3. package/dist/commands/asset-list.js +5 -1
  4. package/dist/commands/harnesses.js +32 -2
  5. package/dist/commands/mcp-env.js +130 -41
  6. package/dist/commands/sets.js +13 -2
  7. package/dist/commands/uninstall.js +62 -0
  8. package/dist/config/paths.js +2 -0
  9. package/dist/entry/update-check.js +15 -0
  10. package/dist/features/adoption/adopt.js +31 -30
  11. package/dist/features/auth/session.js +22 -0
  12. package/dist/features/collaboration/workspace-store.js +2 -1
  13. package/dist/features/doctor/index.js +25 -8
  14. package/dist/features/environment/events.js +8 -1
  15. package/dist/features/environment/kept-values.js +68 -0
  16. package/dist/features/environment/moves.js +17 -1
  17. package/dist/features/environment/stage.js +20 -20
  18. package/dist/features/environment/sync.js +2 -2
  19. package/dist/features/inventory/index.js +45 -2
  20. package/dist/features/mcps/import.js +36 -15
  21. package/dist/features/mcps/index.js +12 -2
  22. package/dist/features/mcps/values.js +108 -20
  23. package/dist/features/migration/migrate.js +15 -0
  24. package/dist/features/migration/move.js +34 -9
  25. package/dist/features/native/adapters.js +1 -2
  26. package/dist/features/native/hook-shell.js +11 -0
  27. package/dist/features/secrets/index.js +94 -29
  28. package/dist/features/uninstall/index.js +126 -0
  29. package/dist/features/uninstall/leave.js +152 -0
  30. package/dist/features/uninstall/survey.js +103 -0
  31. package/dist/features/update-check/index.js +108 -0
  32. package/dist/features/workspace/format.js +6 -1
  33. package/dist/harnesses/claude.js +1 -1
  34. package/dist/harnesses/codex.js +46 -22
  35. package/dist/harnesses/cursor.js +1 -1
  36. package/dist/harnesses/opencode.js +1 -1
  37. package/dist/harnesses/read-renamed-variables.js +141 -0
  38. package/dist/harnesses/renamed-variables.js +99 -0
  39. package/dist/platform.js +12 -1
  40. package/dist/program.js +21 -9
  41. package/dist/ui/add-mcp.js +22 -16
  42. package/dist/ui/adopt.js +11 -6
  43. package/dist/ui/connection.js +2 -0
  44. package/dist/ui/harness-picker.js +7 -2
  45. package/dist/ui/mcp.js +89 -23
  46. package/dist/ui/move.js +2 -1
  47. package/dist/ui/output.js +33 -8
  48. package/dist/ui/secret-input.js +9 -0
  49. package/dist/ui/uninstall.js +174 -0
  50. package/dist/ui/update.js +10 -0
  51. package/dist/version.js +2 -2
  52. package/package.json +1 -1
  53. package/dist/entry/mcp-launch.js +0 -71
@@ -0,0 +1,103 @@
1
+ /** What `barndog uninstall` would find to remove or leave on this machine. */
2
+ import { lstat } from "node:fs/promises";
3
+ import { basename } from "node:path";
4
+ import { barndogPaths } from "../../config/paths.js";
5
+ import { readSettings } from "../../config/settings.js";
6
+ import { readState } from "../../config/state.js";
7
+ import { CliError } from "../../errors.js";
8
+ import { secretRefs } from "../../harnesses/formats.js";
9
+ import { adapters } from "../../harnesses/registry.js";
10
+ import { ifExists, isInside } from "../../shared/files.js";
11
+ import { readCredentials } from "../auth/credentials.js";
12
+ import { readAdoptions, summary, } from "../adoption/record.js";
13
+ import { convertServer } from "../mcps/import.js";
14
+ /** The installed folder name a Hook registration's asset ID refers to. */
15
+ const hookName = (id, state) => {
16
+ const folder = state.installed.find((entry) => entry.kind === "hook" && entry.id === id);
17
+ return folder ? basename(folder.path) : id;
18
+ };
19
+ /** Each asset once per tool; a Hook has one entry per event it handles. */
20
+ function installedAssets(state) {
21
+ const assets = state.links.map((link) => ({
22
+ kind: "skill",
23
+ name: basename(link.target),
24
+ harness: link.harness,
25
+ }));
26
+ for (const entry of state.native) {
27
+ if (entry.kind !== "mcp" && entry.kind !== "hook") {
28
+ continue;
29
+ }
30
+ const name = entry.kind === "mcp" ? entry.key : hookName(entry.id, state);
31
+ if (!assets.some((asset) => asset.kind === entry.kind &&
32
+ asset.name === name &&
33
+ asset.harness === entry.harness)) {
34
+ assets.push({ kind: entry.kind, name, harness: entry.harness });
35
+ }
36
+ }
37
+ return assets;
38
+ }
39
+ /** An MCP entry BarnDog wrote, read back the way `mcp add --from` reads one. */
40
+ function definitionOf(entry) {
41
+ const { imported } = adapters[entry.harness].mcp;
42
+ try {
43
+ return convertServer({
44
+ name: entry.key,
45
+ server: imported ? imported(entry.value) : entry.value,
46
+ });
47
+ }
48
+ catch (error) {
49
+ if (error instanceof CliError) {
50
+ return undefined;
51
+ }
52
+ throw error;
53
+ }
54
+ }
55
+ /**
56
+ * The variables BarnDog's MCP entries read from the environment, each once.
57
+ * A value BarnDog kept is written into the entry, so it isn't one of them.
58
+ */
59
+ export function mcpVariables(state) {
60
+ const variables = new Map();
61
+ for (const entry of state.native) {
62
+ const converted = entry.kind === "mcp" ? definitionOf(entry) : undefined;
63
+ if (!converted) {
64
+ continue;
65
+ }
66
+ const written = new Set(converted.literals.map(({ variable }) => variable));
67
+ for (const { secretRef } of Object.values(secretRefs(converted.definition))) {
68
+ if (!written.has(secretRef)) {
69
+ variables.set(secretRef, (variables.get(secretRef) ?? new Set()).add(entry.key));
70
+ }
71
+ }
72
+ }
73
+ return [...variables].map(([name, servers]) => ({
74
+ name,
75
+ servers: [...servers],
76
+ }));
77
+ }
78
+ export async function uninstallSurvey(runtime) {
79
+ const { home } = runtime;
80
+ const root = barndogPaths(home).root;
81
+ // A damaged config.yaml shouldn't stop an uninstall; only the workspace path comes from it.
82
+ const settings = await readSettings(home).catch(() => null);
83
+ const state = await readState(home);
84
+ const adoptions = await readAdoptions(home);
85
+ const { servers } = await readCredentials(runtime);
86
+ const local = settings?.localWorkspace?.path;
87
+ // Setup always puts it in ~/.barndog/workspace; a path edited to point
88
+ // elsewhere is outside what uninstall deletes, so there is nothing to ask.
89
+ const workspace = local && isInside(root, local) && (await ifExists(lstat(local)))
90
+ ? local
91
+ : undefined;
92
+ return {
93
+ root,
94
+ installed: installedAssets(state),
95
+ adopted: adoptions
96
+ .filter((record) => record.status !== "undone")
97
+ .flatMap((record) => summary(record).items)
98
+ .filter((item) => !item.undone),
99
+ workspace,
100
+ servers: Object.keys(servers),
101
+ variables: mcpVariables(state),
102
+ };
103
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Whether a newer BarnDog CLI is published. The answer comes from the public
3
+ * npm registry, whichever workspace or server the developer uses, and is
4
+ * cached in `~/.barndog/update-check.json`, so a command only reads a file;
5
+ * a detached process (`entry/update-check.ts`) refreshes it at most once a day.
6
+ */
7
+ import { stat } from "node:fs/promises";
8
+ import semver from "semver";
9
+ import { z } from "zod";
10
+ import { barndogPaths } from "../../config/paths.js";
11
+ import { HOURS_PER_DAY, MILLISECONDS_PER_MINUTE, MINUTES_PER_HOUR, } from "../../shared/constants.js";
12
+ import { ifExists, readJsonIfExists, writeAtomic } from "../../shared/files.js";
13
+ /** The package's dist-tags, from the npm registry API. */
14
+ const DIST_TAGS_URL = "https://registry.npmjs.org/-/package/barndog/dist-tags";
15
+ /** Once a day is often enough to hear about a release. */
16
+ const CHECK_INTERVAL_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * MILLISECONDS_PER_MINUTE;
17
+ /** The background check gives up rather than linger. */
18
+ const REQUEST_TIMEOUT_MS = 5000;
19
+ /**
20
+ * Variables that turn the check off. `NO_UPDATE_NOTIFIER` is the one the
21
+ * `update-notifier` package made common across npm CLIs.
22
+ */
23
+ const OPT_OUT_VARIABLES = ["BARNDOG_NO_UPDATE_CHECK", "NO_UPDATE_NOTIFIER"];
24
+ const distTagsSchema = z.object({
25
+ latest: z.string(),
26
+ next: z.string().optional(),
27
+ });
28
+ const cacheSchema = z.object({
29
+ checkedAt: z.string(),
30
+ /** Absent until the registry has answered once. */
31
+ latest: z.string().optional(),
32
+ next: z.string().optional(),
33
+ });
34
+ /** A missing or unreadable cache counts as never checked. */
35
+ async function readCache(home) {
36
+ try {
37
+ return ((await readJsonIfExists(barndogPaths(home).updateCheck, cacheSchema)) ??
38
+ undefined);
39
+ }
40
+ catch {
41
+ return undefined;
42
+ }
43
+ }
44
+ /**
45
+ * Asks the registry for the published versions and caches them. A failure is
46
+ * cached as a check that keeps the earlier answer, so an offline machine
47
+ * still waits a day before trying again.
48
+ */
49
+ export async function refreshUpdateCheck(runtime, fetchTags = fetch) {
50
+ const previous = await readCache(runtime.home);
51
+ let tags;
52
+ try {
53
+ const response = await fetchTags(DIST_TAGS_URL, {
54
+ headers: { accept: "application/json" },
55
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
56
+ });
57
+ tags = response.ok
58
+ ? distTagsSchema.parse(await response.json())
59
+ : undefined;
60
+ }
61
+ catch {
62
+ tags = undefined;
63
+ }
64
+ const cache = {
65
+ checkedAt: new Date().toISOString(),
66
+ latest: tags ? tags.latest : previous?.latest,
67
+ next: tags ? tags.next : previous?.next,
68
+ };
69
+ await writeAtomic(barndogPaths(runtime.home).updateCheck, `${JSON.stringify(cache)}\n`);
70
+ }
71
+ /**
72
+ * The newest cached version above `current`. Someone on a prerelease also
73
+ * hears about newer prereleases; everyone else only about `latest`.
74
+ */
75
+ function newestAbove(current, cache) {
76
+ if (!semver.valid(current)) {
77
+ return undefined;
78
+ }
79
+ const candidates = [];
80
+ if (cache.latest && semver.valid(cache.latest)) {
81
+ candidates.push({ current, version: cache.latest, tag: "latest" });
82
+ }
83
+ if (cache.next && semver.valid(cache.next) && semver.prerelease(current)) {
84
+ candidates.push({ current, version: cache.next, tag: "next" });
85
+ }
86
+ return candidates
87
+ .filter((candidate) => semver.gt(candidate.version, current))
88
+ .sort((a, b) => semver.rcompare(a.version, b.version))[0];
89
+ }
90
+ /**
91
+ * What to do about updates after a command, from the cache alone. Undefined
92
+ * when the check is off: by an opt-out variable, in CI, or while BarnDog isn't
93
+ * set up (before `init`, after `uninstall`), so it never creates `~/.barndog/`.
94
+ */
95
+ export async function updateCheck(current, runtime) {
96
+ const { env, home } = runtime;
97
+ if (env.CI || OPT_OUT_VARIABLES.some((name) => env[name]?.trim())) {
98
+ return undefined;
99
+ }
100
+ if (!(await ifExists(stat(barndogPaths(home).settings)))) {
101
+ return undefined;
102
+ }
103
+ const cache = await readCache(home);
104
+ return {
105
+ update: cache && newestAbove(current, cache),
106
+ due: !cache || !(Date.now() - Date.parse(cache.checkedAt) < CHECK_INTERVAL_MS),
107
+ };
108
+ }
@@ -88,6 +88,11 @@ export function parseConfig(text) {
88
88
  }
89
89
  return parsed.data;
90
90
  }
91
+ /**
92
+ * The ID a Git or local workspace gives an asset, from where it lives: the
93
+ * same before it's committed as after, so a copy's ID is known as it's made.
94
+ */
95
+ export const repoAssetId = (workspaceId, kind, scope, name) => stableId(workspaceId, "asset", kind, scope.type, scope.slug, name);
91
96
  /** A hash formatted as UUIDv4, so IDs need no stored record and cannot merge-conflict. */
92
97
  export function stableId(...parts) {
93
98
  const bytes = createHash("sha256")
@@ -218,7 +223,7 @@ export async function loadWorkspace(snapshot, expectedId, options = {}) {
218
223
  const add = (kind, name, entry, read) => {
219
224
  const base = {
220
225
  kind,
221
- id: id("asset", kind, scope.type, scope.slug, name),
226
+ id: repoAssetId(config.workspaceId, kind, scope, name),
222
227
  name,
223
228
  origin: scope,
224
229
  publishedVersion: entry.hash,
@@ -65,7 +65,7 @@ export const claude = {
65
65
  file: ".claude.json",
66
66
  files: [".claude.json"],
67
67
  path: ["mcpServers"],
68
- server: (definition, _launcher, kept) => jsonMcpServer(definition, {
68
+ server: (definition, kept) => jsonMcpServer(definition, {
69
69
  reference: (variable) => `\${${variable}}`,
70
70
  typed: true,
71
71
  }, kept),
@@ -1,16 +1,20 @@
1
1
  import { hookSpecificContext, nestedHookEntry, secretRefs } from "./formats.js";
2
+ import { renamedVariablesOf } from "./read-renamed-variables.js";
3
+ import { withRenamedVariables } from "./renamed-variables.js";
4
+ import { asRecord, asStrings } from "../shared/values.js";
2
5
  /**
3
6
  * Codex forwards variables by name (`env_vars`, `env_http_headers`) instead of
4
7
  * interpolating references. It can't give a stdio server a variable under
5
- * another name; BarnDog's launcher does that. A value BarnDog keeps goes in
6
- * `env` or `http_headers` as written, the way Codex stores values it's given.
8
+ * another name, so such a server starts through the system shell, which
9
+ * renames them (`renamed-variables.ts`). A value BarnDog keeps goes in `env` or
10
+ * `http_headers` as written, the way Codex stores values it's given.
7
11
  */
8
- function mcpServer(definition, launcher, kept) {
12
+ function mcpServer(definition, kept, platform) {
9
13
  const refs = Object.entries(secretRefs(definition));
10
14
  const literal = refs.filter(([, ref]) => kept[ref.secretRef] !== undefined);
11
15
  const forwarded = refs.filter(([, ref]) => kept[ref.secretRef] === undefined);
12
16
  const values = Object.fromEntries(literal.map(([name, ref]) => [name, kept[ref.secretRef] ?? ""]));
13
- const variables = forwarded.map(([, ref]) => ref.secretRef);
17
+ const variables = [...new Set(forwarded.map(([, ref]) => ref.secretRef))];
14
18
  if (definition.transport === "http") {
15
19
  return {
16
20
  url: definition.url,
@@ -22,28 +26,47 @@ function mcpServer(definition, launcher, kept) {
22
26
  : {}),
23
27
  };
24
28
  }
25
- const inline = literal.length ? { env: values } : {};
26
- const renamed = forwarded.some(([name, ref]) => name !== ref.secretRef);
27
- if (renamed) {
28
- // The launcher checks only the variables it forwards; kept ones arrive in `env`.
29
- const environment = Object.fromEntries(forwarded);
30
- return {
31
- command: process.execPath,
32
- args: [
33
- launcher,
34
- Buffer.from(JSON.stringify({ ...definition, environment })).toString("base64url"),
35
- ],
36
- ...inline,
37
- env_vars: variables,
38
- };
39
- }
29
+ const renamed = forwarded
30
+ .filter(([name, ref]) => name !== ref.secretRef)
31
+ .map(([name, ref]) => ({ name, from: ref.secretRef }));
32
+ const server = { command: definition.command, args: definition.args };
40
33
  return {
41
- command: definition.command,
42
- args: definition.args,
43
- ...inline,
34
+ ...(renamed.length
35
+ ? withRenamedVariables(server, renamed, platform)
36
+ : server),
37
+ ...(literal.length ? { env: values } : {}),
44
38
  env_vars: variables,
45
39
  };
46
40
  }
41
+ /**
42
+ * A Codex entry for `mcp add --from` and `adopt`, with a renaming wrapper
43
+ * (which sync wrote, and `uninstall --keep-setup` left behind) read back as
44
+ * the server it starts and a reference per renamed variable. The wrapper
45
+ * lists each source variable in `env_vars` to rename it, so those are
46
+ * dropped. A definition that also passed a source on under its own name
47
+ * can't be told apart from the entry, and comes back without that variable.
48
+ */
49
+ function importedServer(entry) {
50
+ const wrapped = typeof entry.command === "string"
51
+ ? renamedVariablesOf({
52
+ command: entry.command,
53
+ args: asStrings(entry.args),
54
+ })
55
+ : undefined;
56
+ if (!wrapped) {
57
+ return entry;
58
+ }
59
+ const sources = new Set(wrapped.renamed.map(({ from }) => from));
60
+ return {
61
+ ...entry,
62
+ ...wrapped.server,
63
+ env: {
64
+ ...asRecord(entry.env),
65
+ ...Object.fromEntries(wrapped.renamed.map(({ name, from }) => [name, `\${${from}}`])),
66
+ },
67
+ env_vars: asStrings(entry.env_vars).filter((name) => !sources.has(name)),
68
+ };
69
+ }
47
70
  const toolMatcher = "Tool name, such as Bash or Edit|Write. Leave empty for all";
48
71
  export const codex = {
49
72
  id: "codex",
@@ -102,6 +125,7 @@ export const codex = {
102
125
  files: [".codex/config.toml"],
103
126
  path: ["mcp_servers"],
104
127
  server: mcpServer,
128
+ imported: importedServer,
105
129
  login: { command: ["codex", "mcp", "login"] },
106
130
  },
107
131
  configHome: {
@@ -56,7 +56,7 @@ export const cursor = {
56
56
  file: ".cursor/mcp.json",
57
57
  files: [".cursor/mcp.json"],
58
58
  path: ["mcpServers"],
59
- server: (definition, _launcher, kept) => jsonMcpServer(definition, {
59
+ server: (definition, kept) => jsonMcpServer(definition, {
60
60
  reference: (variable) => `\${env:${variable}}`,
61
61
  typed: false,
62
62
  }, kept),
@@ -6,7 +6,7 @@ import { valuesOrReferences } from "./formats.js";
6
6
  * server is `local` with the program and its arguments in one `command` list,
7
7
  * an HTTP server is `remote`. Values refer to a local variable as `{env:NAME}`.
8
8
  */
9
- function mcpServer(definition, _launcher, kept) {
9
+ function mcpServer(definition, kept) {
10
10
  const references = valuesOrReferences(definition, kept, (variable) => `{env:${variable}}`);
11
11
  const some = Object.keys(references).length > 0;
12
12
  if (definition.transport === "http") {
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Reads back a command `withRenamedVariables()` (`renamed-variables.ts`)
3
+ * wrote, on either platform, so an entry BarnDog no longer owns (after
4
+ * `barndog uninstall --keep-setup`) imports as the server it starts. Anything
5
+ * else, a wrapper edited by hand included, reads as no wrapper: the result
6
+ * must rebuild the exact same command.
7
+ */
8
+ import { isDeepStrictEqual } from "node:util";
9
+ import { encodedPowerShell } from "../platform.js";
10
+ import { VARIABLE_NAME } from "../shared/patterns.js";
11
+ import { POSIX_SHELL, withRenamedVariables, } from "./renamed-variables.js";
12
+ export function renamedVariablesOf(entry) {
13
+ const platform = entry.command === POSIX_SHELL ? "linux" : "win32";
14
+ const wrapped = platform === "linux" ? posixWrapped(entry) : powershellWrapped(entry);
15
+ return wrapped &&
16
+ isDeepStrictEqual(withRenamedVariables(wrapped.server, wrapped.renamed, platform), entry)
17
+ ? wrapped
18
+ : undefined;
19
+ }
20
+ /**
21
+ * One renamed variable in the POSIX wrapper's script, as
22
+ * `'GITHUB_PERSONAL_ACCESS_TOKEN='"$GITHUB_TOKEN"`: the name, then the source.
23
+ *
24
+ * @internal Exported for its table test in `src/tests/patterns.test.ts`.
25
+ */
26
+ export const POSIX_RENAME = new RegExp(String.raw `'(${VARIABLE_NAME.source})='"\$(${VARIABLE_NAME.source})"`, "g");
27
+ function posixWrapped({ args }) {
28
+ const [flag, script, command, ...rest] = args;
29
+ if (flag !== "-c" || script === undefined || command === undefined) {
30
+ return undefined;
31
+ }
32
+ return {
33
+ server: { command, args: rest },
34
+ renamed: [...script.matchAll(POSIX_RENAME)].map(([, name = "", from = ""]) => ({
35
+ name,
36
+ from,
37
+ })),
38
+ };
39
+ }
40
+ /**
41
+ * Where the PowerShell wrapper reads one source variable, as
42
+ * `$v0 = $env:GITHUB_TOKEN`, in the order of the renamed variables.
43
+ *
44
+ * @internal Exported for its table test in `src/tests/patterns.test.ts`.
45
+ */
46
+ export const POWERSHELL_READ = new RegExp(String.raw `\$v\d+ = \$env:(${VARIABLE_NAME.source})`, "g");
47
+ /**
48
+ * Where the PowerShell wrapper sets one renamed variable, as
49
+ * `[Environment]::SetEnvironmentVariable('GITHUB_PERSONAL_ACCESS_TOKEN', $v0)`,
50
+ * in the same order as its reads.
51
+ *
52
+ * @internal Exported for its table test in `src/tests/patterns.test.ts`.
53
+ */
54
+ export const POWERSHELL_WRITE = new RegExp(String.raw `SetEnvironmentVariable\('(${VARIABLE_NAME.source})', \$v\d+\)`, "g");
55
+ /** What `powershellWrapper()` puts after the server's command and arguments. */
56
+ const POWERSHELL_EXIT = "; if ($null -eq $LASTEXITCODE) { exit 1 }; exit $LASTEXITCODE";
57
+ /** What `powershellWrapper()` puts before the server's command and arguments. */
58
+ const POWERSHELL_CALL = "; & ";
59
+ /** The script inside an `encodedPowerShell()` invocation, without its preamble. */
60
+ function encodedScript({ args }) {
61
+ const decode = (value) => Buffer.from(value ?? "", "base64").toString("utf16le");
62
+ const preamble = decode(encodedPowerShell("").args.at(-1));
63
+ const script = decode(args.at(-1));
64
+ return script.startsWith(preamble)
65
+ ? script.slice(preamble.length)
66
+ : undefined;
67
+ }
68
+ function powershellWrapped(entry) {
69
+ const script = encodedScript(entry);
70
+ // Only names come before the call, so the first call marker is the call's.
71
+ const start = script?.indexOf(`${POWERSHELL_CALL}'`) ?? -1;
72
+ if (!script || start < 0 || !script.endsWith(POWERSHELL_EXIT)) {
73
+ return undefined;
74
+ }
75
+ const words = powershellWords(script.slice(start + POWERSHELL_CALL.length, -POWERSHELL_EXIT.length));
76
+ const [command, ...rest] = words ?? [];
77
+ if (command === undefined) {
78
+ return undefined;
79
+ }
80
+ const sources = [...script.matchAll(POWERSHELL_READ)].map(([, from = ""]) => from);
81
+ const names = [...script.matchAll(POWERSHELL_WRITE)].map(([, name = ""]) => name);
82
+ return {
83
+ server: { command, args: rest.map(fromWindowsArgument) },
84
+ renamed: names.map((name, index) => ({ name, from: sources[index] ?? "" })),
85
+ };
86
+ }
87
+ /** PowerShell's single quotes, each doubled inside a quoted word (`powershellQuote()`). */
88
+ const SINGLE_QUOTES = "'\u2018\u2019\u201A\u201B";
89
+ /** The words of `'a' 'it''s'`, or undefined when the text isn't only quoted words. */
90
+ function powershellWords(text) {
91
+ const words = [];
92
+ let index = 0;
93
+ while (index < text.length) {
94
+ if (!SINGLE_QUOTES.includes(text.charAt(index))) {
95
+ return undefined;
96
+ }
97
+ let word = "";
98
+ index += 1;
99
+ while (index < text.length) {
100
+ const character = text.charAt(index);
101
+ if (!SINGLE_QUOTES.includes(character)) {
102
+ word += character;
103
+ index += 1;
104
+ continue;
105
+ }
106
+ if (text.charAt(index + 1) !== character) {
107
+ break;
108
+ }
109
+ word += character;
110
+ index += 2;
111
+ }
112
+ words.push(word);
113
+ index += 1;
114
+ if (index < text.length && text.charAt(index) !== " ") {
115
+ return undefined;
116
+ }
117
+ index += 1;
118
+ }
119
+ return words;
120
+ }
121
+ /** The argument `windowsArgument()` was given, read back from what it wrote. */
122
+ function fromWindowsArgument(written) {
123
+ if (written === '""') {
124
+ return "";
125
+ }
126
+ let value = "";
127
+ let backslashes = 0;
128
+ for (const character of written) {
129
+ if (character === "\\") {
130
+ backslashes += 1;
131
+ continue;
132
+ }
133
+ value +=
134
+ character === '"'
135
+ ? `${"\\".repeat((backslashes - 1) / 2)}"`
136
+ : `${"\\".repeat(backslashes)}${character}`;
137
+ backslashes = 0;
138
+ }
139
+ const quoted = [...written].some((character) => character.trim() === "");
140
+ return value + "\\".repeat(quoted ? backslashes / 2 : backslashes);
141
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Starting a stdio MCP server with some variables taken from other names
3
+ * (`GITHUB_PERSONAL_ACCESS_TOKEN` from `GITHUB_TOKEN`), for a tool that can
4
+ * only pass a variable on under its own name. The tool starts the system
5
+ * shell, which sets each renamed variable and then replaces itself with the
6
+ * server, so the entry needs nothing of BarnDog's and keeps working after
7
+ * BarnDog is uninstalled.
8
+ *
9
+ * The server's command and arguments never become script text on POSIX: they
10
+ * reach the shell as `$0` and `$@` and are passed on exactly as written. A
11
+ * variable name is always `[A-Za-z_][A-Za-z0-9_]*` (the contract's `envName`),
12
+ * so names are safe inside the script. Like any tool's own `env`, the mapping
13
+ * is set before the server's command runs, so a command that sets the same
14
+ * variable itself wins.
15
+ */
16
+ import { encodedPowerShell, isWindows } from "../platform.js";
17
+ import { posixQuote, powershellQuote } from "../shared/shell.js";
18
+ /** The POSIX shell, at the path POSIX systems (NixOS and Guix included) keep it. */
19
+ export const POSIX_SHELL = "/bin/sh";
20
+ /**
21
+ * `env`, which sets every variable from values the shell expanded before it
22
+ * ran, so a swap (`A` from `B`, `B` from `A`) works.
23
+ */
24
+ const POSIX_ENV = "/usr/bin/env";
25
+ export function withRenamedVariables(server, renamed, platform) {
26
+ return isWindows(platform)
27
+ ? powershellWrapper(server, renamed)
28
+ : posixWrapper(server, renamed);
29
+ }
30
+ /** Each local variable once, in the order the definition names them. */
31
+ const sources = (renamed) => [
32
+ ...new Set(renamed.map((variable) => variable.from)),
33
+ ];
34
+ /**
35
+ * `/bin/sh -c '<script>' <command> <args…>`. `${X:?…}` stops with a message
36
+ * when `X` is unset or empty, as the tool's own reference would leave the
37
+ * server without a value; the tool shows the message as the server's error.
38
+ */
39
+ function posixWrapper(server, renamed) {
40
+ const checks = sources(renamed).map((from) => `: "\${${from}:?${from} is not set}"; `);
41
+ const assignments = renamed.map(({ name, from }) => `${posixQuote(`${name}=`)}"$${from}"`);
42
+ const script = `${checks.join("")}exec ${POSIX_ENV} ${assignments.join(" ")} "$0" "$@"`;
43
+ return {
44
+ command: POSIX_SHELL,
45
+ args: ["-c", script, server.command, ...server.args],
46
+ };
47
+ }
48
+ /**
49
+ * Windows PowerShell running the same steps. Its arguments can't be passed
50
+ * apart from the script, so the command and arguments are quoted into it, and
51
+ * the script is encoded so the tool's own argument quoting can't change it.
52
+ * Values are read before any is set, so a swap works here too.
53
+ */
54
+ function powershellWrapper(server, renamed) {
55
+ const checks = sources(renamed).map((from) => `if (-not $env:${from}) { [Console]::Error.WriteLine(${powershellQuote(`${from} is not set`)}); exit 1 }`);
56
+ const reads = renamed.map(({ from }, index) => `$v${index} = $env:${from}`);
57
+ const writes = renamed.map(({ name }, index) => `[Environment]::SetEnvironmentVariable(${powershellQuote(name)}, $v${index})`);
58
+ const call = [
59
+ powershellQuote(server.command),
60
+ ...server.args.map((arg) => powershellQuote(windowsArgument(arg))),
61
+ ].join(" ");
62
+ const script = [
63
+ ...checks,
64
+ ...reads,
65
+ ...writes,
66
+ `& ${call}; if ($null -eq $LASTEXITCODE) { exit 1 }; exit $LASTEXITCODE`,
67
+ ].join("; ");
68
+ return encodedPowerShell(script);
69
+ }
70
+ /**
71
+ * An argument written so the program receives it unchanged from Windows
72
+ * PowerShell 5.1, which builds the command line itself: it puts quotes around
73
+ * an argument with whitespace outside quotes, drops an empty one, and passes
74
+ * every other character as is. The program then splits the line by the
75
+ * Microsoft C runtime's rules, where `\"` is a literal quote and backslashes
76
+ * count only before a quote. So `""` stands for an empty argument, each quote
77
+ * gets a backslash (and the backslashes before it double), and trailing
78
+ * backslashes double when PowerShell will close the argument with a quote.
79
+ */
80
+ function windowsArgument(value) {
81
+ if (value === "") {
82
+ return '""';
83
+ }
84
+ let written = "";
85
+ let backslashes = 0;
86
+ for (const character of value) {
87
+ if (character === "\\") {
88
+ backslashes += 1;
89
+ continue;
90
+ }
91
+ written +=
92
+ character === '"'
93
+ ? `${"\\".repeat(backslashes * 2 + 1)}"`
94
+ : `${"\\".repeat(backslashes)}${character}`;
95
+ backslashes = 0;
96
+ }
97
+ const quoted = [...value].some((character) => character.trim() === "");
98
+ return written + "\\".repeat(quoted ? backslashes * 2 : backslashes);
99
+ }
package/dist/platform.js CHANGED
@@ -258,6 +258,17 @@ export function stopProcessTree(child, runtime, signal = "SIGKILL") {
258
258
  /* The child has already exited. */
259
259
  }
260
260
  }
261
+ /**
262
+ * The environment for a Windows PowerShell (5.1) that BarnDog runs itself.
263
+ * PowerShell 7 puts its own module folders first in `PSModulePath`, and a
264
+ * Windows PowerShell started from it inherits them, then fails to load
265
+ * PowerShell 7's `Microsoft.PowerShell.Security` (`Get-Acl`). Without the
266
+ * variable, Windows PowerShell builds its default module path. Windows
267
+ * environment names ignore case.
268
+ */
269
+ function windowsPowerShellEnvironment(env) {
270
+ return Object.fromEntries(Object.entries(env).filter(([name]) => name.toUpperCase() !== "PSMODULEPATH"));
271
+ }
261
272
  /** Windows DACLs replace POSIX modes: only the current user receives access. */
262
273
  export async function protectPrivate(path, runtime) {
263
274
  if (!isWindows(runtime.platform)) {
@@ -266,7 +277,7 @@ export async function protectPrivate(path, runtime) {
266
277
  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
278
  const invocation = encodedPowerShell(script);
268
279
  await execute(invocation.command, invocation.args, {
269
- env: { ...runtime.env },
280
+ env: windowsPowerShellEnvironment(runtime.env),
270
281
  cwd: runtime.cwd,
271
282
  windowsHide: true,
272
283
  });