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

352 lines (351 loc) • 16.5 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/. /** * Shared CLI utilities extracted from `src/cli.ts` so that individual * command modules can import them without a circular dependency. * * Exported: output, runWithJsonErrors, parseAllFlagValues, emitJsonError, reportChildExit */ import { defineCommand } from "citty"; import { stringify as yamlStringify } from "yaml"; import { assertNever } from "../core/assert.js"; import { AkmError, UsageError } from "../core/errors.js"; import { getOutputMode } from "../output/context.js"; import { renderGenericMarkdown, renderGenericText } from "../output/generic-render.js"; import { getMdRendererHandler } from "../output/render-registry.js"; import { shapeForCommand } from "../output/shapes.js"; import { deliverRendered } from "../output/stdout.js"; import { formatPlain, outputJsonl } from "../output/text.js"; import { parseAllFlagValues } from "./invocation.js"; import { hasSubcommand } from "./parse-args.js"; import { setUsageChildExit, setUsageError, setUsageErrorCode } from "./usage-kinds.js"; export { parseAllFlagValues }; // ── Exit codes ─────────────────────────────────────────────────────────────── /** * Canonical process exit-code table for the akm CLI. Single source of truth — * referenced by `classifyExitCode` here and re-imported by `src/cli.ts` so the * health-warn / general-failure paths stay in sync. * * 0 success * 1 general / not-found * 2 usage error * 4 health warn (doctor or health command) * 70 internal / unclassified (sysexits EX_SOFTWARE — akm threw unexpectedly) * 75 transient (sysexits EX_TEMPFAIL — retry shortly; another akm process * holds a lock or is writing state.db right now, not a bad command line) * 78 config error */ export const EXIT_CODES = { SUCCESS: 0, GENERAL: 1, USAGE: 2, HEALTH_WARN: 4, // sysexits.h EX_SOFTWARE. Distinct from GENERAL(1) so scripts can tell an // expected "not found" outcome from akm itself throwing an unexpected error. INTERNAL: 70, // sysexits.h EX_TEMPFAIL (#948 addendum). Distinct from USAGE(2): a // scheduler or cron wrapper classifies 2 as "fix the command line", but a // TransientError means "try again in a few seconds" — a different retry // contract callers can branch on. TEMPFAIL: 75, CONFIG: 78, }; // ── Helpers ────────────────────────────────────────────────────────────────── /** * Map a thrown value to a process exit code. * * Known, classified errors (instances of `AkmError`) are dispatched through an * exhaustive switch on the `kind` discriminant — `assertNever` makes a missing * case a compile-time error, so adding a new error class can't silently inherit * the wrong code. Anything that is NOT an `AkmError` is treated as a genuinely * unexpected internal failure and maps to INTERNAL(70) rather than GENERAL(1), * so callers can distinguish "akm threw" from a normal not-found outcome. */ function classifyExitCode(error) { if (!(error instanceof AkmError)) return EXIT_CODES.INTERNAL; switch (error.kind) { case "usage": return EXIT_CODES.USAGE; case "config": return EXIT_CODES.CONFIG; case "not-found": return EXIT_CODES.GENERAL; case "transient": return EXIT_CODES.TEMPFAIL; default: return assertNever(error.kind, "classifyExitCode"); } } function extractHint(error) { if (error instanceof Error && "hint" in error && typeof error.hint === "function") { return error.hint(); } return undefined; } /** * Serialize an error to the standard JSON envelope and record the mapped * exit code. Used in both the startup try/catch and `runWithJsonErrors`. * * This sets `process.exitCode = exitCode` and returns rather than calling * `process.exit(exitCode)`: Node/Bun exits with that code once the event loop * drains, so every pending `finally` block (`src/cli.ts`'s * `disposeLlmUsageSink()` cleanup, citty's per-command `cleanup` hooks) still * runs. `src/commands/improve/extract-cli.ts` uses the same pattern. * * Because this neither throws nor exits, it does not terminate control * flow on its own — every call site MUST treat it like a normal return and * stop doing further work itself (an explicit `return;` right after the * call, same as any other caller of a fallible function). `runWithJsonErrors` * below satisfies this for free (this call is its catch block's last * statement); `src/cli.ts`'s three direct call sites add the `return;` * explicitly. */ export function emitJsonError(error) { const message = error instanceof Error ? error.message : String(error); const hint = extractHint(error); const exitCode = classifyExitCode(error); // Classified akm errors carry a stable machine-readable `code`; unexpected // internal errors have none. const code = error instanceof AkmError ? error.code : undefined; console.error(JSON.stringify({ ok: false, error: message, ...(code ? { code } : {}), hint }, null, 2)); process.exitCode = exitCode; setUsageError(error); } /** * End a command that reports a failed result rather than throwing: exit 1, and record `code`, why it failed, for the * usage report. The caller has already printed the result. */ export function failResult(code) { process.exitCode = EXIT_CODES.GENERAL; setUsageErrorCode(code); } /** * Make a child's status akm's exit code. A failure already recorded (a signal owner's handler, an earlier error) * is kept: a later result never turns a failure into success. 0 counts as no failure, as an unset code does. */ export function reportChildExit(code) { if (process.exitCode) return; process.exitCode = code; setUsageChildExit(code); } /** * A Deprecated mount of a command whose replacement mounts the same definition: help for this one says it is * Deprecated and names `use`, and the usage report counts it as Deprecated (src/cli/usage.ts `deprecatedUse`). */ export function deprecatedMount(command, use) { const meta = command.meta; return { ...command, meta: { ...meta, description: `Deprecated, removed in 0.11: use ${use}. ${meta?.description ?? ""}` }, }; } /** * Run an async function and route any thrown error through the standard JSON * error envelope so users never see a raw stack trace. */ export async function runWithJsonErrors(fn) { try { await fn(); } catch (error) { emitJsonError(error); } } /** * The global output flags, redeclared on every leaf command. * * citty parses each command level against only that command's own args, so a * flag declared on the root command is UNKNOWN at the leaf — and an unknown * flag does not consume its space-separated value, which then falls through as * a positional. `akm sync --format json` once synced a bundle named "json", * and `akm env unset env:x KEY --format json` once tried to unset a key named * "json"; both grew bespoke argv-inspection workarounds. Declaring the flags * at the leaf lets the parser consume the value, which is the root-cause fix. * * These declarations exist for PARSING only. The output mode is still read * exactly once, from the invocation singleton at startup — no command body may * read these args (that is the same one-parse rule `cli/invocation.ts` * documents). * * These are also the canonical descriptions for the root command's own args * (`main.args` in src/cli.ts) — the root spreads this same object rather than * redeclaring the text, so root help and leaf help can never drift apart. * `format`/`detail` need per-site `default` overrides (root has one, leaves * don't — see the one-parse rule above), so those two keys get shallow * overrides at the root; the description text itself is never duplicated. */ export const GLOBAL_OUTPUT_ARGS = { config: { type: "string", description: "Use this config file (also AKM_CONFIG_FILE)" }, format: { type: "string", description: "Output format: json|jsonl|yaml|text|md" }, detail: { type: "string", description: "Detail level: brief|normal|full, or agent (trims search, curate and show to essential fields)", }, output: { type: "string", description: "Write output to a file instead of stdout (not jsonl)" }, // These flags are declared at every leaf so a command's flags parse wherever they sit; // leaf `--help` prints them once as a pointer (see `withoutGlobalArgs`), root // `--help` lists them in full. They are parsed from raw argv by // `applyEarlyStderrFlags` in src/cli.ts before citty ever sees them. A // command with its own same-named arg (e.g. `env path --quiet`) wins the // merge in `defineJsonCommand` as usual. quiet: { type: "boolean", alias: "q", description: "Suppress non-essential stderr output; errors and confirmation prompts always show", default: false, }, verbose: { type: "boolean", description: "Print diagnostics to stderr", default: false, }, }; /** * A command with the args `--help` does not list left out. A hidden arg parses * like any other and is simply not advertised, the way `meta.hidden` keeps a * command out of the COMMANDS list (it is for a retired spelling that still * works, so a scheduled command written for an earlier release keeps running). * An arg that is still the shared {@link GLOBAL_OUTPUT_ARGS} definition is left * out too: leaf help points at `akm --help` instead of repeating it. A command's * own same-named arg stays. */ export function withoutHelpHiddenArgs(command) { const args = command.args; if (!args) return command; const globals = GLOBAL_OUTPUT_ARGS; return { ...command, args: Object.fromEntries(Object.entries(args).filter(([key, def]) => def.hidden !== true && globals[key] !== def)), }; } /** * Define a citty command whose `run` body is automatically wrapped in * `runWithJsonErrors`, so the handler emits a byte-identical JSON error * envelope (stdout/stderr/exit-code) on throw without the boilerplate. A * command without a `run` (a pure subcommand group) is passed through * unchanged. * * Every command defined here also accepts the {@link GLOBAL_OUTPUT_ARGS} so * their values are parsed rather than mis-captured as positionals; a command * declaring its own arg of the same name wins (e.g. `env path` has its own * `quiet`). */ export function defineJsonCommand(def) { const { run, configFile, ...rest } = def; // Dynamic task/workflow inputs already own `--config` after the command. const { config, ...dynamicGlobals } = GLOBAL_OUTPUT_ARGS; const globals = configFile === false ? dynamicGlobals : { config, ...dynamicGlobals }; const withGlobals = { ...rest, args: { ...globals, ...rest.args } }; if (!run) return defineCommand(withGlobals); return defineCommand({ ...withGlobals, run: (context) => runWithJsonErrors(() => run(context)), }); } /** * Canonical bare-group behavior (owner ruling 12): a bare group with no * listing (`task`, `migrate`, `command`) is a USAGE ERROR — exit 2 with the * structured JSON envelope. Groups with a read-only `list` never reach this: * `insertBareListSubcommand` (src/cli.ts) rewrites their bare form to * `<group> list`. `defaultRun` is optional; omitting it opts a group into * this error. */ function bareGroupUsageError(meta, subcommandSet) { const name = typeof meta === "object" && meta !== null && "name" in meta && typeof meta.name === "string" ? meta.name : undefined; const usage = name ? `\`akm ${name}\`` : "This command"; const subcommands = [...subcommandSet].sort().join(", "); throw new UsageError(`${usage} requires a subcommand. Available: ${subcommands}.`, "MISSING_REQUIRED_ARGUMENT", `Run \`akm ${name ?? "<command>"} --help\` to see usage for each subcommand.`); } /** * Define a citty subcommand-group command (env, secret, proposal, tasks, wiki, * …) that shares one wiring shape: a `subCommands` map, a routing set * DERIVED from that map's keys (so the set can never silently desync from the * registered subcommands), and a default body that fires ONLY for the bare * group invocation — citty still runs the group body after dispatching a * subcommand, so the shared guard short-circuits when `args._[0]` names a * registered subcommand. * * The `defaultRun` body is wrapped in `runWithJsonErrors`, so it emits a * byte-identical JSON error envelope on throw — exactly the per-site * `run() { return runWithJsonErrors(() => { if (hasSubcommand(...)) return; … }); }` * boilerplate this replaces. */ export function defineGroupCommand(def) { const subcommandSet = new Set(Object.keys(def.subCommands)); const defaultRun = def.defaultRun ?? (() => bareGroupUsageError(def.meta, subcommandSet)); return defineCommand({ meta: def.meta, ...(def.args ? { args: def.args } : {}), subCommands: def.subCommands, run: (context) => runWithJsonErrors(() => { if (hasSubcommand(context.args, subcommandSet)) return; return defaultRun(context); }), }); } /** * Render a command result according to the active output mode * (json/jsonl/yaml/text/md). When `--output <path>` is set, the rendered * document is written to that file instead of stdout (jsonl excepted — it is * a line-streaming protocol and always goes to stdout). */ /** * Emit a result whose success is graded by an exit code. `ok` on the envelope * and `process.exitCode` are set from the same value here, so the two cannot * disagree (#918); `exitCode` undefined or 0 means success. A failure records * `code`, why it failed, for the usage report. */ export function outputWithExitCode(command, result, exitCode, code) { const failed = exitCode !== undefined && exitCode !== EXIT_CODES.SUCCESS; output(command, { ...result, ok: !failed }); if (!failed) return; process.exitCode = exitCode; setUsageErrorCode(code); } export function output(command, result) { const mode = getOutputMode(); const { format } = mode; if (format === "jsonl") { outputJsonl(command, shapeForCommand(command, result, mode.detail, mode.shape)); return; } deliverRendered(renderOutput(command, result, { ...mode, format }), mode.outputPath); } /** * Shape and render a command result into the document `output()` delivers. * Pure: reads no process-level output mode and writes nothing, so in-process * callers (`src/api.ts`) get text byte-identical to the CLI's stdout from an * explicit `mode`. */ export function renderOutput(command, result, mode) { const shaped = shapeForCommand(command, result, mode.detail, mode.shape); switch (mode.format) { case "json": return JSON.stringify(shaped, null, 2); case "yaml": return yamlStringify(shaped); case "text": // D7 — registry first, generic rendering of the shaped envelope second. // A command with no registered text formatter gets generic text, never JSON // under `--format text`. `renderGenericText` renders flat // `key=value` text matching the house style of registered formatters // like `config list`; it is a DISTINCT function from // `renderGenericMarkdown` (see src/output/generic-render.ts). return formatPlain(command, shaped, mode.detail) ?? renderGenericText(command, shaped); case "md": // D7 — registry first, generic rendering second; no command emits JSON // under `--format md`. return getMdRendererHandler(command)?.(shaped, mode.detail) ?? renderGenericMarkdown(command, shaped); } } // parseAllFlagValues moved to ./invocation (argv normalization); re-exported above so every existing importer of this module is // unaffected.