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

250 lines (249 loc) • 11.4 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/. /** * How a recorded invocation is classified, for usage capture (src/cli/usage.ts) and the daily usage report * (src/cli/usage-report.ts) alike: its event source, the error code it failed with, which outcomes are failures, and * which commands and flags akm's own definitions mark Deprecated. */ import os from "node:os"; import { AKM_ERROR_CODES, AkmError } from "../core/errors.js"; import { resolveAgentIdentity } from "../workflows/runtime/agent-identity.js"; /** What an outcome calls an exit code. Any other code is "failure", a signal is "cancelled" and a program's is "child". */ export const EXIT_CATEGORIES = { 0: "success", 1: "general", 2: "usage", 4: "health-warning", 70: "internal", 75: "transient", 78: "config", }; let errorCode; /** The `code` of the error the command failed with (`emitJsonError`); a code outside akm's own closed list is not kept. */ export function setUsageErrorCode(code) { if (code !== undefined && AKM_ERROR_CODES.has(code)) errorCode = code; } let childExit; /** * akm ends with the exit code of a program it ran (`akm run <script>`, `akm exec`, `env run`, a task's process): a * failure of that program, counted as `child` rather than as akm's own exit class. */ export function setUsageChildExit(code) { childExit = code; } const ERROR_CLASSES = new Set(["Error", "TypeError", "RangeError", "SyntaxError", "ReferenceError", "EvalError"]); for (const name of ["URIError", "AggregateError", "AbortError", "TimeoutError"]) ERROR_CLASSES.add(name); /** SQLite's primary result codes, by number (an extended code's low byte). */ const SQLITE_CODES = ["ERROR", "INTERNAL", "PERM", "ABORT", "BUSY", "LOCKED", "NOMEM", "READONLY", "INTERRUPT"] .concat(["IOERR", "CORRUPT", "NOTFOUND", "FULL", "CANTOPEN", "PROTOCOL", "EMPTY", "SCHEMA", "TOOBIG"]) .concat(["CONSTRAINT", "MISMATCH", "MISUSE", "NOLFS", "AUTH", "FORMAT", "RANGE", "NOTADB", "NOTICE", "WARNING"]) .map((name) => `SQLITE_${name}`); const ERRNO_NAMES = new Set(Object.keys(os.constants.errno)); /** * Why an error akm did not classify happened, from closed lists only, never its message: the system error (`ENOENT`), * SQLite's primary result code (`SQLITE_BUSY`, from Bun's code or Node's number), else the JavaScript error class * (`TypeError`), else `other`. */ export function crashCause(error) { const { code, errcode } = (typeof error === "object" && error !== null ? error : {}); if (typeof code === "string" && ERRNO_NAMES.has(code)) return code; const sqlite = typeof code === "string" ? SQLITE_CODES.find((name) => code === name || code.startsWith(`${name}_`)) : undefined; if (sqlite) return sqlite; if (code === "ERR_SQLITE_ERROR" && typeof errcode === "number") return SQLITE_CODES[(errcode & 0xff) - 1] ?? "other"; return error instanceof Error && ERROR_CLASSES.has(error.name) ? error.name : "other"; } /** * Keep what usage may know of the error a command failed with: an akm error's code; for any other error (a crash) its * cause, and, when it escaped every command's handling, whether as an uncaught exception or an unhandled rejection. */ export function setUsageError(error, escaped) { if (error instanceof AkmError) setUsageErrorCode(error.code); else noteUsage(`cause_${crashCause(error)}`, ...(escaped ? [`crash_${escaped}`] : [])); } const PLUGIN_HARNESSES = ["claude-code", "codex", "opencode", "opencode-v2"]; const PLUGIN_OUTCOMES = [ "updated", "current", "skipped", "deferred", "failed", "pending", "unknown", ]; const MIGRATION_STATUSES = ["current", "ready", "blocked", "failed"]; const INSTALL_METHODS = [ "binary", "bun", "npm", "pnpm", "package-local", "unknown", ]; /** * What a command may add to its outcome, each counted in the daily usage report under its own name: every one is * built from akm's own closed lists. `results_none`: a search or curate that found nothing. From `akm upgrade`: * `upgraded`, `install_<method>`, `migration_<status>` and `plugin_<harness>_<outcome>`. From a crash: * `cause_<cause>` ({@link crashCause}) and `crash_uncaught` or `crash_unhandled`. */ export const USAGE_NOTES = new Set([ "results_none", "upgraded", ...INSTALL_METHODS.map((method) => `install_${method}`), ...MIGRATION_STATUSES.map((status) => `migration_${status}`), ...PLUGIN_HARNESSES.flatMap((harness) => PLUGIN_OUTCOMES.map((outcome) => `plugin_${harness}_${outcome}`)), ...[...ERRNO_NAMES, ...SQLITE_CODES, ...ERROR_CLASSES, "other"].map((cause) => `cause_${cause}`), "crash_uncaught", "crash_unhandled", ]); let notes = new Set(); /** Add notes to the running command's outcome; a name outside {@link USAGE_NOTES} is not kept. */ export function noteUsage(...names) { for (const name of names) if (USAGE_NOTES.has(name)) notes.add(name); } /** What `akm upgrade` came to, as notes: whether akm was upgraded, how it is installed, the migration, each plugin. */ export function noteUpgrade(result) { if (result.upgraded) noteUsage("upgraded"); noteUsage(`install_${result.installMethod}`); if (result.migration) noteUsage(`migration_${result.migration.status}`); for (const plugin of result.plugins) noteUsage(`plugin_${plugin.harness}_${plugin.outcome}`); } /** * How the command ended, with the error code and notes set since the last take, all cleared: usage capture reads them * once, when the command finishes with `exitCode` or a signal. A success never keeps the code of an error the command * recovered from. */ export function takeUsageOutcome(exitCode = 0, signal) { const category = signal ? "cancelled" : exitCode !== 0 && exitCode === childExit ? "child" : (EXIT_CATEGORIES[exitCode] ?? "failure"); const taken = { category, code: category === "success" ? undefined : errorCode, notes: [...notes].sort() }; errorCode = undefined; childExit = undefined; notes = new Set(); return taken; } /** * The outcome an aggregate counts: `<category>:<exit code>:<asset type, or "unresolved">`, then `:<error code>` when * there was one, then `:<notes>` joined by `+` when the command added any (with an empty error code when it had none). */ export function outcomeKey(category, exitCode, type, code, added = []) { const key = `${category}:${exitCode}:${type}${code || added.length ? `:${code ?? ""}` : ""}`; return added.length ? `${key}:${added.join("+")}` : key; } /** Every flag name akm declares anywhere in its command tree, aliases included. */ const declaredFlagCache = new WeakMap(); export function declaredFlags(root) { const cached = declaredFlagCache.get(root); if (cached) return cached; const names = new Set(); const walk = (node) => { for (const [name, definition] of Object.entries(node.args ?? {})) { if (definition.type === "positional") continue; names.add(name); for (const alias of [definition.alias ?? []].flat()) names.add(alias); } for (const sub of Object.values(node.subCommands ?? {})) walk(sub); }; walk(root); declaredFlagCache.set(root, names); return names; } /** * How an unknown long flag is spelled in the usage record: `--<name>` when akm declares a flag of that name on some * other command (typed on the wrong one), else `[redacted]`, since an unknown spelling can carry anything. An * `assetInput` (a flag after `akm run <ref>` and the like) is the asset's own input, never named. */ export function unknownFlagSpelling(root, spelling, assetInput) { return !assetInput && declaredFlags(root).has(spelling) ? `--${spelling}` : "[redacted]"; } /** * The categories that are not failures: a success, a health warning (exit 4) and a cancellation (a signal). A program * akm ran that failed (`child`) is the command's failure. */ const NOT_FAILURES = new Set(["success", "health-warning", "cancelled"]); /** Whether an outcome category counts as a failure: every error category, and an exit code akm does not name. */ export function isFailureCategory(category) { return !NOT_FAILURES.has(category); } /** A run the scheduler started: `akm task dispatch`, or `akm run --scheduled` (an earlier row's `akm task run --scheduled`). */ function scheduledRun(usage) { const command = usage.command.join(" "); if (command === "task dispatch") return true; return ((command === "run" || command === "task run") && usage.arguments.some((a) => a.name === "scheduled" && a.explicit && a.value === true)); } export const CLI_USAGE_SOURCES = new Set(["user", "agent", "task", "improve", "audit", "unknown"]); /** * An explicit `AKM_EVENT_SOURCE` wins; otherwise a run the scheduler started is "task", a detected agent harness is * "agent", a terminal with no harness (`terminal`) is "user", and anything else (a pipe, a script, a harness akm does * not know) is "unknown". */ export function resolveCliUsageSource(env, terminal = false, usage) { const explicit = env.AKM_EVENT_SOURCE ?? ""; if (CLI_USAGE_SOURCES.has(explicit)) return explicit; if (usage && scheduledRun(usage)) return "task"; if (resolveAgentIdentity(env).harness) return "agent"; return terminal ? "user" : "unknown"; } /** Whether a definition's own description marks it Deprecated, as its help prints it. */ function markedDeprecated(description) { return typeof description === "string" && /^Deprecated\b/.test(description); } /** * The Deprecated parts of a command as it was typed, from akm's own definitions: `command` when the typed command or * a parent of it is marked Deprecated, and `flags`, the names of the Deprecated flags given explicitly. */ export function deprecatedUse(root, typed, args) { const flags = new Map(Object.entries(root.args ?? {})); let command = false; let node = root; for (const token of typed) { const next = Object.hasOwn(node.subCommands ?? {}, token) ? node.subCommands?.[token] : undefined; if (!next) break; node = next; command ||= markedDeprecated(node.meta?.description); for (const [name, definition] of Object.entries(node.args ?? {})) flags.set(name, definition); } const used = new Set(); for (const argument of args) { if (argument.explicit && markedDeprecated(flags.get(argument.name)?.description)) used.add(argument.name); } return { command, flags: [...used] }; } /** * What an invocation's detail carries and its aggregate never does, so the daily report cannot read it: the ref of * the task it ran in (`AKM_TASK_REF`), and which of it is Deprecated. */ export function detailOnly(root, usage, env) { const deprecated = deprecatedUse(root, usage.invokedCommand ?? usage.command, usage.arguments); return { ...(env.AKM_TASK_REF ? { task: env.AKM_TASK_REF } : {}), ...(deprecated.command || deprecated.flags.length ? { deprecated } : {}), }; }