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
405 lines (404 loc) • 20.2 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/.
/**
* Reject flags the resolved command does not declare.
*
* citty (0.2.x) parses argv with `node:util`'s parseArgs in non-strict mode
* (`strict: false`), so an undeclared flag is collected into the parsed object
* and silently ignored by the handler. Nothing
* downstream noticed, so `akm lint --fail-on-flaged` (one transposed letter in
* the flag STABILITY.md documents as a CI contract) parsed fine, exited 0, and
* the gate it was meant to enforce never fired. Same for `--limt 3`, `--jsn`,
* and every other typo — the command ran with the default instead, and the user
* had no signal.
*
* This walks the same subcommand path citty resolves (via the shared scan
* helpers in `./invocation`), unions the arg definitions declared along it,
* and fails a flag that matches nothing. The union (rather than the leaf's
* args alone) is deliberate: parent-level flags may legally appear before the
* subcommand token, and a false positive here would reject a VALID invocation
* — much worse than the silence it replaces. In the same spirit, everything
* after a literal `--` is passthrough, a declared value flag's value is never
* scanned as a flag, `--no-<name>` resolves against `<name>`, and a bare `-`
* (stdin convention) and negative numbers are left alone. A subcommand invoked
* by a `meta.name` alias rather than its key takes the stand-down path (no
* validation) — conservative by design.
*
* A positional beyond the ones the command declares is the same silence:
* citty leaves it in `args._`, which no handler reads.
* {@link assertNoStrayPositionals} refuses it from the same command walk.
*/
import { closestMatch } from "../core/closest-match.js";
import { UsageError } from "../core/errors.js";
import { warn } from "../core/warn.js";
import { cittyComparableName, findCittyTopLevelCommandIndex, toAliasArray, } from "./invocation.js";
/**
* Commands that must never refuse on an unrecognized flag or a stray
* positional — `akm info` warns and continues instead of exiting 2, the same
* tolerance a bare `akm help --whatever` already gets for free from its
* group-command fallback (no resolved subcommand, so this gate stands down
* entirely). `info` is a leaf command, so it needs an explicit opt-in here
* instead.
*/
const TOLERANT_COMMANDS = new Set(["info", "doctor info"]);
/** The command a flag scan resolves `path` to, as the root of its tree. */
export function scanRoot(path, command) {
let root = command;
for (const part of [...path].reverse())
root = { subCommands: { [part]: root } };
return root;
}
/** Flags citty implements itself, which no command declares. */
const IMPLICIT_FLAGS = ["help", "h", "version", "v"];
/**
* Union the arg definitions declared along the resolved command path. The
* subcommand walk delegates to {@link findCittyTopLevelCommandIndex} — the
* same scan `src/cli.ts` resolves commands with — so both agree on which
* token is the subcommand name.
*/
function collectKnownArgs(root, rawArgs) {
const names = new Set(IMPLICIT_FLAGS.map(cittyComparableName));
const valueFlags = new Set();
const booleanFlags = new Set();
const displayNames = [];
const path = [];
const inheritedArgs = {};
let cmd = root;
let args = rawArgs;
const known = (resolved) => ({
names,
valueFlags,
booleanFlags,
displayNames,
path,
command: cmd,
commandArgs: args,
resolved,
});
for (;;) {
Object.assign(inheritedArgs, cmd.args);
for (const [key, def] of Object.entries(cmd.args ?? {})) {
// Positionals are not flags; including them would accept `--<positional>`.
if (def.type === "positional")
continue;
const comparable = cittyComparableName(key);
// Shared args (GLOBAL_OUTPUT_ARGS) recur at every level; suggest each once.
if (!names.has(comparable)) {
names.add(comparable);
if (def.hidden !== true)
displayNames.push(`--${key}`);
}
if (def.type === "string" || def.type === "enum")
valueFlags.add(comparable);
if (def.type === "boolean")
booleanFlags.add(comparable);
for (const alias of toAliasArray(def.alias)) {
names.add(cittyComparableName(alias));
if (def.type === "string" || def.type === "enum")
valueFlags.add(cittyComparableName(alias));
if (def.type === "boolean")
booleanFlags.add(cittyComparableName(alias));
}
}
const subCommands = cmd.subCommands;
if (!subCommands || Object.keys(subCommands).length === 0)
break;
const idx = findCittyTopLevelCommandIndex(args, inheritedArgs);
const token = idx >= 0 ? args[idx] : undefined;
// A command that takes a positional AND has subcommands (`improve [scope]`
// beside `improve report`) is itself the target when the token is absent
// or names none of them.
const takesPositional = Object.values(cmd.args ?? {}).some((def) => def.type === "positional");
if (takesPositional && (token === undefined || !subCommands[token]))
break;
// A group with no subcommand token: citty reports "no command specified".
if (token === undefined)
return known(false);
const sub = subCommands[token];
// An unrecognized token: citty reports the unknown command, which is the
// real problem — its flags are beside the point.
if (!sub)
return known(false);
path.push(token);
cmd = sub;
args = args.slice(idx + 1);
}
return known(true);
}
/**
* Consume the startup selector from the invocation's own tokens without interpreting another flag's value as an
* option. `args` is the user tokens without it; the tokens after the boundary are returned as they are.
*/
export function consumeConfigFileFlag(root, invocation) {
const rawArgs = invocation.ownArgs;
const known = collectKnownArgs(root, rawArgs);
// These legacy commands accept arbitrary named inputs, including `config`.
// Only the prefix before the top-level command belongs to the global flag.
const dynamic = new Set(["task run", "task explain", "workflow run", "run"]);
const topLevel = findCittyTopLevelCommandIndex(rawArgs, (root.args ?? {}));
const end = dynamic.has(known.path.join(" ")) && topLevel >= 0 ? topLevel : rawArgs.length;
let selected;
const forwarded = [];
let index = 0;
for (; index < end; index += 1) {
const token = rawArgs[index];
if (token === "--config" || token.startsWith("--config=")) {
const value = token === "--config" ? rawArgs[++index] : token.slice("--config=".length);
if (value === undefined || !value.trim() || (token === "--config" && value.startsWith("-"))) {
throw new UsageError("--config requires a non-empty file path.", "INVALID_FLAG_VALUE");
}
// `setup --config '{...}'` was the retired inline-JSON form: keep its exit 2 and hint.
if (known.path.join(" ") === "setup" && value.trimStart().startsWith("{")) {
throwUnknownFlag("--config", "--config", known);
}
selected = value;
continue;
}
forwarded.push(token);
if (token.startsWith("--")) {
const name = cittyComparableName(token.slice(2).split("=")[0]);
if (!token.includes("=") && known.valueFlags.has(name)) {
const value = rawArgs[++index];
if (value !== undefined)
forwarded.push(value);
}
}
else if (token.startsWith("-") && token !== "-") {
for (let offset = 1; offset < token.length; offset += 1) {
if (known.valueFlags.has(cittyComparableName(token[offset]))) {
if (offset === token.length - 1) {
const value = rawArgs[++index];
if (value !== undefined)
forwarded.push(value);
}
break;
}
}
}
}
return {
file: selected,
args: [...forwarded, ...rawArgs.slice(index), ...invocation.userArgs.slice(rawArgs.length)],
};
}
/**
* Flags STABILITY.md lists under "Gone / Use", checked before edit distance so
* the hint names the real replacement (`--shape` is not a typo of `--type`).
* `commands` limits an entry to those command paths; absent means every command.
*/
const GONE_FLAGS = [
{ flag: "--shape", use: "`--detail agent` (was `--shape agent`) or `--detail brief` (was `--shape summary`)" },
{
flag: "--target",
use: "`--bundle`",
commands: [
"import",
"env create",
"env remove",
"secret set",
"proposal accept",
"proposal diff",
"proposal revert",
],
},
{ flag: "--all", use: "`akm doctor info`", commands: ["config path"] },
{ flag: "--run", use: "`akm doctor metrics improve --run`", commands: ["improve"] },
{ flag: "--since", use: "`akm doctor metrics improve --since`", commands: ["improve"] },
{ flag: "--config", use: "`--endpoint <url> --yes` and the other answer flags", commands: ["setup"] },
{ flag: "--probe", use: "no flag: probing is the default, and `--no-probe` runs offline", commands: ["setup"] },
];
/**
* The one unknown-flag rejection, shared by the short- and long-flag scans so
* the user-facing error contract cannot drift between them. No explicit hint
* when there is no suggestion — UNKNOWN_FLAG's canned hint (core/errors.ts)
* already says to run the command with --help.
*
* @param shown The flag as the user typed it (dashes, no `=value`).
* @param attempted The spelling to edit-distance against `--long` candidates.
*/
function throwUnknownFlag(shown, attempted, known) {
const command = known.path.join(" ");
const gone = GONE_FLAGS.find((entry) => entry.flag === attempted && (!entry.commands || entry.commands.includes(command)));
if (gone) {
throw new UsageError(`Unknown flag "${shown}".`, "UNKNOWN_FLAG", `\`${gone.flag}\` is gone: use ${gone.use}. Run the command with \`--help\` to see its accepted flags.`);
}
const threshold = Math.max(2, Math.ceil(attempted.length / 3));
const suggestion = closestMatch(attempted, known.displayNames, threshold);
throw new UsageError(`Unknown flag "${shown}".`, "UNKNOWN_FLAG", suggestion
? `Did you mean \`${suggestion}\`? Run the command with \`--help\` to see its accepted flags.`
: undefined);
}
/** The {@link TOLERANT_COMMANDS} counterpart to {@link throwUnknownFlag}: report, don't refuse. */
function warnUnknownFlag(shown, known) {
warn(`[akm ${known.path.join(" ")}] ignoring unknown flag "${shown}" — run with --help to see its accepted flags.`);
}
// `run` delegates flag validation to its selected executor.
// `workflow run`, `task run`, and `task explain` each own one deliberately
// dynamic namespace: long options become exact-name parameter/input flags
// and are checked against the frozen plan / task source's own contract
// before this gate would otherwise reject them (task run's
// UNKNOWN_FLAG/INPUT_BINDING_INVALID must be raised from INSIDE the command
// body, where runWithJsonErrors renders the JSON envelope, not from this
// generic pre-dispatch gate; `task explain` reuses the identical
// `parseTaskInputFlags` scanner, so it needs the identical exemption).
const DYNAMIC_INPUT_COMMANDS = new Set([
"workflow run",
"task run",
"task explain",
"doctor explain",
"run",
]);
/** The commands whose tokens after their target (a ref or a task id) are checked by the command, which knows what that target declares. */
const CHECKED_AFTER_TARGET = new Set(["run", "task run", "task explain", "doctor explain"]);
/**
* Throw a {@link UsageError} naming the first flag the resolved command does
* not declare. Returns silently when every flag is known.
*
* `untilTarget` is the pre-dispatch gate's: for {@link CHECKED_AFTER_TARGET} it checks only up to the target, and the
* command checks the rest from inside its body, where a failure is rendered as the command's own error.
*/
export function assertKnownFlags(root, rawArgs, options = {}) {
let ownArgs = rawArgs;
const known = collectKnownArgs(root, rawArgs);
if (!known.resolved)
return;
if (options.untilTarget === true && CHECKED_AFTER_TARGET.has(known.path.join(" "))) {
const target = findCittyTopLevelCommandIndex(known.commandArgs, (known.command.args ?? {}));
if (target >= 0)
ownArgs = ownArgs.slice(0, rawArgs.length - known.commandArgs.length + target + 1);
}
const dynamicWorkflowParams = DYNAMIC_INPUT_COMMANDS.has(known.path.join(" "));
const tolerant = TOLERANT_COMMANDS.has(known.path.join(" "));
for (let i = 0; i < ownArgs.length; i += 1) {
const token = ownArgs[i];
// Not a flag: positional, a bare `-` (stdin), or a negative number.
if (!token.startsWith("-") || token === "-" || /^-\d/.test(token))
continue;
// Node's util.parseArgs, which citty delegates to, treats one-dash tokens
// as bundled short flags. Boolean aliases may be combined (`-qy`), while a
// string alias consumes the remainder (`-mhello`) or the following token.
// It never treats `-auto-fix` as the long `auto-fix` option.
if (!token.startsWith("--")) {
const shortFlags = token.slice(1);
for (let offset = 0; offset < shortFlags.length; offset += 1) {
const rawName = shortFlags[offset];
const candidate = cittyComparableName(rawName);
if (!known.names.has(candidate)) {
if (tolerant) {
warnUnknownFlag(token, known);
break;
}
throwUnknownFlag(token, `-${rawName}`, known);
}
if (known.valueFlags.has(candidate)) {
if (offset === shortFlags.length - 1)
i += 1;
break;
}
}
continue;
}
const withoutDashes = token.replace(/^-{1,2}/, "");
const [rawName = ""] = withoutDashes.split("=", 1);
const hasInlineValue = withoutDashes.includes("=");
// `--no-foo` is citty's negation of the BOOLEAN `--foo`. Resolving it
// against a value flag would accept `--no-limit`, which citty's own `--no-`
// preprocessing force-sets to `limit: false` (no type check, before
// parseArgs runs) — a boolean reaching a string parser, i.e. an internal
// error (exit 70) instead of the usage error (exit 2) this is here to give.
const negated = rawName.startsWith("no-") && known.booleanFlags.has(cittyComparableName(rawName.slice(3)))
? rawName.slice(3)
: undefined;
const candidates = [cittyComparableName(rawName), ...(negated ? [cittyComparableName(negated)] : [])];
if (!candidates.some((name) => known.names.has(name))) {
// `workflow run` owns one deliberately dynamic namespace: long options
// become exact-name workflow parameters and are checked against the
// frozen plan before a run is inserted. Short flags remain strict.
if (dynamicWorkflowParams)
continue;
if (tolerant) {
warnUnknownFlag(token.split("=")[0], known);
continue;
}
throwUnknownFlag(token.split("=")[0], `--${rawName}`, known);
}
// Skip a declared value flag's value so `--reason "--x"` is not scanned.
if (!hasInlineValue && candidates.some((name) => known.valueFlags.has(name)))
i += 1;
}
}
/** The flag that takes the value, for a command where a positional is an easy mistake for it. */
const POSITIONAL_FLAG = { "bundle create": "--dir", setup: "--dir" };
/**
* Commands whose handler reads `args._` itself: `proposal accept` and
* `proposal reopen` take any number of ids, `migrate apply` and `migrate status` any number of task and workflow
* files, and `show` and `doctor prompt`
* refuse an extra token with a message of their own.
*/
const OWN_POSITIONALS = new Set([
"proposal accept",
"proposal reopen",
"migrate apply",
"migrate status",
"show",
"doctor prompt",
]);
/** Commands whose `--` tail is the child command to run, not positionals of their own. */
const CHILD_COMMAND_TAIL = new Set(["exec", "env run", "secret run"]);
/** The tokens citty collects as positionals: neither a flag nor the value of a declared value flag. */
function positionalsIn(args, valueFlags) {
const found = [];
for (let i = 0; i < args.length; i += 1) {
const token = args[i];
if (!token.startsWith("-") || token === "-") {
found.push(token);
continue;
}
if (token.includes("="))
continue;
// `--name value`, `-n value`, or a short bundle whose last letter takes the value.
const letters = token.startsWith("--") ? [token.slice(2)] : [...token.slice(1)];
const taking = letters.findIndex((letter) => valueFlags.has(cittyComparableName(letter)));
if (taking !== -1 && taking === letters.length - 1)
i += 1;
}
return found;
}
/**
* Throw a {@link UsageError} when argv carries more positionals than the
* resolved command declares: `akm bundle create /some/folder` ran as a bare
* `akm bundle create` and initialized the default bundle, and
* `akm search deploy script` searched for "deploy".
*/
export function assertNoStrayPositionals(root, rawArgs) {
const known = collectKnownArgs(root, rawArgs);
if (!known.resolved)
return;
// `akm help <command> <subcommand>` prints the command's help.
if (known.path[0] === "help")
return;
const command = known.path.join(" ");
// A dynamic input's value (`--scope all`) is not a positional, and only the command knows its inputs.
if (DYNAMIC_INPUT_COMMANDS.has(command) || OWN_POSITIONALS.has(command))
return;
const declared = Object.values(known.command.args ?? {}).filter((def) => def.type === "positional").length;
const separator = known.commandArgs.indexOf("--");
const given = positionalsIn(separator === -1 ? known.commandArgs : known.commandArgs.slice(0, separator), known.valueFlags);
// After `--` every token is a positional, which citty assigns like any other (`akm bundle remove -- <name>`).
if (separator !== -1 && !CHILD_COMMAND_TAIL.has(command))
given.push(...known.commandArgs.slice(separator + 1));
if (given.length <= declared)
return;
const got = given.map((token) => `"${token}"`).join(" ");
if (TOLERANT_COMMANDS.has(command)) {
warn(`[akm ${command}] ignoring positional argument ${got} — it takes none.`);
return;
}
const help = `Run \`akm ${command} --help\` to see what it accepts.`;
if (declared === 0) {
const flag = POSITIONAL_FLAG[command];
throw new UsageError(`akm ${command} takes no positional arguments, but got ${got}.`, "INVALID_FLAG_VALUE", flag ? `Pass it with \`${flag}\`: \`akm ${command} ${flag} ${given[0]}\`.` : help);
}
throw new UsageError(`akm ${command} takes ${declared} positional argument${declared === 1 ? "" : "s"}, but got ${given.length}: ${got}.`, "INVALID_FLAG_VALUE", `Quote a value that contains spaces. ${help}`);
}