akm-cli
Version:
akm (Agent Knowledge Manager) — a portable, local-first capability library for AI agents. Discover, load, share, and improve reusable skills, scripts, workflows, and knowledge across any shell-capable coding agent, including Claude Code, OpenCode, and Cur
265 lines (264 loc) • 13.3 kB
JavaScript
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
import { isDeepStrictEqual } from "node:util";
import { defineGroupCommand, defineJsonCommand, output } from "../cli/shared.js";
/**
* Config CLI commands — `akm config get/set/unset/list`.
*
* Thin wrappers around the schema walker in `core/config-walker.ts`. Adding a
* new config field is one line of Zod schema in `core/config-schema.ts` and
* zero lines here — the walker handles get/set/unset/coercion uniformly.
*
* `configVersion` is controlled by the config lifecycle. All execution
* settings use their canonical connection, harness and strategy paths; retired aliases are not
* rewritten at this boundary.
*/
import { assertKnownAdapter } from "../core/assets/gate.js";
import { isRecord } from "../core/common.js";
import { DEFAULT_CONFIG, loadConfig, mutateConfig, parseAndValidateConfigText, unusableEntryAt, } from "../core/config/config.js";
import { getConfigValueSource, resolveConfigRefSource } from "../core/config/config-extends.js";
import { resolveConfiguredSources } from "../core/config/config-sources.js";
import { configGet, configSet, configUnset, unknownKeyHint } from "../core/config/config-walker.js";
import { isEnvReference } from "../core/config/schema/primitives.js";
import { UsageError } from "../core/errors.js";
import { getConfigPath } from "../core/paths.js";
import { isInferredSecretName } from "../core/redaction.js";
import { formatRegistryUrl } from "../core/registry-url.js";
// ── Public API ──────────────────────────────────────────────────────────────
export function getConfigValue(config, key) {
return redactConfigValue(configGet(config, key), key.split("."));
}
export function setConfigValue(config, key, rawValue) {
const [group, bundle, member] = key.split(".");
if (group === "bundles" && member === "components") {
throw new UsageError(`Config key "${key}" is retired: a bundle has no components. Set bundles.${bundle}.adapter, bundles.${bundle}.root or bundles.${bundle}.writable.`, "INVALID_FLAG_VALUE");
}
const next = configSet(config, key, rawValue);
// A typo in an adapter id, or an adapter the bundle is not addressed for, is caught as it is typed, not when a bundle
// is next read.
if (key === "bundles" || key.startsWith("bundles.")) {
// Only the bundle the key names (every bundle for `bundles` itself): another bundle's fault is not this edit's.
const touched = key.split(".")[1];
for (const source of resolveConfiguredSources(next)) {
if (touched !== undefined && source.name !== touched)
continue;
if (source.adapterId !== undefined)
assertKnownAdapter(source.name, source.adapterId, { location: source.source.type === "location" });
}
}
return next;
}
export function unsetConfigValue(config, key) {
return configUnset(config, key);
}
/**
* Refuse an unset that would do nothing. A key only an `extends` base supplies has nothing local to remove:
* `unsetConfigValue` would silently no-op and the value comes right back on the next load. An entry the reader drops
* is not in the config `unsetConfigValue` sees, so it would no-op and say ok. Refuse before mutating rather than
* pretend it worked.
*/
export function assertUnsettable(key) {
const source = getConfigValueSource(key);
if (source.startsWith("extends:")) {
throw new UsageError(`Config key "${key}" is inherited from ${source} and cannot be unset here.`, "TARGET_NOT_UPDATABLE", `Override it locally with "akm config set ${key} <value>", or edit the base file directly.`);
}
const ignored = unusableEntryAt(key);
if (ignored) {
throw new UsageError(`Config key "${key}" is inside ${ignored.kind} "${ignored.name}", which akm ignores (${ignored.why}), so \`akm config\` cannot edit it.`, "TARGET_NOT_UPDATABLE", ignored.inFile
? `Remove or fix the ${ignored.group}.${ignored.name} entry in ${getConfigPath()} by hand.`
: `${getConfigPath()} is still in the retired engines form: run \`akm migrate apply\` first, then fix or remove the entry.`);
}
}
export function listConfig(config) {
// Sources live in `bundles` (spread from config); there is no top-level
// `sources[]` array.
return redactConfigValue({ ...DEFAULT_CONFIG, ...config });
}
/** A key whose string value is a credential: a name akm infers as secret, or an HTTP credential header. */
function isCredentialKey(key) {
return isInferredSecretName(key.replace(/-/g, "_")) || /^(?:proxy-)?authorization$/i.test(key);
}
/** A credential's value is never shown; an environment reference to it is (it names where the value lives). */
function redactConfigValue(value, path = []) {
const key = path.at(-1);
if (typeof value === "string" && key !== undefined && isCredentialKey(key) && !isEnvReference(value))
return undefined;
if (typeof value === "string" && isRegistryUrlPath(path))
return formatRegistryUrl(value);
if (Array.isArray(value))
return value.map((child, index) => redactConfigValue(child, [...path, String(index)]));
if (!value || typeof value !== "object")
return value;
const result = {};
for (const [name, child] of Object.entries(value)) {
const redacted = redactConfigValue(child, [...path, name]);
if (redacted !== undefined || child === undefined)
result[name] = redacted;
}
return result;
}
function isRegistryUrlPath(path) {
return path[0] === "registries" && path.at(-1) === "url";
}
export { unknownKeyHint };
/**
* Flatten a (redacted) config object down to `{dottedPath: leafValue}`
* entries. A plain object descends; an array or scalar is a leaf — matching
* `deepMergeConfig`'s own "objects merge, arrays replace wholesale" rule, so
* an array difference reports as one row rather than per-index noise.
*/
function flattenConfigLeaves(value, prefix, out) {
if (isRecord(value) && Object.keys(value).length > 0) {
for (const [key, child] of Object.entries(value))
flattenConfigLeaves(child, [...prefix, key], out);
return;
}
out.set(prefix.join("."), value);
}
/**
* Diff two (already redacted) effective config objects into sorted
* `{path, local, other}` rows for every leaf that differs — including a leaf
* present on only one side (the other's value reads `undefined`).
*/
function diffConfigs(local, other) {
const localLeaves = new Map();
const otherLeaves = new Map();
flattenConfigLeaves(local, [], localLeaves);
flattenConfigLeaves(other, [], otherLeaves);
const paths = new Set([...localLeaves.keys(), ...otherLeaves.keys()]);
const rows = [];
for (const path of paths) {
const localValue = localLeaves.get(path);
const otherValue = otherLeaves.get(path);
if (!isDeepStrictEqual(localValue, otherValue))
rows.push({ path, local: localValue, other: otherValue });
}
rows.sort((a, b) => a.path.localeCompare(b.path));
return rows;
}
/**
* `akm config diff <path|bundle//path>`: the current effective config
* (this instance's `extends` already applied) against another config file or
* bundle-relative file (loaded through the same loader, its own `extends`
* honoured), secrets redacted on both sides before comparison so a differing
* secret never round-trips into the diff.
*/
export function akmConfigDiff(ref) {
const current = loadConfig();
const { text, resolvedPath } = resolveConfigRefSource(ref, current, getConfigPath());
const other = parseAndValidateConfigText(text, resolvedPath);
const rows = diffConfigs(redactConfigValue(current), redactConfigValue(other));
return { rows };
}
// ── `akm config` command surface ────────────────────────────────────────────
// Leaf handlers are `defineJsonCommand`s, which emit the JSON envelope
// (stdout/stderr/exit-code).
//
// There is no `akm config enable|disable`: add or remove a registry with
// `akm registry add|remove`.
export const configCommand = defineGroupCommand({
meta: { name: "config", description: "Show and manage configuration" },
subCommands: {
path: defineJsonCommand({
meta: { name: "path", description: "Print the path to the config file" },
run() {
console.log(getConfigPath());
},
}),
list: defineJsonCommand({
meta: { name: "list", description: "List current configuration" },
run() {
output("config", listConfig(loadConfig()));
},
}),
get: defineJsonCommand({
meta: { name: "get", description: "Get a configuration value by key" },
args: {
key: { type: "positional", required: true, description: "Config key (for example: embedding, defaultBundle)" },
"show-source": {
type: "boolean",
description: "Wrap the value as { value, source } (local, extends:<ref> or default)",
default: false,
},
},
run({ args }) {
const value = getConfigValue(loadConfig(), args.key);
output("config", args["show-source"] ? { value, source: getConfigValueSource(args.key) } : value);
},
}),
set: defineJsonCommand({
meta: {
name: "set",
description: "Set a configuration value by key; prints the resulting config with ok: true. " +
"Array and object values take JSON, quoted for the shell: akm config set projects.x.filters.project '[\"x\"]'. " +
"Remove a key with `akm config unset`.",
},
args: {
key: {
type: "positional",
required: true,
description: "Config key (for example: defaultBundle, connections.fast.endpoint)",
},
value: { type: "positional", required: true, description: "Config value (JSON for arrays and objects)" },
// #463: stable machine-friendly entry point for plugins / hooks.
// `--silent` suppresses the config dump on stdout so hook-driven
// writes don't pollute their host's output stream.
silent: {
type: "boolean",
description: "Print nothing on success (for hooks and CI); errors still print",
default: false,
},
},
run({ args }) {
const updated = mutateConfig((current) => setConfigValue(current, args.key, args.value)).config;
if (!args.silent) {
output("config", listConfig(updated));
}
},
}),
unset: defineJsonCommand({
meta: {
name: "unset",
description: "Unset an optional configuration key or a whole section such as connections.fast or harnesses.opencode; prints the resulting config with ok: true",
},
args: {
key: { type: "positional", required: true, description: "Config key to unset" },
silent: {
type: "boolean",
description: "Print nothing on success (for hooks and CI); errors still print",
default: false,
},
},
run({ args }) {
assertUnsettable(args.key);
const result = mutateConfig((current) => unsetConfigValue(current, args.key), { absentNoop: true });
const updated = result.config;
if (!args.silent) {
output("config", listConfig(updated));
}
},
}),
diff: defineJsonCommand({
meta: {
name: "diff",
description: "Show effective-config differences against another config file or bundle-relative file, secrets redacted",
},
args: {
ref: {
type: "positional",
required: true,
description: "Other config: a file path or bundle//path (relative to the bundle's content root)",
},
},
run({ args }) {
output("config-diff", akmConfigDiff(args.ref));
},
}),
},
// The bare `akm config` invocation (and `akm config --list`) dumps the
// current config. defineGroupCommand short-circuits this body when a
// registered subcommand ran, so the routing set stays derived from the
// subCommands map and can never desync.
// Bare `akm config` runs `akm config list` (see insertBareListSubcommand in src/cli.ts).
});