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
@@ -10,8 +10,19 @@ import { LoginRequiredError } from "../auth/transport.js";
10
10
  import { synchronize } from "../environment/sync.js";
11
11
  import { assetKinds } from "../asset-kinds/index.js";
12
12
  import { barndogPaths } from "../../config/paths.js";
13
- /** An MCP variable installed servers refer to that has no value on this machine. */
13
+ import { unassignedValueMessage, unsetValueMessage, } from "../environment/events.js";
14
+ /** An MCP variable with no value on this machine, or a kept value no server has. */
14
15
  function variableCheck(event) {
16
+ if (event.type === "unassigned-value") {
17
+ return [
18
+ {
19
+ name: "MCP variable",
20
+ status: "warn",
21
+ detail: unassignedValueMessage(event.variable),
22
+ fix: `barndog mcp env set <server> ${event.variable}`,
23
+ },
24
+ ];
25
+ }
15
26
  if (event.type !== "unset-variable") {
16
27
  return [];
17
28
  }
@@ -19,8 +30,8 @@ function variableCheck(event) {
19
30
  {
20
31
  name: "MCP variable",
21
32
  status: "warn",
22
- detail: `${event.variable} has no value here, so ${event.servers.join(", ")} can't use it: BarnDog doesn't keep it and it isn't set in this shell. Coding tools opened outside a terminal may not see your shell's variables either.`,
23
- fix: `barndog mcp env set ${event.variable}`,
33
+ detail: `${unsetValueMessage(event)} BarnDog doesn't keep it and it isn't set in this shell. Coding tools opened outside a terminal may not see your shell's variables either.`,
34
+ fix: `barndog mcp env set ${event.server} ${event.variable}`,
24
35
  },
25
36
  ];
26
37
  }
@@ -98,13 +109,19 @@ export async function doctor(runtime) {
98
109
  });
99
110
  const detected = await detectHarnesses(runtime);
100
111
  for (const harness of settings.harnesses) {
112
+ const { name } = adapters[harness];
101
113
  const found = detected.find((d) => d.id === harness)?.evidence;
114
+ if (found) {
115
+ checks.push({ name, status: "ok", detail: found });
116
+ continue;
117
+ }
118
+ // Disabling removes what BarnDog installed there, so it goes in `command`.
102
119
  checks.push({
103
- name: adapters[harness].name,
104
- status: found ? "ok" : "warn",
105
- detail: found ??
106
- "Not found on this machine; assets are still installed for it.",
107
- fix: found ? undefined : "barndog init",
120
+ name,
121
+ status: "warn",
122
+ detail: "Not found on this machine; assets are still installed for it.",
123
+ fix: `Install ${name}, or stop BarnDog installing for it.`,
124
+ command: `barndog harnesses disable ${harness}`,
108
125
  });
109
126
  }
110
127
  const connected = settings.connection;
@@ -1 +1,8 @@
1
- export {};
1
+ /** What an `unset-variable` event means, as one sentence. */
2
+ export function unsetValueMessage(event) {
3
+ return event.from
4
+ ? `${event.from} has no value here, so ${event.server} can't read ${event.variable} from it.`
5
+ : `${event.variable} has no value here, so ${event.server} can't use it.`;
6
+ }
7
+ /** What an `unassigned-value` event means, as one sentence. */
8
+ export const unassignedValueMessage = (variable) => `BarnDog keeps a value for ${variable} from before each value belonged to one MCP server, and no server has it yet.`;
@@ -0,0 +1,68 @@
1
+ import { readState } from "../../config/state.js";
2
+ import { recordedVariables } from "../native/secret-values.js";
3
+ import { changeSecrets, readStoredSecrets, } from "../secrets/index.js";
4
+ function converted(values, state) {
5
+ const servers = {};
6
+ const assigned = new Set();
7
+ for (const entry of state.native) {
8
+ if (entry.kind !== "mcp") {
9
+ continue;
10
+ }
11
+ for (const variable of recordedVariables(entry.value)) {
12
+ const value = values[variable];
13
+ if (value !== undefined) {
14
+ servers[entry.id] = { ...servers[entry.id], [variable]: { value } };
15
+ assigned.add(variable);
16
+ }
17
+ }
18
+ }
19
+ return {
20
+ servers,
21
+ unassigned: Object.fromEntries(Object.entries(values).filter(([variable]) => !assigned.has(variable))),
22
+ };
23
+ }
24
+ const upgraded = (stored, state) => stored.version === 2 ? stored : converted(stored.values, state);
25
+ /** The kept values, converting a version 1 file first. */
26
+ export async function keptValues(runtime) {
27
+ const stored = await readStoredSecrets(runtime);
28
+ if (stored.version === 2) {
29
+ return stored;
30
+ }
31
+ const state = await readState(runtime.home);
32
+ const { secrets } = await changeSecrets((latest) => upgraded(latest, state), runtime);
33
+ return secrets;
34
+ }
35
+ /** Saves what `change` makes of the kept values; returns the file's path. */
36
+ export async function updateKeptValues(change, runtime) {
37
+ const state = await readState(runtime.home);
38
+ const { file } = await changeSecrets((latest) => change(upgraded(latest, state)), runtime);
39
+ return file;
40
+ }
41
+ /** `secrets` with `values` set for the server with asset ID `id`; null forgets that variable's value. */
42
+ export function withServerValues(secrets, id, values) {
43
+ const server = { ...secrets.servers[id] };
44
+ for (const [variable, value] of Object.entries(values)) {
45
+ if (value === null) {
46
+ delete server[variable];
47
+ }
48
+ else {
49
+ server[variable] = value;
50
+ }
51
+ }
52
+ return { ...secrets, servers: { ...secrets.servers, [id]: server } };
53
+ }
54
+ /** `secrets` with each moved server's values under its new asset ID. */
55
+ export function withMovedServers(secrets, moves) {
56
+ const servers = { ...secrets.servers };
57
+ for (const { from, to, copy } of moves) {
58
+ const values = servers[from];
59
+ if (!values) {
60
+ continue;
61
+ }
62
+ servers[to] = { ...values, ...servers[to] };
63
+ if (!copy) {
64
+ delete servers[from];
65
+ }
66
+ }
67
+ return { ...secrets, servers };
68
+ }
@@ -2,6 +2,7 @@ import { rm } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { isDeepStrictEqual } from "node:util";
4
4
  import { resolveAssets } from "../asset-selection/index.js";
5
+ import { updateKeptValues, withMovedServers, } from "./kept-values.js";
5
6
  import { forgetImport } from "../imports/local.js";
6
7
  import { saveSettings } from "../../config/settings.js";
7
8
  import { withSelection } from "../../config/environment.js";
@@ -46,6 +47,12 @@ async function removeLocal(entry, input) {
46
47
  });
47
48
  await forgetImport(input.overlay.label, entry.kind, entry.name);
48
49
  }
50
+ /** Kept MCP values follow each moved server to its shared copy. */
51
+ async function carryKeptValues(servers, runtime) {
52
+ if (servers.length) {
53
+ await updateKeptValues((secrets) => withMovedServers(secrets, servers), runtime);
54
+ }
55
+ }
49
56
  async function settleMoves(input) {
50
57
  const records = await readMoved(input.overlay.label);
51
58
  if (!records.length) {
@@ -57,6 +64,7 @@ async function settleMoves(input) {
57
64
  const notices = [];
58
65
  const finished = [];
59
66
  const removals = [];
67
+ const servers = [];
60
68
  const finish = (entry, keep) => {
61
69
  finished.push(entry.path);
62
70
  if (keep) {
@@ -96,7 +104,14 @@ async function settleMoves(input) {
96
104
  finished.push(entry.path);
97
105
  continue;
98
106
  }
99
- finish(entry, !(await unchanged(entry, local, shared, input)));
107
+ const keep = !(await unchanged(entry, local, shared, input));
108
+ servers.push({
109
+ kind: entry.kind,
110
+ from: local.id,
111
+ to: shared.id,
112
+ copy: keep,
113
+ });
114
+ finish(entry, keep);
100
115
  }
101
116
  const selection = ids.length === input.selection.individualAssetIds.length
102
117
  ? input.selection
@@ -104,6 +119,7 @@ async function settleMoves(input) {
104
119
  if (input.persist && finished.length) {
105
120
  // Saved first, so an interrupted sync can't leave an asset with neither copy.
106
121
  await input.saveSelection(selection);
122
+ await carryKeptValues(servers.filter((server) => server.kind === "mcp"), input.runtime);
107
123
  for (const entry of removals) {
108
124
  await removeLocal(entry, input);
109
125
  }
@@ -5,30 +5,28 @@ import { hookManifestSchema, } from "@barndog-ai/api-contract";
5
5
  import { packageFingerprint } from "@barndog-ai/api-contract/package";
6
6
  import { CliError } from "../../errors.js";
7
7
  import { adapters, isHookHarness, skillDirectory, } from "../../harnesses/registry.js";
8
- import { secretRefs } from "../../harnesses/formats.js";
9
8
  import { isInside } from "../../shared/files.js";
10
9
  import { defined } from "../../shared/lookup.js";
11
10
  import { hookEntries, hookIssue, mcpEntry } from "../native/adapters.js";
11
+ import { applyKeptValues, missingValues, } from "../secrets/index.js";
12
12
  import { desiredEntries, installedPath } from "../workspace/installed.js";
13
13
  import { hookFolders, installedName } from "./names.js";
14
14
  /**
15
- * One event per variable that installed MCP servers refer to but that has no
16
- * value here: BarnDog doesn't keep it and this environment doesn't set it.
15
+ * One event per variable an installed MCP server refers to that has no value
16
+ * here, and one per value kept from a version 1 file that no server has.
17
17
  */
18
- function unsetVariables(servers, kept, env) {
19
- const unset = new Map();
20
- for (const { name, definition } of servers) {
21
- for (const { secretRef } of Object.values(secretRefs(definition))) {
22
- if (kept[secretRef] === undefined && !env[secretRef]) {
23
- unset.set(secretRef, [...(unset.get(secretRef) ?? []), name]);
24
- }
25
- }
26
- }
27
- return [...unset].map(([variable, names]) => ({
28
- type: "unset-variable",
29
- variable,
30
- servers: names,
31
- }));
18
+ function valueEvents(servers, kept, env) {
19
+ return [
20
+ ...servers.flatMap(({ name, definition, values }) => missingValues(definition, values, env).map((missing) => ({
21
+ type: "unset-variable",
22
+ server: name,
23
+ ...missing,
24
+ }))),
25
+ ...Object.keys(kept.unassigned).map((variable) => ({
26
+ type: "unassigned-value",
27
+ variable,
28
+ })),
29
+ ];
32
30
  }
33
31
  export async function stageAssets(input) {
34
32
  const { invalid, vanished, skipped, localNames, source, harnesses, runtime } = input;
@@ -147,9 +145,11 @@ export async function stageAssets(input) {
147
145
  }
148
146
  else if (ref.kind === "mcp") {
149
147
  const definition = await source.mcpDefinition(ref);
150
- servers.push({ name, definition });
148
+ const values = input.kept.servers[ref.id] ?? {};
149
+ const applied = applyKeptValues(definition, values);
150
+ servers.push({ name, definition, values });
151
151
  for (const harness of harnesses) {
152
- native.push(mcpEntry(harness, { id: ref.id, name, definition }, input.kept, runtime));
152
+ native.push(mcpEntry(harness, { id: ref.id, name, definition: applied.definition }, applied.kept, runtime));
153
153
  }
154
154
  }
155
155
  else {
@@ -169,7 +169,7 @@ export async function stageAssets(input) {
169
169
  events.push(...registered.events);
170
170
  }
171
171
  }
172
- events.push(...unsetVariables(servers, input.kept, input.runtime.env));
172
+ events.push(...valueEvents(servers, input.kept, input.runtime.env));
173
173
  return { links: desired, native, trees, events };
174
174
  }
175
175
  /**
@@ -12,7 +12,7 @@ import { followImports } from "../imports/local.js";
12
12
  import { localOverlay } from "../workspace/overlay.js";
13
13
  import { openWorkspaceSource } from "../workspace/workspace-source.js";
14
14
  import { finishMoves } from "./moves.js";
15
- import { readSecrets } from "../secrets/index.js";
15
+ import { keptValues } from "./kept-values.js";
16
16
  import { locked, transact } from "./transaction.js";
17
17
  import { assertInstalledUntouched, linkWrites, nativeWrites, entryNames, stateText, treeWrites, } from "./writes.js";
18
18
  import { fileText } from "../../shared/files.js";
@@ -121,7 +121,7 @@ export async function synchronize(configPath, runtime, override, options = {}) {
121
121
  state: before,
122
122
  source,
123
123
  harnesses: settings.harnesses,
124
- kept: await readSecrets(runtime),
124
+ kept: await keptValues(runtime),
125
125
  runtime,
126
126
  });
127
127
  const { links: desired, native, trees } = staged;
@@ -6,7 +6,11 @@ import { treeFingerprint } from "../workspace/tree.js";
6
6
  import { linkTarget } from "../environment/transaction.js";
7
7
  import { environmentCatalog } from "../server/catalog.js";
8
8
  import { openRepoSource } from "../workspace/workspace-source.js";
9
- import { localOverlay, mergeLocalCatalog, moveDestination, readMoved, } from "../workspace/overlay.js";
9
+ import { localOverlay, mergeLocalCatalog, moveDestination, readMoved, withOverlay, } from "../workspace/overlay.js";
10
+ import { cloudSource } from "../workspace/cloud-source.js";
11
+ import { secretRefs } from "../../harnesses/formats.js";
12
+ import { missingValues } from "../secrets/index.js";
13
+ import { keptValues } from "../environment/kept-values.js";
10
14
  import { resolveAssets } from "../asset-selection/index.js";
11
15
  import { installedName, resolveClashes } from "../environment/names.js";
12
16
  import { originLabel, scopes } from "../server/origin.js";
@@ -46,11 +50,42 @@ function leftoverState(modified, offline) {
46
50
  }
47
51
  return offline ? "installed" : "removing";
48
52
  }
53
+ /**
54
+ * Finds an MCP server's variables with no value here, reading its definition
55
+ * from the same sources the inventory's catalog came from.
56
+ */
57
+ function variableCheck(input) {
58
+ const { settings, repo, overlay, runtime } = input;
59
+ const conn = settings.connection;
60
+ const primary = repo ?? (conn ? cloudSource(conn, runtime) : undefined);
61
+ const source = primary && overlay ? withOverlay(primary, overlay) : primary;
62
+ let kept;
63
+ return async ({ asset, enabled }) => {
64
+ if (!input.wanted || !source || asset.kind !== "mcp") {
65
+ return {};
66
+ }
67
+ // Read once, and only when some server needs checking.
68
+ kept ??= keptValues(runtime);
69
+ const values = (await kept).servers[asset.id] ?? {};
70
+ const definition = await source.mcpDefinition(asset);
71
+ const variables = [
72
+ ...new Set(Object.values(secretRefs(definition)).map((ref) => ref.secretRef)),
73
+ ];
74
+ return {
75
+ variables,
76
+ ...(enabled
77
+ ? {
78
+ unsetVariables: missingValues(definition, values, runtime.env).map((missing) => missing.variable),
79
+ }
80
+ : {}),
81
+ };
82
+ };
83
+ }
49
84
  /**
50
85
  * Compares configured selections, catalog and installed files to report status;
51
86
  * unreachable sources fall back to local state.
52
87
  */
53
- export async function inventory(runtime) {
88
+ export async function inventory(runtime, options = {}) {
54
89
  const { home } = runtime;
55
90
  const settings = await readSettings(home);
56
91
  if (!settings) {
@@ -101,6 +136,13 @@ export async function inventory(runtime) {
101
136
  const catalog = overlay
102
137
  ? await mergeLocalCatalog(primaryCatalog, overlay)
103
138
  : primaryCatalog;
139
+ const variablesOf = variableCheck({
140
+ wanted: Boolean(options.checkVariables),
141
+ settings,
142
+ repo,
143
+ overlay,
144
+ runtime,
145
+ });
104
146
  const selection = selectionState(settings);
105
147
  const effective = resolveAssets(catalog, selection);
106
148
  const outcome = await resolveClashes(effective.assets.flatMap(({ asset, enabled }) => {
@@ -154,6 +196,7 @@ export async function inventory(runtime) {
154
196
  ...links.map((l) => l.target),
155
197
  ...new Set(entries.map((n) => `${n.file} (${n.key})`)),
156
198
  ],
199
+ ...(await variablesOf(entry)),
157
200
  });
158
201
  }
159
202
  const visible = await loadScopes();
@@ -18,7 +18,9 @@ import { validMcpName, VARIABLE_NAME } from "../../shared/patterns.js";
18
18
  import { assetKinds } from "../asset-kinds/index.js";
19
19
  import { LOCAL_ORIGIN } from "../workspace/overlay.js";
20
20
  import { ensureLocalWorkspace } from "../imports/local.js";
21
- import { updateSecrets } from "../secrets/index.js";
21
+ import { keptValues, updateKeptValues, withServerValues, } from "../environment/kept-values.js";
22
+ import { localRepoSource } from "../workspace/repo-source.js";
23
+ import { defined } from "../../shared/lookup.js";
22
24
  import { asRecord, asStrings, isRecord } from "../../shared/values.js";
23
25
  import { barndogPaths } from "../../config/paths.js";
24
26
  /** Random characters that keep two backups of one file taken in the same millisecond apart. */
@@ -89,14 +91,33 @@ const SECRET_WORD = /api[-_]?key|token|secret|password/i;
89
91
  * @internal Exported for its table test in `src/tests/patterns.test.ts`.
90
92
  */
91
93
  export const looksSecret = (arg) => SECRET_WORD.test(arg) || arg.startsWith("sk-");
94
+ const isKept = (keep, server, variable) => keep.some((choice) => choice.server === server && choice.variable === variable);
95
+ /** Each literal of one server, and whether BarnDog keeps it. */
96
+ export function literalValues(server, literals, keep) {
97
+ return literals.map((literal) => ({
98
+ server,
99
+ variable: literal.variable,
100
+ kept: isKept(keep, server, literal.variable),
101
+ }));
102
+ }
92
103
  /**
93
- * What to tell the developer about each literal: where BarnDog keeps it, or
94
- * which variable to set. `kept` holds the variables BarnDog keeps.
104
+ * Keeps the chosen literal values for the server each came from, by its asset
105
+ * ID, and returns how to put back the values those servers had before.
95
106
  */
96
- export function literalNotes(literals, kept) {
97
- return literals.map((literal) => kept.includes(literal.variable)
98
- ? `BarnDog keeps the value of ${literal.variable} in ~/.barndog/secrets.json on this machine, never uploaded, and writes it into your coding tools.`
99
- : `${literal.key} held a literal value, which BarnDog doesn't keep. Set ${literal.variable} in your environment, or keep it with barndog mcp env set ${literal.variable}.`);
107
+ export async function keepLiteralValues(servers, keep, runtime) {
108
+ const chosen = servers.flatMap((server) => server.literals
109
+ .filter((literal) => isKept(keep, server.name, literal.variable))
110
+ .map((literal) => ({ id: server.id, ...literal })));
111
+ if (!chosen.length) {
112
+ return async () => { };
113
+ }
114
+ const before = await keptValues(runtime);
115
+ await updateKeptValues((secrets) => chosen.reduce((next, { id, variable, value }) => withServerValues(next, id, { [variable]: { value } }), secrets), runtime);
116
+ return async () => {
117
+ await updateKeptValues((secrets) => chosen.reduce((next, { id, variable }) => withServerValues(next, id, {
118
+ [variable]: before.servers[id]?.[variable] ?? null,
119
+ }), secrets), runtime);
120
+ };
100
121
  }
101
122
  /** Secrets are named, never shared: every literal becomes a variable the definition refers to. */
102
123
  function reference(key, value, fallback, found) {
@@ -349,19 +370,19 @@ export async function addMcpServers(servers, options, runtime) {
349
370
  await writeAtomic(join(workspace.path, "org/mcp", `${name}.yaml`), stringify(definition), { mode: POSIX_MODE.regularFile });
350
371
  }
351
372
  // Saved before the sync, which writes them into the tools' settings.
352
- const kept = servers.flatMap((s) => s.literals.filter((literal) => options.keep.includes(literal.variable)));
353
- if (kept.length) {
354
- await updateSecrets(Object.fromEntries(kept.map((l) => [l.variable, l.value])), runtime);
355
- }
373
+ const model = await localRepoSource(workspace, runtime).model();
374
+ await keepLiteralValues(servers.map((server) => ({
375
+ ...server,
376
+ id: defined(model.assets.find((asset) => asset.kind === "mcp" &&
377
+ asset.path === `org/mcp/${server.name}.yaml`)?.id, `The local folder has no ${server.name} after writing it`),
378
+ })), options.keep, runtime);
356
379
  const events = await synchronize(undefined, runtime, undefined, {
357
380
  prompt: false,
358
381
  });
359
382
  return {
360
383
  added: servers.map((s) => s.name),
361
- notes: servers.flatMap((s) => [...s.notes, ...literalNotes(s.literals, options.keep)].map((text) => ({
362
- server: s.name,
363
- text,
364
- }))),
384
+ notes: servers.flatMap((s) => s.notes.map((text) => ({ server: s.name, text }))),
385
+ values: servers.flatMap((s) => literalValues(s.name, s.literals, options.keep)),
365
386
  backups,
366
387
  events,
367
388
  };
@@ -14,6 +14,8 @@ import { readSettings } from "../../config/settings.js";
14
14
  import { repoForOrigin, selectRepoAsset, showRepoAsset, } from "../workspace/assets.js";
15
15
  import { gitVersions } from "../collaboration/workspace-git.js";
16
16
  import { adapters } from "../../harnesses/registry.js";
17
+ import { missingValues } from "../secrets/index.js";
18
+ import { keptValues } from "../environment/kept-values.js";
17
19
  import { patchNative } from "../native/configuration.js";
18
20
  import { fileText, inputJson } from "../../shared/files.js";
19
21
  import { defined } from "../../shared/lookup.js";
@@ -61,10 +63,18 @@ export async function showMcp(name, origin, runtime) {
61
63
  const { home } = runtime;
62
64
  const settings = await readSettings(home);
63
65
  const repo = settings && repoForOrigin(settings, runtime, origin);
66
+ const withUnset = async (asset, definition) => ({
67
+ ...asset,
68
+ unsetVariables: definition
69
+ ? missingValues(definition, (await keptValues(runtime)).servers[asset.id] ?? {}, runtime.env).map((missing) => missing.variable)
70
+ : [],
71
+ });
64
72
  if (repo) {
65
- return showRepoAsset(selectRepoAsset(await repo.model(), "mcp", name, origin));
73
+ const view = showRepoAsset(selectRepoAsset(await repo.model(), "mcp", name, origin));
74
+ return withUnset(view, view.definition);
66
75
  }
67
- return (await selectAsset("mcp", name, origin, runtime)).asset;
76
+ const { asset } = await selectAsset("mcp", name, origin, runtime);
77
+ return withUnset(asset, mcpSchema.parse(asset).version.definition);
68
78
  }
69
79
  export async function mcpVersions(name, origin, runtime) {
70
80
  const { home } = runtime;
@@ -1,33 +1,121 @@
1
1
  import { readState } from "../../config/state.js";
2
2
  import { CliError } from "../../errors.js";
3
+ import { keptValues, updateKeptValues, withServerValues, } from "../environment/kept-values.js";
3
4
  import { synchronize } from "../environment/sync.js";
4
- import { recordedVariables } from "../native/secret-values.js";
5
- import { readSecrets, updateSecrets } from "../secrets/index.js";
6
- /** Keeps `value` for `variable` and writes it into the coding tools. */
7
- export async function keepMcpValue(variable, value, runtime) {
8
- if (!value) {
9
- throw new CliError(`The value for ${variable} is empty, so nothing was kept.`, `barndog mcp env set ${variable}`);
5
+ import { inventory } from "../inventory/index.js";
6
+ import { assertVariableName, literalOf, readsFrom, } from "../secrets/index.js";
7
+ /** The MCP server called `name` on this machine: its installed name, published name or asset ID. */
8
+ async function findServer(name, runtime) {
9
+ const { items } = await inventory(runtime, { checkVariables: true });
10
+ const matches = items.filter((item) => item.kind === "mcp" &&
11
+ [item.installedName, item.name, item.id].includes(name));
12
+ const exact = matches.filter((item) => item.installedName === name);
13
+ const [only] = exact.length === 1 ? exact : matches;
14
+ if (!only || matches.length > 1) {
15
+ throw new CliError(only
16
+ ? `More than one MCP server is called ${name}.`
17
+ : `There's no MCP server called ${name} on this machine.`, "barndog mcp list");
10
18
  }
11
- const file = await updateSecrets({ [variable]: value }, runtime);
12
- return { file, events: await synchronize(undefined, runtime) };
19
+ return only;
13
20
  }
14
- /** Forgets a kept value; the tools refer to the environment variable again. */
15
- export async function forgetMcpValue(variable, runtime) {
16
- if ((await readSecrets(runtime))[variable] === undefined) {
17
- throw new CliError(`BarnDog doesn't keep a value for ${variable}.`, "barndog mcp env list");
21
+ function assertUses(server, variable) {
22
+ assertVariableName(variable);
23
+ if (server.variables && !server.variables.includes(variable)) {
24
+ throw new CliError(server.variables.length
25
+ ? `${server.installedName} doesn't use ${variable}. It uses ${server.variables.join(", ")}.`
26
+ : `${server.installedName} doesn't use any variables.`, `barndog mcp show ${server.installedName}`);
18
27
  }
19
- const file = await updateSecrets({ [variable]: null }, runtime);
28
+ }
29
+ async function changed(file, runtime) {
20
30
  return { file, events: await synchronize(undefined, runtime) };
21
31
  }
22
- /** The kept variables, with the settings files sync wrote each into. */
32
+ /** Keeps a value, or another variable to read, for one server's variable and writes it into the coding tools. */
33
+ export async function keepMcpValue(target, kept, runtime) {
34
+ const server = await findServer(target.server, runtime);
35
+ assertUses(server, target.variable);
36
+ const fix = `barndog mcp env set ${server.installedName} ${target.variable}`;
37
+ const from = readsFrom(kept);
38
+ if (literalOf(kept) === "") {
39
+ throw new CliError(`The value for ${target.variable} is empty, so nothing was kept.`, fix);
40
+ }
41
+ if (from !== undefined) {
42
+ assertVariableName(from);
43
+ if (from === target.variable) {
44
+ throw new CliError(`${target.variable} already reads ${from} from the environment.`, `barndog mcp env unset ${server.installedName} ${target.variable}`);
45
+ }
46
+ }
47
+ const file = await updateKeptValues((secrets) => withServerValues(secrets, server.id, { [target.variable]: kept }), runtime);
48
+ return changed(file, runtime);
49
+ }
50
+ /** Gives a value kept before values belonged to servers to one server. */
51
+ export async function assignKeptValue(target, runtime) {
52
+ const server = await findServer(target.server, runtime);
53
+ assertUses(server, target.variable);
54
+ const value = (await keptValues(runtime)).unassigned[target.variable];
55
+ if (value === undefined) {
56
+ throw new CliError(`BarnDog has no unassigned value for ${target.variable}.`, `barndog mcp env set ${server.installedName} ${target.variable}`);
57
+ }
58
+ const file = await updateKeptValues((secrets) => {
59
+ const unassigned = { ...secrets.unassigned };
60
+ delete unassigned[target.variable];
61
+ return withServerValues({ ...secrets, unassigned }, server.id, {
62
+ [target.variable]: { value },
63
+ });
64
+ }, runtime);
65
+ return changed(file, runtime);
66
+ }
67
+ /** Forgets one server's kept value; the tools read the variable again. */
68
+ export async function forgetMcpValue(target, runtime) {
69
+ const secrets = await keptValues(runtime);
70
+ // A server that's gone is still named by the asset ID `mcp env list` shows.
71
+ const id = Object.hasOwn(secrets.servers, target.server)
72
+ ? target.server
73
+ : (await findServer(target.server, runtime)).id;
74
+ if (!secrets.servers[id]?.[target.variable]) {
75
+ throw new CliError(`BarnDog doesn't keep ${target.variable} for ${target.server}.`, "barndog mcp env list");
76
+ }
77
+ const file = await updateKeptValues((latest) => withServerValues(latest, id, { [target.variable]: null }), runtime);
78
+ return changed(file, runtime);
79
+ }
80
+ /** Forgets a value kept before values belonged to servers. */
81
+ export async function forgetUnassignedValue(variable, runtime) {
82
+ if ((await keptValues(runtime)).unassigned[variable] === undefined) {
83
+ throw new CliError(`BarnDog has no unassigned value for ${variable}.`, "barndog mcp env list");
84
+ }
85
+ const file = await updateKeptValues((secrets) => {
86
+ const unassigned = { ...secrets.unassigned };
87
+ delete unassigned[variable];
88
+ return { ...secrets, unassigned };
89
+ }, runtime);
90
+ return changed(file, runtime);
91
+ }
92
+ /** Every kept value, by server, with the settings files sync wrote it into. */
23
93
  export async function listKeptValues(runtime) {
24
- const names = Object.keys(await readSecrets(runtime)).sort();
94
+ const secrets = await keptValues(runtime);
25
95
  const { native } = await readState(runtime.home);
26
- return names.map((variable) => ({
96
+ const servers = native.filter((entry) => entry.kind === "mcp");
97
+ const assigned = Object.entries(secrets.servers).flatMap(([id, values]) => {
98
+ const entries = servers.filter((entry) => entry.id === id);
99
+ const name = entries[0]?.key ?? id;
100
+ return Object.entries(values).map(([variable, kept]) => {
101
+ const from = readsFrom(kept);
102
+ return {
103
+ server: name,
104
+ assetId: id,
105
+ variable,
106
+ ...(from ? { from } : {}),
107
+ writtenTo: [...new Set(entries.map((entry) => entry.file))],
108
+ };
109
+ });
110
+ });
111
+ const unassigned = Object.keys(secrets.unassigned).map((variable) => ({
112
+ server: null,
113
+ assetId: null,
27
114
  variable,
28
- writtenTo: native
29
- .filter((entry) => entry.kind === "mcp" &&
30
- recordedVariables(entry.value).includes(variable))
31
- .map((entry) => ({ file: entry.file, server: entry.key })),
115
+ writtenTo: [],
32
116
  }));
117
+ const byName = (a, b) => (a.server ?? "").localeCompare(b.server ?? "") ||
118
+ a.variable.localeCompare(b.variable);
119
+ // Values no server has come last.
120
+ return [...assigned.sort(byName), ...unassigned.sort(byName)];
33
121
  }
@@ -11,6 +11,7 @@ import { originLabel, scopes } from "../server/origin.js";
11
11
  import { environmentCatalog } from "../server/catalog.js";
12
12
  import { parsed } from "../server/client.js";
13
13
  import { synchronize } from "../environment/sync.js";
14
+ import { keptValues, updateKeptValues, withMovedServers, } from "../environment/kept-values.js";
14
15
  import { locked } from "../environment/transaction.js";
15
16
  import { openRepoSource } from "../workspace/workspace-source.js";
16
17
  import { connectionContext } from "../auth/session.js";
@@ -89,6 +90,19 @@ function carryNames(next, names = {}, cloudId, kept) {
89
90
  next.localNames = carried;
90
91
  }
91
92
  }
93
+ /** Kept MCP values follow their servers to Cloud; a kept local folder's stay as they are. */
94
+ async function carryKeptValues(cloudId, kept, runtime) {
95
+ const { servers } = await keptValues(runtime);
96
+ const moves = Object.keys(servers).flatMap((from) => {
97
+ const to = kept?.assets.some((asset) => asset.id === from)
98
+ ? undefined
99
+ : cloudId(from);
100
+ return to ? [{ from, to, copy: false }] : [];
101
+ });
102
+ if (moves.length) {
103
+ await updateKeptValues((secrets) => withMovedServers(secrets, moves), runtime);
104
+ }
105
+ }
92
106
  /**
93
107
  * Knowledge is organization-wide. A broken document blocks the move like a
94
108
  * broken asset, so nothing is left behind.
@@ -255,6 +269,7 @@ export async function migrate(options, runtime) {
255
269
  delete next.gitWorkspace;
256
270
  carryNames(next, settings.localNames, cloudId, kept);
257
271
  await saveSettings(next, home);
272
+ await carryKeptValues(cloudId, kept, runtime);
258
273
  // Not the Cloud catalog fetched above: a kept local folder's assets are
259
274
  // selected too, and only the full source (Cloud plus that folder) has them.
260
275
  await synchronize(undefined, runtime, next);