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
189 lines (188 loc) • 9.98 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/.
/**
* Contribution command cluster (`akm agent`, `akm lint`) — the asset
* authoring / validation verbs.
*
* These handlers branch on the result and set a non-zero `process.exitCode`
* conditionally (exit 1 on a failed dispatch, or on `--fail-on-flagged` lint
* findings) rather than emitting through the thrown-error path, so they keep
* the inline `runWithJsonErrors` form rather than migrating to
* `defineJsonCommand` (which is reserved for plain runWithJsonErrors+output
* handlers). `process.exitCode` (not `process.exit()`) so the process still
* exits via natural event-loop drain rather than skipping pending cleanup.
*
* Asset authoring is `akm proposal new` (src/commands/proposal/propose-cli.ts).
*/
import fs from "node:fs";
import { defineCommand } from "citty";
import { getExactStringArg, getStringArg, parseNonNegativeIntFlag, parsePositiveIntFlag, parseTimeoutFlags, } from "../../cli/parse-args.js";
import { RETIRED_ENGINE_ARG, SELECTION_ARGS, selectionFromArgs } from "../../cli/selection.js";
import { failResult, GLOBAL_OUTPUT_ARGS, output, runWithJsonErrors } from "../../cli/shared.js";
import { loadConfig } from "../../core/config/config.js";
import { agentFailureCode, UsageError } from "../../core/errors.js";
import { retryDispatch } from "../../execution/retry.js";
import { getHyphenatedBoolean } from "../../output/context.js";
import { akmLint } from "../lint/index.js";
import { akmAgentDispatch } from "./agent-dispatch.js";
// asset-io: user-input stdin
export function readPromptStdin(read = () => fs.readFileSync(0, "utf8")) {
return read();
}
export const agentCommand = defineCommand({
meta: {
name: "agent",
description: "Deprecated, removed in 0.11: use `akm run <ref>` for agent assets, or the agent's own CLI. Dispatch an agent CLI (opencode, claude, …) with an optional agent persona and model defaults. Use --prompt for work; without one the harness starts interactively. Stored commands run through akm command run.",
},
args: {
...GLOBAL_OUTPUT_ARGS,
"agent-ref": {
type: "positional",
description: "Agent asset ref (e.g. agents/code-reviewer)",
required: false,
},
prompt: { type: "string", description: "Task prompt to pass to the agent" },
"prompt-stdin": {
type: "boolean",
description: "Read the task prompt from stdin (mutually exclusive with --prompt)",
default: false,
},
...SELECTION_ARGS,
...RETIRED_ENGINE_ARG,
model: {
...SELECTION_ARGS.model,
description: `${SELECTION_ARGS.model.description}. Overrides the model specified in the agent asset.`,
},
timeout: {
type: "string",
description: "Timeout as a duration (30s, 2m) or milliseconds",
},
"timeout-ms": {
type: "string",
description: "Deprecated: use `--timeout`. Override the agent CLI timeout in milliseconds",
},
"max-retries": { type: "string", hidden: true, description: "Run again up to N times when the agent fails" },
cwd: {
type: "string",
description: "Working directory for the spawned agent (defaults to the current directory)",
},
},
async run({ args }) {
await runWithJsonErrors(async () => {
const timeoutMs = parseTimeoutFlags(args.timeout, parsePositiveIntFlag(args["timeout-ms"], "--timeout-ms"));
const config = loadConfig();
const agentConfig = config;
// Preserve the selector; the common execution-source adapter resolves it.
const agentRef = getStringArg(args, "agent-ref");
const promptText = getExactStringArg(args, "prompt");
const promptStdin = args["prompt-stdin"] === true;
if (promptStdin && promptText !== undefined) {
throw new UsageError("--prompt-stdin cannot be combined with --prompt.", "INVALID_FLAG_VALUE");
}
const cwd = getStringArg(args, "cwd");
// The common invocation resolver loads a selected agent through its
// owning bundle adapter. This CLI never re-reads/show-projects the file.
const selection = selectionFromArgs(args);
const stdinPrompt = promptStdin ? readPromptStdin() : undefined;
const result = await retryDispatch(parseNonNegativeIntFlag(getExactStringArg(args, "max-retries"), "--max-retries") ?? 0, () => akmAgentDispatch({
prompt: stdinPrompt ?? promptText,
...(agentRef === undefined ? {} : { agentRef }),
agentConfig,
...(Object.keys(selection).length === 0 ? {} : { selection }),
...(cwd ? { cwd } : {}),
...(timeoutMs !== undefined && Number.isFinite(timeoutMs) ? { timeoutMs } : {}),
}));
output("agent-result", result);
if (!result.ok) {
// Set `process.exitCode` and return rather than calling
// `process.exit(EXIT_GENERAL)`, which would skip pending
// `finally`/cleanup up the call stack (including the dispatched agent
// process' own bookkeeping). `output()` has already run above, so the
// process can exit naturally once the event loop drains.
failResult(agentFailureCode(result.reason));
return;
}
});
},
});
export const lintCommand = defineCommand({
meta: {
name: "lint",
description: "Scan bundle .md files for structural issues (unquoted colons, missing updated field, orphaned stubs, placeholder stubs, missing name/type, stale paths (paths the agent can find and correct; `--rule stale-path` lists them), tracked secrets, broken refs in body text and in refs/xrefs/supersededBy/contradictedBy frontmatter). Takes one file (`akm lint <file>`) or the whole bundle. Use --fix to auto-fix Tier 1 issues. Exits 0 on success regardless of findings; use --fail-on-flagged for CI fail-on-finding behavior.",
},
args: {
// `lint` is a raw `defineCommand` (not `defineJsonCommand`), so it
// does not get `GLOBAL_OUTPUT_ARGS` for free. `--format`/`--detail`/
// `--output` already parsed correctly here (this command has no
// positional for a stray value to fall into), so this is purely a
// `--help` visibility / consistency fix, not a behavior change.
...GLOBAL_OUTPUT_ARGS,
fix: {
type: "boolean",
description: "Apply auto-fixes in place",
default: false,
},
// Declared as its own arg rather than `alias: "auto-fix"`: citty's alias
// handling (node:util parseArgs `short` options) only supports
// SINGLE-character aliases. A
// multi-char alias rendered in help as `-auto-fix` (one dash) and parsed
// as a pile of junk single-char flags, so BOTH advertised spellings —
// `-auto-fix` and `--auto-fix` — silently ran a plain lint while claiming
// to fix. Two real boolean args, OR'd at the call site, work and render.
"auto-fix": {
type: "boolean",
description: "Deprecated: use `--fix`. Apply auto-fixes in place",
default: false,
},
file: {
type: "positional",
description: "Lint just this file (e.g. `akm lint ./nightly.yml --type tasks`); needs --type when it is outside every bundle",
required: false,
},
dir: { type: "string", description: "Override bundle root directory (default: from config)" },
"fail-on-flagged": {
type: "boolean",
description: "Exit non-zero when summary.flagged > 0 (CI)",
default: false,
},
// #884: NOT folded into `--fix`. Every other auto-fix repairs a structural
// defect in the file it edits; this one DELETES an assertion the user (or
// the improve pipeline) made about the belief graph, and it does so in
// files that are themselves perfectly well-formed. That is a data decision,
// so it stays opt-in behind its own flag even when `--fix` is present.
"prune-dangling-edges": {
type: "boolean",
description: "Drop supersededBy/contradictedBy entries whose target is gone (modifies memories)",
default: false,
},
type: {
type: "string",
description: "Only lint assets of this type (akm bundles only; e.g. skills, tasks); with a file, its type",
default: undefined,
},
rule: {
type: "string",
description: "List the findings of this rule grouped by asset (e.g. stale-path); cannot combine with --fix",
default: undefined,
},
},
async run({ args }) {
await runWithJsonErrors(async () => {
const result = await akmLint({
fix: args.fix === true || getHyphenatedBoolean(args, "auto-fix"),
dir: getStringArg(args, "dir"),
file: getStringArg(args, "file"),
typeFilter: getStringArg(args, "type"),
rule: getStringArg(args, "rule"),
pruneDanglingEdges: getHyphenatedBoolean(args, "prune-dangling-edges"),
stores: getStringArg(args, "dir") === undefined && getStringArg(args, "file") === undefined,
});
output("lint", result);
if (args["fail-on-flagged"] && result.summary.flagged > 0) {
failResult("LINT_FLAGGED");
return;
}
});
},
});