UNPKG

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

461 lines (460 loc) • 20.3 kB
// 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/. /** * Dotted-path getter/setter/unsetter for AKM config objects, driven by the * Zod schema in `./config-schema.ts`. * * Adding a new config field is zero lines * of CLI code — the schema describes how to get/set/unset, and this walker * does the rest. * * Coercion rules for `configSet`: * - z.string() → use raw value * - z.number() → Number(value), must be finite * - z.boolean() → "true" | "false" (case-sensitive) * - z.enum([...]) → must match one of the literal values * - z.array(...) → JSON-parse value, expect array, validate items * - z.object({...}) → JSON-parse value, expect object, schema-validate * - z.union([a,b,...]) → try each branch in order * - z.record(...) → JSON-parse value, validate */ import { z } from "zod"; import { isRecord } from "../common.js"; import { UsageError } from "../errors.js"; import { hasRegistryUrlCredentials, REGISTRY_CREDENTIALS_UNSUPPORTED } from "../registry-url.js"; import { AkmConfigBaseSchema, listTopLevelConfigKeys } from "./config-schema.js"; import { deepMergeConfig } from "./deep-merge.js"; import { isEnvReference, OpaqueFieldSchema } from "./schema/primitives.js"; /** * Parse a dotted path into segments. Empty segments are rejected. Bracket * notation (e.g. `sources[0]`) is NOT supported — arrays are set as JSON. */ function parsePath(dotted) { if (!dotted) { throw new UsageError("Config key is required.", "INVALID_FLAG_VALUE", unknownKeyHint()); } const segments = dotted.split("."); if (segments.some((s) => !s)) { throw new UsageError(`Invalid config key "${dotted}": empty segment between dots.`, "INVALID_FLAG_VALUE", unknownKeyHint()); } return segments; } /** Strip Zod wrappers down to the inner schema. */ function unwrap(schema) { let current = schema; while (true) { if (current instanceof z.ZodOptional || current instanceof z.ZodDefault || current instanceof z.ZodNullable || // `.catch(...)` wraps an inner schema with a fallback value. current instanceof z.ZodCatch || current instanceof z.ZodReadonly) { current = current.def.innerType; } else if (current instanceof z.ZodPipe) { // `.transform()` pipes the schema into a transform and `z.preprocess()` pipes a transform into it: // descend into the side that is a schema. (`.refine()` and `.superRefine()` wrap nothing.) const { in: input, out } = current.def; current = (input instanceof z.ZodTransform ? out : input); } else { return current; } } } /** * The schema of the keys an object takes without naming them (`index.<passName>`, * a connection's request fields), or `undefined` when its extra keys are not * ones akm defines. `.passthrough()` gives an object an `unknown` catchall, so * only `OpaqueFieldSchema` itself says "any key, contents left to the endpoint". */ function namedCatchall(object) { const catchall = object.def.catchall; if (catchall === undefined || catchall instanceof z.ZodNever) return undefined; if (catchall instanceof z.ZodUnknown && catchall !== OpaqueFieldSchema) return undefined; return catchall; } /** True for a schema that accepts any value (`z.unknown()`): its contents are not keys akm defines. */ export function isOpaqueSchema(schema) { return unwrap(schema) instanceof z.ZodUnknown; } /** * Resolve the Zod schema for a given dotted path, walking from the top-level * AkmConfig schema. Returns `undefined` if any path segment doesn't match a * known schema field. */ export function resolveSchemaAt(path, config, raw) { let schema = AkmConfigBaseSchema; let existing = config; for (const [index, segment] of path.entries()) { schema = unwrap(schema); if (schema instanceof z.ZodObject) { const next = schema.shape[segment]; if (!next) { // Catchall (e.g. index.<passName>) — descend into the catchall schema. const catchall = namedCatchall(schema); if (!catchall) return undefined; schema = catchall; } else { schema = next; } } else if (schema instanceof z.ZodRecord) { // Named records (connections, harnesses, improve.strategies, sources, etc.) // accept any string key — descend into the value schema. schema = schema.def.valueType; } else if (schema instanceof z.ZodUnion) { const option = selectUnionObjectOption(schema.options, segment, existing, index === path.length - 1 ? raw : undefined); if (!option) return undefined; schema = (option.shape[segment] ?? namedCatchall(option)); } else { // Cannot descend into a non-object schema. return undefined; } existing = isRecord(existing) ? existing[segment] : undefined; } // Preserve leaf refinements/transforms for validation. Traversal unwraps at // the start of each loop iteration, while coercion unwraps independently. return schema; } function selectUnionObjectOption(candidates, segment, existing, raw) { const options = candidates .map((candidate) => unwrap(candidate)) .filter((candidate) => candidate instanceof z.ZodObject); if (raw !== undefined) { const requested = options.find((option) => { const leaf = option.shape[segment]; if (!leaf || !(unwrap(leaf) instanceof z.ZodLiteral)) return false; return leaf.safeParse(coerceForSchema(leaf, raw, segment)).success; }); if (requested) return requested; } if (isRecord(existing)) { const selected = options.find((option) => Object.entries(option.shape).some(([key, field]) => key in existing && unwrap(field) instanceof z.ZodLiteral && field.safeParse(existing[key]).success)); if (selected) return segment in selected.shape ? selected : undefined; } return (options.find((option) => segment in option.shape) ?? // A model entry such as `{ model, reasoning_effort }` holds request fields the object does not name. options.find((option) => namedCatchall(option) !== undefined)); } /** * Get the value at the dotted path from a config-shaped object. Returns * `undefined` when the path is unset, `null` for paths that are explicitly * set to `null`. */ export function configGet(config, dotted) { const path = parsePath(dotted); const schema = resolveSchemaAt(path, config); if (!schema) { throw new UsageError(`Unknown config key: ${dotted}`, "INVALID_FLAG_VALUE", unknownKeyHint()); } let cursor = config; for (const segment of path) { if (cursor === null || cursor === undefined) return null; if (typeof cursor !== "object") return null; cursor = cursor[segment]; } return cursor ?? null; } /** * Set the value at the dotted path. Coerces `raw` according to the schema at * that path. Returns a new config object — the input is not mutated. * * Throws {@link UsageError} on: * - unknown path * - invalid apiKey paths * - coercion failure */ export function configSet(config, dotted, raw) { const path = parsePath(dotted); if (path.length === 1 && path[0] === "configVersion") { throw new UsageError("configVersion cannot be changed through config set.", "INVALID_FLAG_VALUE"); } // #454: a literal apiKey is not persistable. Throw at set time. rejectApiKeyPath(path, raw, dotted); rejectLiteralApiKeyInWholeObjectSet(path, raw, dotted); const schema = resolveSchemaAt(path, config, raw); if (!schema) { throw new UsageError(`Unknown config key: ${dotted}`, "INVALID_FLAG_VALUE", unknownKeyHint()); } const judgmentObjectPath = isTriageJudgmentPath(path); const value = judgmentObjectPath && raw === "null" ? undefined : coerceForSchema(schema, raw, dotted); if (path[0] === "registries") rejectRegistryCredentialValue(value, dotted); const existing = path.reduce((value, key) => { if (value && typeof value === "object") return value[key]; return undefined; }, config); // The judgment leaf supplies `enabled: true` when the field is omitted. // Merge a JSON object patch with the existing value before that current // schema transform, // otherwise the synthesized default can overwrite an explicit false. const candidate = judgmentObjectPath && isRecord(value) ? deepMergeConfig(isRecord(existing) ? existing : {}, value) : value; // Validate the coerced value against the leaf schema. This catches enum // mismatches, out-of-range numbers, schema-level shape errors (writable // npm/website sources via .superRefine, strict-mode unknown keys in nested // objects, etc.) BEFORE we apply the patch. const parsed = schema.safeParse(candidate); if (!parsed.success) { const lines = parsed.error.issues .map((i) => { const path = i.path.length > 0 ? `${dotted}.${i.path.join(".")}` : dotted; return ` - ${path}: ${i.message}`; }) .join("\n"); throw new UsageError(`Invalid value for ${dotted}:\n${lines}`, "INVALID_FLAG_VALUE"); } const next = setPath(config, path, isRecord(existing) && isRecord(parsed.data) ? deepMergeConfig(existing, parsed.data) : parsed.data); // Targeted invariant: defaultWriteTarget must point at a configured bundle // (#464.a). Whole-config validation happens at save time; this check fires // at set time so the user sees the typo immediately. if (dotted === "defaultWriteTarget" && typeof value === "string") { const bundles = next.bundles && typeof next.bundles === "object" ? next.bundles : {}; const knownNames = Object.keys(bundles); if (!knownNames.includes(value)) { throw new UsageError(`Unknown bundle "${value}" for defaultWriteTarget; configured bundles: ${knownNames.map((n) => `"${n}"`).join(", ") || "none"}.`, "INVALID_FLAG_VALUE"); } } return next; } function isTriageJudgmentPath(path) { return (path.length === 6 && path[0] === "improve" && path[1] === "strategies" && path[3] === "processes" && path[4] === "triage" && path[5] === "judgment"); } /** * Unset the value at the dotted path. Removes the leaf key and leaves its * parent objects in place, even when they become empty: `{}` is a value here * (`harnesses.opencode: {}` is how a harness is enabled). Returns a new config * object. */ export function configUnset(config, dotted) { const path = parsePath(dotted); if (path.length === 1 && path[0] === "configVersion") { throw new UsageError("configVersion cannot be removed through config unset.", "INVALID_FLAG_VALUE"); } // A path the schema does not know is removable only when the file holds it (a key an older akm wrote); otherwise a // typo would no-op. if (!resolveSchemaAt(path, config) && !holdsPath(config, path)) { throw new UsageError(`Unknown config key: ${dotted}`, "INVALID_FLAG_VALUE", unknownKeyHint()); } return unsetPath(config, path); } // ── apiKey rejection (#454) ───────────────────────────────────────────────── const LITERAL_API_KEY_RECIPE = "use a $VAR reference (and set that variable), or put the key in credentials.json under the block's name"; const LITERAL_API_KEY_HINT = "Storing API keys in config.json leaks them through backups, logs, and version control. " + "akm keeps keys in the environment or in credentials.json."; /** The two config blocks that carry an `apiKey` akm resolves at request time. */ function isCredentialPath(path) { return (path[0] === "connections" && path.length === 3) || (path[0] === "embedding" && path.length === 2); } /** * A literal `apiKey` is never persisted: on the two credential blocks only a * `$VAR` reference is accepted, and an `apiKey` anywhere else is not a key akm * defines. */ function rejectApiKeyPath(path, raw, dotted) { if (path[path.length - 1] !== "apiKey") return; if (isCredentialPath(path) && isEnvReference(raw)) return; throw new UsageError(`apiKey cannot be a literal in config; ${LITERAL_API_KEY_RECIPE}. (key: ${dotted})`, "INVALID_FLAG_VALUE", LITERAL_API_KEY_HINT); } /** Whether `value` holds a string `apiKey` that is not a `$VAR` reference, at any depth. */ function holdsLiteralApiKey(value) { if (!isRecord(value)) return false; return Object.entries(value).some(([key, child]) => key === "apiKey" ? typeof child === "string" && !isEnvReference(child) : holdsLiteralApiKey(child)); } function rejectLiteralApiKeyInWholeObjectSet(path, raw, dotted) { const wholeObject = ["connections", "embedding"].includes(path[0]) && !isCredentialPath(path); if (!wholeObject) return; let parsed; try { parsed = JSON.parse(raw); } catch { return; // Malformed JSON — the caller's own parse/coercion reports this. } if (!holdsLiteralApiKey(parsed)) return; throw new UsageError(`apiKey cannot be a literal in config; ${LITERAL_API_KEY_RECIPE}. (key: ${dotted})`, "INVALID_FLAG_VALUE", LITERAL_API_KEY_HINT); } function rejectRegistryCredentialValue(value, dotted) { const entries = Array.isArray(value) ? value : [value]; for (const entry of entries) { const url = isRecord(entry) && typeof entry.url === "string" ? entry.url : undefined; if (url && hasRegistryUrlCredentials(url)) { throw new UsageError(`${REGISTRY_CREDENTIALS_UNSUPPORTED} (key: ${dotted})`, "INVALID_FLAG_VALUE", REGISTRY_CREDENTIALS_UNSUPPORTED); } } } // ── Coercion ──────────────────────────────────────────────────────────────── /** * Coerce a CLI string into the value expected by the given schema. JSON-object * and JSON-array schemas accept either a JSON literal or the string `null`/ * empty (which clears the value, equivalent to unset). */ function coerceForSchema(schema, raw, key) { const target = unwrap(schema); if (target instanceof z.ZodString) { return raw; } if (target instanceof z.ZodNumber) { const n = Number(raw); if (!Number.isFinite(n)) { throw new UsageError(`Invalid value for ${key}: expected a number, got "${raw}".`); } return n; } if (target instanceof z.ZodBoolean) { if (raw === "true") return true; if (raw === "false") return false; throw new UsageError(`Invalid value for ${key}: expected true or false, got "${raw}".`); } if (target instanceof z.ZodEnum) { return raw; } if (target instanceof z.ZodLiteral) { return typeof target.value === "string" ? raw : target.value; } if (target instanceof z.ZodArray || target instanceof z.ZodObject || target instanceof z.ZodRecord) { if (raw === "" || raw === "null") return undefined; try { return JSON.parse(raw); } catch (err) { const detail = err instanceof Error ? err.message : String(err); throw new UsageError(`Invalid JSON for ${key}: ${detail}`, "INVALID_JSON_CONFIG_VALUE"); } } if (target instanceof z.ZodUnion) { // Try each option in order. Use the first that the schema accepts after // coercion. Falls through to JSON parsing if all fail. const options = target.options; // A value that starts like JSON (`["x"]`, `{...}`) is JSON when an option takes an array or object, // even though a string option would also accept the text. const trimmed = raw.trim(); const takesJson = options.some((opt) => { const inner = unwrap(opt); return inner instanceof z.ZodArray || inner instanceof z.ZodObject || inner instanceof z.ZodRecord; }); if (takesJson && (trimmed.startsWith("[") || trimmed.startsWith("{"))) { let json; try { json = JSON.parse(trimmed); } catch (err) { const detail = err instanceof Error ? err.message : String(err); throw new UsageError(`Invalid JSON for ${key}: ${detail}`, "INVALID_JSON_CONFIG_VALUE"); } if (options.some((opt) => opt.safeParse(json).success)) return json; } let lastErr; for (const opt of options) { try { const coerced = coerceForSchema(opt, raw, key); const parsed = opt.safeParse(coerced); if (parsed.success) return parsed.data; lastErr = parsed.error; } catch (err) { lastErr = err; } } if (lastErr instanceof Error) throw new UsageError(`Invalid value for ${key}: ${lastErr.message}`); throw new UsageError(`Invalid value for ${key}: did not match any expected type.`); } if (target instanceof z.ZodNull) { if (raw === "" || raw === "null") return null; throw new UsageError(`Invalid value for ${key}: expected null.`); } // Fallback: try JSON parse, then raw string. if (raw === "" || raw === "null") return undefined; try { return JSON.parse(raw); } catch { return raw; } } // ── Path mutators ─────────────────────────────────────────────────────────── function setPath(config, path, value) { if (path.length === 0) return config; const head = path[0]; // non-empty: guarded by the `path.length === 0` check above const rest = path.slice(1); const next = { ...config }; if (rest.length === 0) { if (value === undefined) { delete next[head]; } else { next[head] = value; } return next; } const existing = next[head]; const child = typeof existing === "object" && existing !== null && !Array.isArray(existing) ? existing : {}; next[head] = setPath(child, rest, value); return next; } function holdsPath(config, path) { let cursor = config; for (const segment of path) { if (!isRecord(cursor) || !(segment in cursor)) return false; cursor = cursor[segment]; } return true; } function unsetPath(config, path) { if (path.length === 0) return config; const head = path[0]; // non-empty: guarded by the `path.length === 0` check above const rest = path.slice(1); const next = { ...config }; if (rest.length === 0) { delete next[head]; return next; } const existing = next[head]; if (typeof existing !== "object" || existing === null || Array.isArray(existing)) { return next; // nothing to unset } next[head] = unsetPath(existing, rest); return next; } // ── Hint generation (#460) ────────────────────────────────────────────────── export function unknownKeyHint() { const keys = listTopLevelConfigKeys(); return `Valid top-level keys: ${keys.join(", ")}. Use dotted paths for nested values (e.g. embedding.endpoint, connections.<name>.endpoint).`; }