barndog 0.2.0 → 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 (112) hide show
  1. package/README.md +45 -24
  2. package/dist/cli.js +27 -1
  3. package/dist/commands/add.js +1 -0
  4. package/dist/commands/adopt.js +91 -0
  5. package/dist/commands/asset-install.js +1 -0
  6. package/dist/commands/asset-list.js +12 -3
  7. package/dist/commands/availability.js +25 -8
  8. package/dist/commands/capabilities.js +8 -2
  9. package/dist/commands/collaboration.js +22 -2
  10. package/dist/commands/harnesses.js +104 -0
  11. package/dist/commands/mcp-env.js +167 -0
  12. package/dist/commands/mcp.js +4 -2
  13. package/dist/commands/sets.js +13 -2
  14. package/dist/commands/status.js +2 -1
  15. package/dist/commands/sync.js +2 -1
  16. package/dist/commands/uninstall.js +62 -0
  17. package/dist/commands/workspace.js +43 -5
  18. package/dist/config/paths.js +21 -0
  19. package/dist/config/settings.js +5 -3
  20. package/dist/config/state.js +18 -6
  21. package/dist/entry/update-check.js +15 -0
  22. package/dist/features/adoption/adopt.js +235 -0
  23. package/dist/features/adoption/copies.js +29 -0
  24. package/dist/features/adoption/originals.js +116 -0
  25. package/dist/features/adoption/record.js +120 -0
  26. package/dist/features/adoption/restore.js +28 -0
  27. package/dist/features/adoption/scan.js +482 -0
  28. package/dist/features/adoption/undo.js +42 -0
  29. package/dist/features/asset-kinds/index.js +9 -0
  30. package/dist/features/auth/credentials.js +7 -14
  31. package/dist/features/auth/session.js +26 -5
  32. package/dist/features/auth/transport.js +3 -2
  33. package/dist/features/collaboration/workspace-git.js +13 -7
  34. package/dist/features/collaboration/workspace-github.js +2 -1
  35. package/dist/features/collaboration/workspace-store.js +25 -4
  36. package/dist/features/collaboration/workspace.js +22 -2
  37. package/dist/features/doctor/index.js +46 -7
  38. package/dist/features/environment/events.js +8 -1
  39. package/dist/features/environment/harnesses.js +36 -0
  40. package/dist/features/environment/kept-values.js +68 -0
  41. package/dist/features/environment/moves.js +187 -0
  42. package/dist/features/environment/names.js +10 -6
  43. package/dist/features/environment/operations.js +7 -7
  44. package/dist/features/environment/stage.js +25 -1
  45. package/dist/features/environment/sync.js +17 -6
  46. package/dist/features/environment/writes.js +55 -8
  47. package/dist/features/hooks/compatibility.js +11 -5
  48. package/dist/features/hooks/divergence.js +30 -9
  49. package/dist/features/hooks/test.js +25 -25
  50. package/dist/features/imports/discover.js +1 -1
  51. package/dist/features/imports/local.js +15 -2
  52. package/dist/features/imports/remote.js +2 -1
  53. package/dist/features/inventory/index.js +57 -3
  54. package/dist/features/inventory/show.js +74 -0
  55. package/dist/features/mcps/import.js +95 -21
  56. package/dist/features/mcps/index.js +24 -9
  57. package/dist/features/mcps/values.js +121 -0
  58. package/dist/features/migration/migrate.js +15 -0
  59. package/dist/features/migration/move.js +105 -25
  60. package/dist/features/migration/promote.js +2 -0
  61. package/dist/features/native/adapters.js +20 -7
  62. package/dist/features/native/configuration.js +8 -4
  63. package/dist/features/native/hook-shell.js +11 -0
  64. package/dist/features/native/secret-values.js +74 -0
  65. package/dist/features/secrets/index.js +142 -0
  66. package/dist/features/uninstall/index.js +126 -0
  67. package/dist/features/uninstall/leave.js +152 -0
  68. package/dist/features/uninstall/survey.js +103 -0
  69. package/dist/features/update-check/index.js +108 -0
  70. package/dist/features/workspace/format.js +19 -10
  71. package/dist/features/workspace/git.js +11 -4
  72. package/dist/features/workspace/overlay.js +23 -36
  73. package/dist/features/workspace/packages.js +16 -3
  74. package/dist/features/workspace/publish.js +1 -1
  75. package/dist/features/workspace/repo-source.js +4 -3
  76. package/dist/features/workspace/setup.js +12 -3
  77. package/dist/features/workspace/snapshot.js +7 -1
  78. package/dist/harnesses/claude.js +2 -2
  79. package/dist/harnesses/codex.js +54 -20
  80. package/dist/harnesses/cursor.js +2 -2
  81. package/dist/harnesses/formats.js +12 -5
  82. package/dist/harnesses/opencode.js +3 -6
  83. package/dist/harnesses/read-renamed-variables.js +141 -0
  84. package/dist/harnesses/renamed-variables.js +99 -0
  85. package/dist/platform.js +51 -12
  86. package/dist/program.js +68 -8
  87. package/dist/shared/files.js +35 -0
  88. package/dist/shared/lock.js +87 -23
  89. package/dist/shared/patterns.js +8 -0
  90. package/dist/shared/shell.js +0 -2
  91. package/dist/ui/add-hook.js +8 -2
  92. package/dist/ui/add-mcp.js +82 -13
  93. package/dist/ui/add-skills.js +7 -5
  94. package/dist/ui/adopt.js +202 -0
  95. package/dist/ui/assets.js +5 -3
  96. package/dist/ui/auth.js +2 -1
  97. package/dist/ui/clash.js +2 -3
  98. package/dist/ui/connection.js +9 -2
  99. package/dist/ui/harness-picker.js +23 -0
  100. package/dist/ui/mcp.js +89 -23
  101. package/dist/ui/move.js +49 -2
  102. package/dist/ui/onboarding.js +40 -27
  103. package/dist/ui/output.js +35 -8
  104. package/dist/ui/package-details.js +34 -0
  105. package/dist/ui/scope-install.js +4 -1
  106. package/dist/ui/secret-input.js +28 -0
  107. package/dist/ui/selection.js +3 -1
  108. package/dist/ui/uninstall.js +174 -0
  109. package/dist/ui/update.js +10 -0
  110. package/dist/version.js +2 -2
  111. package/package.json +1 -1
  112. package/dist/entry/mcp-launch.js +0 -71
@@ -1,9 +1,9 @@
1
- import { resolveAssets } from "../asset-selection/index.js";
2
1
  import { localRepoSource } from "./repo-source.js";
3
2
  import { z } from "zod";
4
3
  import { localWorkspaceFiles } from "../../config/paths.js";
5
4
  import { readJsonIfExists, writeAtomic } from "../../shared/files.js";
6
5
  import { POSIX_MODE } from "../../shared/constants.js";
6
+ import { rm } from "node:fs/promises";
7
7
  /** How assets in the kept local folder are addressed next to a shared workspace. */
8
8
  export const LOCAL_ORIGIN = "local";
9
9
  const movedSchema = z.array(z.looseObject({
@@ -12,12 +12,21 @@ const movedSchema = z.array(z.looseObject({
12
12
  name: z.string(),
13
13
  /** Scope it was moved to; knowledge has none. */
14
14
  originId: z.string().optional(),
15
- /** Set once the shared copy was selected, so removing it later sticks. */
16
- adopted: z.boolean().optional(),
15
+ /**
16
+ * The local version that was moved, so an edit made since keeps the local
17
+ * copy. Moves recorded before this was kept have none.
18
+ */
19
+ version: z.string().optional(),
20
+ /** Where it went, as `local list` names it: a scope or a repository. */
21
+ target: z.string().optional(),
22
+ /** The pull request it waits for, when the move needs a review. */
23
+ url: z.string().nullable().optional(),
17
24
  }));
25
+ /** Where a move is going, as people read it: its pull request, else the destination. */
26
+ export const moveDestination = (entry) => entry.url ?? entry.target ?? "the shared workspace";
18
27
  /**
19
28
  * Reads and validates movement records in a workspace folder; an absent file
20
- * means nothing has moved.
29
+ * means nothing is moving.
21
30
  */
22
31
  export async function readMoved(folder) {
23
32
  return ((await readJsonIfExists(localWorkspaceFiles(folder).moved, movedSchema)) ??
@@ -25,11 +34,17 @@ export async function readMoved(folder) {
25
34
  }
26
35
  /**
27
36
  * Writes movement records in the folder, replacing prior entries with the same
28
- * local path.
37
+ * local path and dropping the `finished` ones.
29
38
  */
30
- export async function recordMoved(folder, added) {
31
- const kept = (await readMoved(folder)).filter((entry) => !added.some((asset) => asset.path === entry.path));
32
- await writeAtomic(localWorkspaceFiles(folder).moved, JSON.stringify([...kept, ...added], null, 2) + "\n", { mode: POSIX_MODE.regularFile });
39
+ export async function recordMoved(folder, added, finished = []) {
40
+ const kept = (await readMoved(folder)).filter((entry) => !finished.includes(entry.path) &&
41
+ !added.some((asset) => asset.path === entry.path));
42
+ const next = [...kept, ...added];
43
+ if (!next.length) {
44
+ await rm(localWorkspaceFiles(folder).moved, { force: true });
45
+ return;
46
+ }
47
+ await writeAtomic(localWorkspaceFiles(folder).moved, JSON.stringify(next, null, 2) + "\n", { mode: POSIX_MODE.regularFile });
33
48
  }
34
49
  /** The local folder, when it runs alongside a Git or Cloud workspace. */
35
50
  export function localOverlay(settings, runtime) {
@@ -86,34 +101,6 @@ export async function mergeLocalCatalog(catalog, overlay) {
86
101
  ],
87
102
  };
88
103
  }
89
- /** Once a moved asset exists in the shared workspace, this machine uses that copy. */
90
- export async function adoptMoved(overlay, catalog, state, persist) {
91
- const moved = await readMoved(overlay.label);
92
- const selected = new Set(resolveAssets(catalog, state).assets.map((entry) => entry.asset.id));
93
- const ids = [...state.individualAssetIds];
94
- const adopted = [];
95
- for (const entry of moved) {
96
- if (entry.adopted || !entry.originId) {
97
- continue;
98
- }
99
- const asset = catalog.assets.find((a) => a.kind === entry.kind &&
100
- a.name === entry.name &&
101
- a.origin.id === entry.originId);
102
- if (!asset) {
103
- continue;
104
- }
105
- if (!selected.has(asset.id)) {
106
- ids.push(asset.id);
107
- }
108
- adopted.push({ ...entry, adopted: true });
109
- }
110
- if (persist && adopted.length) {
111
- await recordMoved(overlay.label, adopted);
112
- }
113
- return ids.length === state.individualAssetIds.length
114
- ? state
115
- : { ...state, individualAssetIds: ids };
116
- }
117
104
  /** Keeps every local asset selected, including ones added to the folder later. */
118
105
  export function withLocalSubscription(state, model) {
119
106
  return state.subscriptions.some((s) => s.scope.id === model.organizationId)
@@ -2,7 +2,7 @@ import { directoryFingerprint, writePackage } from "./directory.js";
2
2
  import { fixSteps, removeCommand } from "../../platform.js";
3
3
  import { POSIX_MODE } from "../../shared/constants.js";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
- import { mkdir, readdir, readFile, rename, rm, lstat } from "node:fs/promises";
5
+ import { mkdir, readdir, rename, rm, lstat } from "node:fs/promises";
6
6
  import { join } from "node:path";
7
7
  import { z } from "zod";
8
8
  import { defaultLimits, parsePackage, } from "@barndog-ai/api-contract/package";
@@ -13,8 +13,20 @@ import { assetFolders, packageKindList, } from "../../config/selection.js";
13
13
  import { GIT_OBJECT_ID, UUID_V4 } from "../../shared/patterns.js";
14
14
  import { CliError, PackageError } from "../../errors.js";
15
15
  import { barndogPaths, packageManifest } from "../../config/paths.js";
16
- import { ifExists, writeAtomic } from "../../shared/files.js";
16
+ import { ifExists, readIfExists, writeAtomic } from "../../shared/files.js";
17
17
  /** One identity's cache partition: server, organization and developer never mix. */
18
+ /** `text` parsed as JSON, or undefined when it is missing or not JSON. */
19
+ function jsonOrUndefined(text) {
20
+ if (text === null) {
21
+ return undefined;
22
+ }
23
+ try {
24
+ return JSON.parse(text);
25
+ }
26
+ catch {
27
+ return undefined;
28
+ }
29
+ }
18
30
  export function cacheKey(conn) {
19
31
  const server = createHash("sha256").update(conn.server).digest("hex");
20
32
  return join(server, conn.organizationId, conn.developerId);
@@ -59,9 +71,10 @@ export async function storePackage(kind, asset, { key, runtime }, load) {
59
71
  const parent = join(barndogPaths(home).packageCache(key), assetFolders[kind], asset.id);
60
72
  await mkdir(parent, { recursive: true, mode: POSIX_MODE.privateDirectory });
61
73
  const check = async (root) => {
74
+ // A missing or unreadable manifest means the same as a wrong fingerprint.
62
75
  const saved = z
63
76
  .object({ fingerprint: z.string() })
64
- .safeParse(JSON.parse(await readFile(packageManifest(root), "utf8")));
77
+ .safeParse(jsonOrUndefined(await readIfExists(packageManifest(root))));
65
78
  if (!saved.success ||
66
79
  (await directoryFingerprint(join(root, asset.name), runtime)) !==
67
80
  saved.data.fingerprint) {
@@ -46,7 +46,7 @@ export async function commitFiles(repo, parent, change, options) {
46
46
  ...(parent ? ["-p", parent] : []),
47
47
  "-m",
48
48
  change.message,
49
- ], runtime, { repo, allowPrompt: options.allowPrompt }).catch(explainIdentity);
49
+ ], runtime, { repo, allowPrompt: options.allowPrompt }).catch((error) => explainIdentity(error, runtime.platform));
50
50
  }
51
51
  finally {
52
52
  await rm(index, { force: true });
@@ -1,10 +1,11 @@
1
+ import { gitAccessCommand } from "../../platform.js";
1
2
  import { POSIX_MODE, HOURS_PER_DAY, MILLISECONDS_PER_MINUTE, MINUTES_PER_HOUR, } from "../../shared/constants.js";
2
3
  import { createHash } from "node:crypto";
3
4
  import { mkdir } from "node:fs/promises";
4
5
  import { join } from "node:path";
5
6
  import { CliError } from "../../errors.js";
6
7
  import { storePackage } from "./packages.js";
7
- import { loadWorkspace, NAME_RULE, } from "./format.js";
8
+ import { loadWorkspace, } from "./format.js";
8
9
  import { git, GitError, gitReason, gitText } from "./git.js";
9
10
  import { folderSnapshot, gitSnapshot } from "./snapshot.js";
10
11
  import { defined } from "../../shared/lookup.js";
@@ -41,7 +42,7 @@ function repoSource(backend, runtime) {
41
42
  return [
42
43
  ...invalidKnowledge.map((problem) => `Knowledge file ${problem.path} was skipped: ${problem.reason}`),
43
44
  ...problems
44
- .filter((problem) => problem.reason === NAME_RULE)
45
+ .filter((problem) => problem.badName)
45
46
  .map((problem) => `${problem.path} was skipped: ${problem.reason}. Rename it to deliver it.`),
46
47
  ];
47
48
  },
@@ -157,7 +158,7 @@ export function gitRepoSource(workspace, runtime, options = {}) {
157
158
  throw error;
158
159
  }
159
160
  if (!state.accepted) {
160
- throw new CliError(`Can't fetch ${workspace.url}: ${gitReason(error.stderr)}. Make sure you can clone it on this machine; BarnDog manages it from there.`, `git clone ${workspace.url}`, { cause: error });
161
+ throw new CliError(`Can't fetch ${workspace.url}: ${gitReason(error.stderr)}. Make sure you can clone it on this machine; BarnDog manages it from there.`, gitAccessCommand(workspace.url, runtime.platform), { cause: error });
161
162
  }
162
163
  notices.push(`Can't reach ${workspace.url}, so this uses what was fetched ${age(state.fetchedAt)} ago.`);
163
164
  return state.accepted;
@@ -1,3 +1,4 @@
1
+ import { gitAccessCommand } from "../../platform.js";
1
2
  import { POSIX_MODE } from "../../shared/constants.js";
2
3
  import { randomUUID } from "node:crypto";
3
4
  import { mkdir, rename, rm, writeFile } from "node:fs/promises";
@@ -9,6 +10,7 @@ import { commitFiles, pushCommit } from "./publish.js";
9
10
  import { ensureBareClone, fetchBranch, recordFetch, trackingRef, } from "./repo-source.js";
10
11
  import { barndogPaths } from "../../config/paths.js";
11
12
  import { readIfExists } from "../../shared/files.js";
13
+ import { errorCode } from "../../shared/values.js";
12
14
  /**
13
15
  * Branch name used when creating the first commit of an empty Git workspace.
14
16
  */
@@ -100,7 +102,7 @@ export async function cloneGitWorkspace(url, runtime) {
100
102
  await gitInTerminal(["clone", "--bare", "--", url, staging], runtime);
101
103
  }
102
104
  catch (error) {
103
- throw new CliError(`Git couldn't clone ${url}. Check that you have access, and that this URL is right.`, `git clone ${url}`, { cause: error });
105
+ throw new CliError(`Git couldn't clone ${url}. Check that you have access, and that this URL is right.`, gitAccessCommand(url, runtime.platform), { cause: error });
104
106
  }
105
107
  let commit;
106
108
  let branch;
@@ -143,11 +145,18 @@ export async function localWorkspace(runtime, path = barndogPaths(runtime.home).
143
145
  if (config !== null) {
144
146
  return { path, workspaceId: parseConfig(config).workspaceId };
145
147
  }
148
+ // barndog.yaml goes last, so a run that stopped part way is finished by the
149
+ // next one; files that run already wrote are kept as they are.
146
150
  const workspaceId = randomUUID();
147
- for (const file of skeleton({ workspaceId, name: "My workspace" })) {
151
+ const files = skeleton({ workspaceId, name: "My workspace" }).sort((a, b) => Number(a.path === CONFIG_FILE) - Number(b.path === CONFIG_FILE));
152
+ for (const file of files) {
148
153
  const target = join(path, file.path);
149
154
  await mkdir(dirname(target), { recursive: true });
150
- await writeFile(target, file.data, { flag: "wx" });
155
+ await writeFile(target, file.data, { flag: "wx" }).catch((error) => {
156
+ if (errorCode(error) !== "EEXIST" || file.path === CONFIG_FILE) {
157
+ throw error;
158
+ }
159
+ });
151
160
  }
152
161
  return { path, workspaceId };
153
162
  }
@@ -130,7 +130,13 @@ export async function gitSnapshot(repo, commit, runtime) {
130
130
  let offset = 0;
131
131
  for (const hash of unique) {
132
132
  const end = output.indexOf(LF_BYTE, offset);
133
- const size = Number(output.toString("utf8", offset, end).split(" ")[2]);
133
+ const header = output.toString("utf8", offset, end);
134
+ // `<hash> <type> <size>`, or `<hash> missing` for an absent object.
135
+ const [, type, sizeText] = header.split(" ");
136
+ const size = Number(sizeText);
137
+ if (end < 0 || type === "missing" || !Number.isSafeInteger(size)) {
138
+ throw new Error(`Git object ${hash} is missing from ${repo}: git cat-file answered "${header}"`);
139
+ }
134
140
  blobs.set(hash, output.subarray(end + 1, end + 1 + size));
135
141
  offset = end + 1 + size + 1;
136
142
  }
@@ -65,10 +65,10 @@ export const claude = {
65
65
  file: ".claude.json",
66
66
  files: [".claude.json"],
67
67
  path: ["mcpServers"],
68
- server: (definition) => jsonMcpServer(definition, {
68
+ server: (definition, kept) => jsonMcpServer(definition, {
69
69
  reference: (variable) => `\${${variable}}`,
70
70
  typed: true,
71
- }),
71
+ }, kept),
72
72
  login: { command: ["claude", "mcp", "login"] },
73
73
  },
74
74
  configHome: {
@@ -1,39 +1,72 @@
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
- * interpolating references, so secrets stay out of `config.toml`. It can't give
5
- * a stdio server a variable under another name; BarnDog's launcher does that.
7
+ * interpolating references. It can't give a stdio server a variable under
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.
6
11
  */
7
- function mcpServer(definition, launcher) {
8
- const refs = secretRefs(definition);
9
- const variables = Object.values(refs).map((ref) => ref.secretRef);
12
+ function mcpServer(definition, kept, platform) {
13
+ const refs = Object.entries(secretRefs(definition));
14
+ const literal = refs.filter(([, ref]) => kept[ref.secretRef] !== undefined);
15
+ const forwarded = refs.filter(([, ref]) => kept[ref.secretRef] === undefined);
16
+ const values = Object.fromEntries(literal.map(([name, ref]) => [name, kept[ref.secretRef] ?? ""]));
17
+ const variables = [...new Set(forwarded.map(([, ref]) => ref.secretRef))];
10
18
  if (definition.transport === "http") {
11
19
  return {
12
20
  url: definition.url,
13
- ...(variables.length
21
+ ...(literal.length ? { http_headers: values } : {}),
22
+ ...(forwarded.length
14
23
  ? {
15
- env_http_headers: Object.fromEntries(Object.entries(refs).map(([name, ref]) => [name, ref.secretRef])),
24
+ env_http_headers: Object.fromEntries(forwarded.map(([name, ref]) => [name, ref.secretRef])),
16
25
  }
17
26
  : {}),
18
27
  };
19
28
  }
20
- const renamed = Object.entries(refs).some(([name, ref]) => name !== ref.secretRef);
21
- if (renamed) {
22
- return {
23
- command: process.execPath,
24
- args: [
25
- launcher,
26
- Buffer.from(JSON.stringify(definition)).toString("base64url"),
27
- ],
28
- env_vars: variables,
29
- };
30
- }
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 };
31
33
  return {
32
- command: definition.command,
33
- args: definition.args,
34
+ ...(renamed.length
35
+ ? withRenamedVariables(server, renamed, platform)
36
+ : server),
37
+ ...(literal.length ? { env: values } : {}),
34
38
  env_vars: variables,
35
39
  };
36
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
+ }
37
70
  const toolMatcher = "Tool name, such as Bash or Edit|Write. Leave empty for all";
38
71
  export const codex = {
39
72
  id: "codex",
@@ -92,6 +125,7 @@ export const codex = {
92
125
  files: [".codex/config.toml"],
93
126
  path: ["mcp_servers"],
94
127
  server: mcpServer,
128
+ imported: importedServer,
95
129
  login: { command: ["codex", "mcp", "login"] },
96
130
  },
97
131
  configHome: {
@@ -56,10 +56,10 @@ export const cursor = {
56
56
  file: ".cursor/mcp.json",
57
57
  files: [".cursor/mcp.json"],
58
58
  path: ["mcpServers"],
59
- server: (definition) => jsonMcpServer(definition, {
59
+ server: (definition, kept) => jsonMcpServer(definition, {
60
60
  reference: (variable) => `\${env:${variable}}`,
61
61
  typed: false,
62
- }),
62
+ }, kept),
63
63
  login: { settings: "Settings → MCP" },
64
64
  },
65
65
  };
@@ -2,16 +2,23 @@
2
2
  export const secretRefs = (definition) => definition.transport === "stdio"
3
3
  ? definition.environment
4
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
+ }
5
15
  /**
6
16
  * A server entry for a tool that keeps `mcpServers` in JSON, as Claude Code and
7
17
  * Cursor do. They differ in how a value refers to a local environment variable
8
18
  * and in whether an entry must name its transport in `type`.
9
19
  */
10
- export function jsonMcpServer(definition, format) {
11
- const references = Object.fromEntries(Object.entries(secretRefs(definition)).map(([name, ref]) => [
12
- name,
13
- format.reference(ref.secretRef),
14
- ]));
20
+ export function jsonMcpServer(definition, format, kept) {
21
+ const references = valuesOrReferences(definition, kept, format.reference);
15
22
  const type = format.typed ? { type: definition.transport } : {};
16
23
  const some = Object.keys(references).length > 0;
17
24
  if (definition.transport === "http") {
@@ -1,16 +1,13 @@
1
1
  import { VARIABLE_NAME } from "../shared/patterns.js";
2
2
  import { asRecord, asStrings } from "../shared/values.js";
3
- import { secretRefs } from "./formats.js";
3
+ import { valuesOrReferences } from "./formats.js";
4
4
  /**
5
5
  * OpenCode's server entry (`mcp.servers.<name>` in opencode.jsonc): a stdio
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) {
10
- const references = Object.fromEntries(Object.entries(secretRefs(definition)).map(([name, ref]) => [
11
- name,
12
- `{env:${ref.secretRef}}`,
13
- ]));
9
+ function mcpServer(definition, kept) {
10
+ const references = valuesOrReferences(definition, kept, (variable) => `{env:${variable}}`);
14
11
  const some = Object.keys(references).length > 0;
15
12
  if (definition.transport === "http") {
16
13
  return {
@@ -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
+ }