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

554 lines (553 loc) • 27 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/. /** * `akm task` command family. Handlers whose body is a plain * `runWithJsonErrors(...) + output(...)` are `defineJsonCommand`s, which emit * the JSON envelope (stdout/stderr/exit-code). `task run` keeps a plain * `defineCommand` because it forwards the task's own exit code via * `process.exitCode` (not `process.exit()`, which would skip pending cleanup). * * The default improve-schedule task set ships as embedded templates under * src/assets/tasks/improve/ (see src/tasks/embedded.ts), seeded through the * interactive `akm setup` task-review step. `enable`/`disable` mutate the * host-local scheduler allow-list, never the task source. Every subcommand * shares one `--bundle <bundle>` axis. */ import { defineCommand, parseArgs } from "citty"; import { getParsedInvocation } from "../../cli/invocation.js"; import { parsePositiveIntFlag, parseTimeoutFlags } from "../../cli/parse-args.js"; import { RETIRED_ENGINE_ARG, SELECTION_ARGS, selectionFromArgs } from "../../cli/selection.js"; import { defineGroupCommand, defineJsonCommand, EXIT_CODES, GLOBAL_OUTPUT_ARGS, output, outputWithExitCode, reportChildExit, runWithJsonErrors, } from "../../cli/shared.js"; import { assertKnownFlags, scanRoot } from "../../cli/unknown-flags.js"; import { UsageError } from "../../core/errors.js"; import { TASK_RUN_BOOLEAN_FLAGS, TASK_RUN_VALUE_FLAGS } from "../../tasks/task-run-reserved-flags.js"; import { parseStartFlags, taskIdInStart } from "../../tasks/v5/flags.js"; import { akmTaskDispatch } from "./dispatch.js"; import { akmTaskExplain } from "./explain.js"; import { akmTasksAdd, akmTasksDisable, akmTasksDoctor, akmTasksEnable, akmTasksHistory, akmTasksPrune, akmTasksRun, akmTasksSync, akmTasksSyncPlan, } from "./tasks.js"; /** Shared `--bundle <bundle>` arg wired onto every task subcommand. */ const bundleArg = { bundle: { type: "string", description: "Bundle to operate on (defaults to the primary/default bundle)", }, }; /** * True when argv carries a `--<name>` flag in ANY spelling — bare, * `--<name>=<value>` for any value, or a trailing `=` — stopping at a literal * `--` separator exactly as `hasFlagIn` (`../../cli/invocation.ts`) does. * * `ParsedInvocation.hasFlag` cannot be used for the rejections below: it * compares WHOLE tokens against `--<name>` and `--<name>=true` only, so every * other value spelling (`--<name>=false`, `--<name>=1`, `--<name>=`) walks * straight past it and is then absorbed downstream — by citty's non-strict * parser, or by `parseTaskInputFlags`' reserved-name skip — exactly the * silent-discard defect these rejecters exist to close. The * name is taken as everything before the FIRST `=`, which is * `parseTaskInputFlags`' own split (see its `body.indexOf("=")` below), so the * rejecter and the scanner can never disagree about what a token names. */ function hasFlagNamed(name) { for (const token of getParsedInvocation().ownArgs) { if (!token.startsWith("--")) continue; const body = token.slice(2); const equalsAt = body.indexOf("="); if ((equalsAt === -1 ? body : body.slice(0, equalsAt)) === name) return true; } return false; } /** * `--scheduled` is `akm task run`'s own declared flag (an internal marker for * scheduler-generated runs) — `task explain` declares no such flag. Because * `explain` reuses `parseTaskInputFlags` (the same exact-name scanner `task * run` uses, see that function's docstring below) to capture input flags, and * `scheduled` is one of that scanner's reserved boolean-flag names * (`TASK_RUN_BOOLEAN_FLAG_SET`, from `../../tasks/task-run-reserved-flags`), * the scanner silently skips over `--scheduled` rather than ever surfacing it * as an input flag — so it reached neither `materializeInputFlags`' own * unknown-flag diagnostic nor the generic pre-dispatch flag gate (which * exempts `task explain`'s whole dynamic namespace, `../../cli/unknown-flags` * §`dynamicNamedFlagCommands`). The net effect: `akm task explain <ref> * --scheduled` silently accepted and discarded the flag instead of rejecting * it (finding F7) — `scheduled` can never be a declared input name either * (same reserved-name module), so this can never reject a flag that was ever * a valid input binding. Reject it explicitly, before the shared scanner ever * sees it — same UNKNOWN_FLAG diagnostic family the generic gate uses. * * Rejection is keyed on the flag NAME (`hasFlagNamed` above), not on a literal * token: `parseTaskInputFlags` splits on the first `=` BEFORE its reserved-name * check, so `--scheduled=false` and `--scheduled=1` are swallowed by that skip * just as the bare token is. A whole-token test would leave every spelling but * `--scheduled` / `--scheduled=true` in the hole this exists to close. */ function rejectExplainScheduledFlag() { if (!hasFlagNamed("scheduled")) return; throw new UsageError('Unknown flag "--scheduled".', "UNKNOWN_FLAG"); } // ── `akm task run` input flags — Stage 1: capture ─────────────────────────── // // Mirrors `parseWorkflowParameterFlags` (src/commands/workflow-cli.ts:232-289) // exactly: the CLI carries RAW string/boolean flag values to the boundary // that knows the task's declared contract (Stage 2, src/tasks/run/load-task.ts) // — coercion happens once, there. `akm task run`'s own declared flags // (GLOBAL_OUTPUT_ARGS, --bundle, --scheduled) are excluded so they are never // mistaken for inputs. // `TASK_RUN_VALUE_FLAGS` / `TASK_RUN_BOOLEAN_FLAGS` are re-exported here // (unchanged in name, location, and value) from a dependency-free leaf module // so `src/tasks/source/task-source-v4.ts` can reject a declared `inputs:` // name that collides with one of them without importing this CLI file — // which would cycle back through `./tasks` -> `../../tasks/source/*` into the // parser (see `../../tasks/task-run-reserved-flags.ts`'s own header). export { TASK_RUN_BOOLEAN_FLAGS, TASK_RUN_VALUE_FLAGS }; const TASK_RUN_VALUE_FLAG_SET = new Set(TASK_RUN_VALUE_FLAGS); const TASK_RUN_BOOLEAN_FLAG_SET = new Set(TASK_RUN_BOOLEAN_FLAGS); /** * Scan `akm task run`'s raw argv for exact-name input flags, excluding the * task id and every declared flag above. Input flags must come after the * task id (mirrors `parseWorkflowParameterFlags`'s positional rule); a bare * `--` is rejected, matching `workflow run`. */ export function parseTaskInputFlags(rawArgs, id) { const flags = []; let idSeen = false; for (let index = 0; index < rawArgs.length; index += 1) { const token = rawArgs[index]; if (token === "--") { throw new UsageError("`akm task run` does not accept positional arguments after `--`.", "INVALID_FLAG_VALUE"); } if (!token.startsWith("-") || token === "-" || /^-\d/.test(token)) { if (!idSeen) { if (token !== id) { throw new UsageError("Task input flags must come after the task id.", "INVALID_FLAG_VALUE"); } idSeen = true; continue; } throw new UsageError(`Unexpected positional task argument "${token}".`, "INVALID_FLAG_VALUE"); } if (!token.startsWith("--")) continue; const body = token.slice(2); const equalsAt = body.indexOf("="); const name = equalsAt === -1 ? body : body.slice(0, equalsAt); const inlineValue = equalsAt === -1 ? undefined : body.slice(equalsAt + 1); if (TASK_RUN_VALUE_FLAG_SET.has(name)) { if (inlineValue === undefined) index += 1; continue; } if (TASK_RUN_BOOLEAN_FLAG_SET.has(name)) continue; if (!idSeen) { throw new UsageError("Task input flags must come after the task id.", "INVALID_FLAG_VALUE"); } if (inlineValue !== undefined) { flags.push({ name, value: inlineValue }); continue; } const next = rawArgs[index + 1]; if (next !== undefined && (!next.startsWith("-") || /^-\d/.test(next))) { flags.push({ name, value: next }); index += 1; } else { flags.push({ name, value: true }); } } return flags; } /** * Join each flag naming a declared value input to its value (`--who -x` becomes `--who=-x`), the one spelling * {@link parseTaskInputFlags} cannot mistake for a flag. The unknown-flag scan and the binder both read the result, * so neither takes `-x` for a flag of its own. */ function inlineInputValues(tokens, valueInputs) { const joined = []; for (let index = 0; index < tokens.length; index += 1) { const token = tokens[index]; const next = tokens[index + 1]; if (token.startsWith("--") && valueInputs.has(token.slice(2)) && next !== undefined) { joined.push(`${token}=${next}`); index += 1; } else { joined.push(token); } } return joined; } /** What a start of a version 5 task gave: its start flags, and its input flags as a version 4 task's are read. */ function readV5Start(rawArgs, id) { const { rest, ...start } = parseStartFlags(rawArgs); return { ...start, inputs: parseTaskInputFlags(rest, id) }; } /** * The one reader of a task's input tokens, run once the task's declared value inputs are known: each declared value * input is joined to its value (`--who -x` is `--who=-x`), and the tokens are checked as the command at `path` checks * its flags. `akm run`, `akm task run`, `akm task explain` and `akm doctor explain` all read through it. */ function readTaskInputTokens(command, rawArgs, valueInputs) { const joined = inlineInputValues(rawArgs, valueInputs); assertKnownFlags(scanRoot(command.path, command.schema), [...command.path, ...joined]); return joined; } /** What a task command hands the task layer to read its input flags and start flags once the task is known. */ function taskInputReaders(command, rawArgs, id) { return { inputFlags: (valueInputs) => parseTaskInputFlags(readTaskInputTokens(command, rawArgs, valueInputs), id), start: (valueInputs) => readV5Start(readTaskInputTokens(command, rawArgs, valueInputs), id), }; } const tasksAddCommand = defineJsonCommand({ meta: { name: "add", description: "Deprecated, removed in 0.11: use `akm import <file> --type task`. Register a new scheduled task and install it in the OS scheduler", }, args: { id: { type: "positional", description: "Task id (used as filename and scheduler entry)", required: true }, schedule: { type: "string", description: 'Cron-style schedule, e.g. "0 9 * * *" or "@daily"', required: true }, ...bundleArg, workflow: { type: "string", description: "Workflow ref to invoke (e.g. workflows/my-flow)" }, prompt: { type: "string", description: "Inline text prompt for the configured agent harness (asset refs and file paths are rejected)", }, command: { type: "string", description: 'Exact shell string to run on the schedule (no AI agent), e.g. "akm improve --strategy consolidate".', }, ...SELECTION_ARGS, ...RETIRED_ENGINE_ARG, timeout: { type: "string", description: "Timeout as a duration (30s, 2m) or milliseconds, for prompt or command targets", }, "timeout-ms": { type: "string", description: "Deprecated: use `--timeout`. Positive timeout in milliseconds for prompt or command targets", }, params: { type: "string", description: "Workflow params as a JSON object" }, name: { type: "string", description: "Human-readable name for the task" }, "when-to-use": { type: "string", description: "Guidance on when this task runs or should be used" }, description: { type: "string", description: "Human-readable description" }, tags: { type: "string", description: "Comma-separated tags" }, disabled: { type: "boolean", description: "Register but leave disabled in the OS scheduler", default: false }, force: { type: "boolean", description: "Overwrite an existing task with the same id", default: false }, rebind: { type: "boolean", description: "Also point the bundle's installed scheduler rows at this akm invocation (as `task sync --rebind`)", default: false, }, }, async run({ args }) { const result = await akmTasksAdd({ id: args.id, schedule: args.schedule, target: args.bundle, workflow: args.workflow, prompt: args.prompt, command: args.command, ...selectionFromArgs(args), timeoutMs: parseTimeoutFlags(args.timeout, args["timeout-ms"] === undefined ? undefined : parsePositiveIntFlag(args["timeout-ms"])), params: args.params, name: args.name, when_to_use: args["when-to-use"], description: args.description, tags: args.tags ? args.tags .split(/[\s,]+/) .map((s) => s.trim()) .filter(Boolean) : undefined, disabled: args.disabled === true, force: args.force === true, rebind: args.rebind === true, }); output("task-add", result); }, }); const { config: _configFileArg, ...taskRunGlobalArgs } = GLOBAL_OUTPUT_ARGS; export const tasksRunCommand = defineCommand({ meta: { name: "run", description: "Deprecated, removed in 0.11: use `akm run <qualified-task-ref>`. Execute a task now (this is what cron / launchd / schtasks invoke at the scheduled time)", }, // Raw defineCommand (it forwards the task's exit code), so the global output // flags are declared here or `--format md nightly` loses the task id. args: { ...taskRunGlobalArgs, id: { type: "positional", description: "Task id", required: true }, ...bundleArg, scheduled: { type: "boolean", description: "Internal marker for scheduler-generated runs", default: false }, }, async run({ args, rawArgs }) { await runWithJsonErrors(async () => { const id = taskIdInStart(rawArgs) ?? args.id; const envelope = await akmTasksRun(id, { scheduled: args.scheduled === true, ...(args.bundle !== undefined ? { target: args.bundle } : {}), ...taskInputReaders({ path: ["task", "run"], schema: tasksRunCommand }, rawArgs, id), }); output("task-run", envelope); // Set `process.exitCode` rather than calling `process.exit`, which would // skip pending cleanup (this command forwards a run task's own exit code, // so it can be any value, not just 0/1). output() has already run and // this is the last statement. // A process the task ran that exited non-zero is that program's failure (usage counts it as `child`). const ran = envelope.result.status === "failed" ? envelope.result.detail?.exitCode : undefined; if (typeof ran === "number" && ran !== 0) reportChildExit(envelope.exitCode); else if (envelope.exitCode !== 0) process.exitCode = envelope.exitCode; }); }, }); /** * Whether the tokens after `task` are `run <id> …`. Such a run reads the config itself, so that a scheduled one records * its failure to start; undeclared input flags (`--scope all`) do not change the answer. */ export function namesTaskToRun(taskArgs) { if (taskArgs[0] !== "run") return false; try { const parsed = parseArgs(taskArgs.slice(1), tasksRunCommand.args); return typeof parsed.id === "string" && parsed.id.length > 0; } catch { return false; } } const tasksEnableCommand = defineJsonCommand({ meta: { name: "enable", description: "Enable a task in this host's scheduler configuration and sync it" }, args: { ref: { type: "positional", description: "Task ref or id", required: true }, ...bundleArg, }, async run({ args }) { output("task-enable", await akmTasksEnable(args.ref, { target: args.bundle })); }, }); const tasksDisableCommand = defineJsonCommand({ meta: { name: "disable", description: "Disable a task in this host's scheduler configuration and sync it" }, args: { ref: { type: "positional", description: "Task ref or id", required: true }, ...bundleArg, }, async run({ args }) { output("task-disable", await akmTasksDisable(args.ref, { target: args.bundle })); }, }); /** * #911: `task run <id>` and `task explain <ref>` take the id positionally, so * `task history <id>` is the natural thing to write — so a positional id * means the same as `--id`; giving both with different * values is a usage error rather than a silent pick. */ export function resolveTaskHistoryId(positional, flag) { if (positional !== undefined && flag !== undefined && positional !== flag) { throw new UsageError(`\`akm task history\` was given two task ids: "${positional}" and --id "${flag}". Pass one.`, "INVALID_FLAG_VALUE"); } return flag ?? positional; } const tasksHistoryCommand = defineJsonCommand({ meta: { name: "history", description: "Deprecated, removed in 0.11: use `akm doctor log --task <id>`. Show recent task run history", }, args: { task: { type: "positional", description: "Task id to filter to (same as --id)", required: false }, id: { type: "string", description: "Filter to one task id" }, limit: { type: "string", description: "Maximum rows to return (default 50)" }, ...bundleArg, }, async run({ args }) { const limit = parsePositiveIntFlag(args.limit ?? undefined); const id = resolveTaskHistoryId(args.task, args.id); const result = await akmTasksHistory({ id, limit, target: args.bundle }); output("task-history", result); }, }); /** * #849: `task sync --dry-run`'s exit-code contract, "non-zero when the plan * contains removals" — factored out as a pure function (rather than left * inline in the command's `run()`) so it's directly unit-testable without * driving the whole CLI through a real scheduler backend. #867: also * non-zero when any source failed to parse/prepare — sync degrades (still * reconciles the tasks/workflows that DID parse) rather than rejecting the * whole set, but a dropped source must still surface as a failing exit. */ export function taskSyncDryRunExitCode(preview) { return preview.hasRemovals || (preview.failures?.length ?? 0) > 0 ? EXIT_CODES.GENERAL : undefined; } /** Shared with `akm doctor scheduler sync`, which reuses this handler. */ export const taskSyncArgs = { ...bundleArg, rebind: { type: "boolean", description: "Point installed rows at this akm invocation instead of keeping their launcher", default: false, }, "dry-run": { type: "boolean", description: "Print the reconcile plan without touching the OS scheduler; exits non-zero if it has removals", default: false, }, }; export async function runTaskSync(args) { { const options = { rebind: args.rebind === true, ...(args.dispatch !== undefined ? { dispatch: args.dispatch } : {}), }; if (args["dry-run"] === true) { const preview = await akmTasksSyncPlan({}, args.bundle, options); outputWithExitCode("task-sync-dry-run", preview, taskSyncDryRunExitCode(preview), (preview.failures?.length ?? 0) > 0 ? "SCHEDULER_SYNC_FAILED" : "SCHEDULER_REMOVALS_PENDING"); return; } const result = await akmTasksSync({}, args.bundle, options); // #867: sync degrades — sources that failed to parse/prepare are // excluded from reconciliation and reported in `result.failures` rather // than poisoning the whole sync, but their presence must still fail // the command's exit code so the breakage stays visible. (#906: this key // matches the `--dry-run` preview's `failures` field — no separate name.) outputWithExitCode("task-sync", result, result.failures.length > 0 ? EXIT_CODES.GENERAL : undefined, "SCHEDULER_SYNC_FAILED"); } } const tasksSyncCommand = defineJsonCommand({ meta: { name: "sync", description: "Deprecated, removed in 0.11: use `akm doctor scheduler sync`. Reconcile enabled task/workflow schedules with the OS scheduler, one row at a time", }, args: taskSyncArgs, async run({ args }) { await runTaskSync(args); }, }); const tasksDispatchCommand = defineJsonCommand({ meta: { name: "dispatch", description: "Start every enabled task due this minute, then exit: what the OS scheduler runs every minute on a host in dispatch mode (`akm doctor scheduler sync --dispatch`)", }, args: {}, async run() { const result = await akmTaskDispatch(); outputWithExitCode("task-dispatch", result, result.failures.length > 0 ? EXIT_CODES.GENERAL : undefined, "TASK_DISPATCH_FAILED"); }, }); // ── `akm task explain` — read-only introspection ──────────────────────────── /** Shared with `akm doctor explain <task-ref>`, which reuses this handler. */ export async function runTaskExplain(args, rawArgs, command) { // `--scheduled` must be rejected BEFORE the shared scanner below ever // sees it — the scanner treats it as `task run`'s own reserved flag // (silently skipped, never surfaced as unknown) rather than explain's, // since it has no way to know which command called it (F7 fix). rejectExplainScheduledFlag(); const ref = taskIdInStart(rawArgs) ?? args.ref; const result = await akmTaskExplain(ref, { ...(args.bundle !== undefined ? { target: args.bundle } : {}), ...taskInputReaders(command, rawArgs, ref), }); // A schedule entry the start check refuses fails the preview, as it fails `doctor scheduler sync`. const refused = result.schedule.some((entry) => entry.error !== undefined); outputWithExitCode("task-explain", result, refused ? EXIT_CODES.GENERAL : undefined, "TASK_SCHEDULE_REFUSED"); } const tasksExplainCommand = defineJsonCommand({ configFile: false, meta: { name: "explain", description: "Deprecated, removed in 0.11: use `akm doctor explain <ref>`. Print a task's source, declared inputs (with provenance), resolved target, execution settings, and " + "schedule bindings — read-only and secret-free; never spawns anything", }, args: { ref: { type: "positional", description: "Task ref or id", required: true }, ...bundleArg, }, async run({ args, rawArgs }) { await runTaskExplain(args, rawArgs, { path: ["task", "explain"], schema: tasksExplainCommand }); }, }); const tasksDoctorCommand = defineJsonCommand({ meta: { name: "doctor", description: "Deprecated, removed in 0.11: use `akm doctor`. Report the active scheduler backend, akm bin path, log dir, and supported schedule subset", }, args: {}, async run() { const result = await akmTasksDoctor(); output("task-doctor", result); }, }); /** * #851: `akm task prune`'s exit-code contract mirrors `task sync --dry-run`'s * (`taskSyncDryRunExitCode` above) — non-zero whenever the preview lists * removals the invocation didn't (or couldn't, without `--yes`) execute, so * `akm task prune` is usable as a CI/health check the same way `sync * --dry-run` is. */ export function taskPruneExitCode(result) { return result.dryRun && result.preview.hasRemovals ? EXIT_CODES.GENERAL : undefined; } /** Shared with `akm doctor scheduler sync --prune`, which reuses this handler. */ export const taskPruneArgs = { yes: { type: "boolean", description: "Execute removal of every currently-computed orphan (the plan is still printed first)", default: false, }, id: { type: "string", description: "Comma-separated scheduler binding id(s) to limit pruning to (must already be orphan candidates)", }, }; export async function runTaskPrune(args) { { const id = args.id ? args.id .split(",") .map((value) => value.trim()) .filter(Boolean) : undefined; const result = await akmTasksPrune({}, { yes: args.yes === true, id }); outputWithExitCode("task-prune", result, taskPruneExitCode(result), "SCHEDULER_REMOVALS_PENDING"); } } const tasksPruneCommand = defineJsonCommand({ meta: { name: "prune", description: "Deprecated, removed in 0.11: use `akm doctor scheduler sync --prune`. Remove installed scheduler entries `sync` can never reclaim because they no longer resolve to a live " + "bundle (the bundle directory a row names is gone, or an older row's --scheduler-context descriptor " + "cannot be read). Defaults to a dry-run preview — zero scheduler writes. Requires --yes to remove anything; " + "--id narrows removal to specific binding ids (comma-separated).", }, args: taskPruneArgs, async run({ args }) { await runTaskPrune(args); }, }); export const taskCommand = defineGroupCommand({ meta: { name: "task", description: "Enable or disable scheduled tasks on this host (cron / launchd / schtasks). The add, run, sync, prune, doctor, history and explain subcommands are Deprecated and removed in 0.11; each help names its replacement", }, subCommands: { add: tasksAddCommand, enable: tasksEnableCommand, disable: tasksDisableCommand, run: tasksRunCommand, explain: tasksExplainCommand, history: tasksHistoryCommand, sync: tasksSyncCommand, dispatch: tasksDispatchCommand, prune: tasksPruneCommand, doctor: tasksDoctorCommand, }, // Bare `akm task` reports scheduler diagnostics. Deeper inspection of // individual tasks is the generic `akm show <bundle//tasks/id>`; listing is // `akm search --type task`. // No `defaultRun`: bare `akm task` is a usage error (exit 2), the canonical // bare-group behavior — owner ruling 12. });