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

192 lines (191 loc) • 8.88 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/. /** * Everything the design checks before a version 5 task runs, that does not need * running anything: `checkTaskV5` reads the task and every task it runs, all the * way down, and throws on the first rule that fails. A start, `doctor explain` * and the scheduler call this one function with the same inputs and flags, so * what they accept is what a run is given. What one file alone decides is * `parseTaskSourceV5Document`'s (`./source.ts`); this adds what needs other * files: the assets a step names, the env assets and secrets, the inputs given, * and tasks that run each other in a loop. */ import path from "node:path"; import { resolveEnvBinding } from "../../commands/env/env-binding.js"; import { assertWorkingFolderCanBeMade } from "../../commands/env/injection.js"; import { makeBundleRef, parseBundleRef } from "../../core/asset/asset-ref.js"; import { loadConfig } from "../../core/config/config.js"; import { resolveSecretPath } from "../../core/env-secret-ref.js"; import { NotFoundError, UsageError } from "../../core/errors.js"; import { parseSecretSpec } from "../../core/ref-token.js"; import { applyInputDefaults, materializeInputFlags, validateInputs, } from "../../execution/input-contract.js"; import { scriptProgram } from "../frozen-script.js"; import { resolveBundleAsset } from "../run/load-task.js"; import { parseTaskSource } from "../source/parse-task-source.js"; import { TASK_V5_INPUT_DIAGNOSTICS } from "../source/task-input-diagnostics.js"; import { requireAssetIn, resolveOwnBundleAsset } from "../task-ref.js"; import { readTaskV5Options } from "./source.js"; const WHOLE_TOKEN = /^\$\{([^}\s]+)\}$/; const ASSET_TYPE = { tasks: "task", commands: "command", scripts: "script", agents: "agent", }; /** Check a task and everything it runs, for a start with these inputs and flags. Returns the task's document. */ export async function checkTaskV5(input) { const flags = input.flags ?? {}; checkStartFlags(flags); return checkTask(input.bundle, input.ref, input.inputs ?? [], new Set(), [], input.ref); } function checkStartFlags(flags) { const given = {}; if (flags.env !== undefined) given.env = flags.env; if (flags.secret !== undefined) given.secret = flags.secret; if (flags.inherit !== undefined) given.inherit = flags.inherit; if (flags.timeout !== undefined) given.timeout = flags.timeout; if (flags.maxRetries !== undefined) given["max-retries"] = flags.maxRetries; const options = readTaskV5Options(given, ["env", "secret", "inherit", "timeout", "max-retries"], [], new Set(), (at, detail) => { throw new UsageError(`--${at[0]} ${detail}`, "INVALID_FLAG_VALUE"); }); checkOptionRefs(options, "akm run"); if (flags.cwd !== undefined) assertWorkingFolderCanBeMade(flags.cwd); } async function checkTask(bundle, ref, inputs, later, trail, where) { const found = await locateTaskV5Asset(bundle, ref, "tasks", where); if (trail.some((visited) => visited.file === found.file)) { throw new UsageError(`Invalid task source v5 at ${found.file}: tasks run each other in a loop: ${[...trail.map((visited) => visited.ref), ref].join(" -> ")}.`, "TASK_SOURCE_INVALID"); } const parsed = parseTaskSource({ yaml: found.asset.entry.content(), filePath: found.file }); if (parsed.version === 4) { throw new UsageError(`Invalid task source v5 at ${where}: ${ref} is a version 4 task, and a version 5 task does not run one. Run \`akm migrate apply\` to convert it.`, "TASK_SOURCE_INVALID"); } const document = parsed.v5; checkSupplied(document.inputs ?? {}, inputs, later); checkOptionRefs(document.options, ref); checkWorkingFolder(document.options, found.bundle, ref); const visited = [...trail, { file: found.file, ref }]; for (const step of document.steps) { const at = step.name === "" ? ref : `${ref} step ${step.name}`; checkOptionRefs(step.options, at); checkWorkingFolder(step.options, found.bundle, at); if (step.kind === "exec" || step.kind === "prompt") continue; const target = step.run; if (step.kind === "tasks") { const given = []; const known = new Set(); for (const { name, value } of step.taskInputs ?? []) { if (typeof value === "string" && WHOLE_TOKEN.test(value)) known.add(name); else given.push({ name, value: String(value) }); } await checkTask(found.bundle, target, given, known, visited, at); continue; } const asset = await locateTaskV5Asset(found.bundle, target, step.kind, at); if (step.kind === "scripts") { scriptProgram(target, asset.asset, []); } } return document; } /** The asset (and its file, for messages) a ref names, in the bundle it is read from, and that bundle. A ref that names nothing is refused. */ export async function locateTaskV5Asset(bundle, ref, kind, where) { const parsed = parseBundleRef(ref); const name = parsed.conceptId.slice(parsed.conceptId.indexOf("/") + 1); const type = ASSET_TYPE[kind]; const owner = parsed.bundle ?? bundle.name; try { const placed = owner === bundle.name ? { file: resolveOwnBundleAsset({ name: bundle.name, path: bundle.dir, ...(bundle.adapterId !== undefined ? { adapterId: bundle.adapterId } : {}), }, { type, name }).file, bundle, } : (() => { const found = resolveBundleAsset(loadConfig(), { bundle: owner, type, name }); return { file: found.file, bundle: { name: owner, dir: found.bundleRoot } }; })(); // What the asset holds is read through its bundle's adapter, by its ref. const asset = requireAssetIn({ name: owner, path: placed.bundle.dir, ...(placed.bundle.adapterId !== undefined ? { adapterId: placed.bundle.adapterId } : {}), }, makeBundleRef(owner, parsed.conceptId)); return { ...placed, asset }; } catch (cause) { throw inContext(where, cause); } } /** * The inputs given, as the task's declared inputs take them: converted to their types, defaults applied, each * required one present. One whose value is only known when the step runs counts as given. */ function checkSupplied(contract, flags, later) { const declared = Object.keys(contract); for (const name of later) { if (!declared.includes(name)) throw TASK_V5_INPUT_DIAGNOSTICS.unknownFlag(name, [...declared].sort()); } const repeated = flags.find((flag) => later.has(flag.name)); if (repeated) throw TASK_V5_INPUT_DIAGNOSTICS.duplicateNonArray(repeated.name); const known = Object.fromEntries(Object.entries(contract).filter(([name]) => !later.has(name))); const defaulted = applyInputDefaults(known, materializeInputFlags(known, flags, TASK_V5_INPUT_DIAGNOSTICS)); const errors = validateInputs(known, defaulted); if (errors.length > 0) throw TASK_V5_INPUT_DIAGNOSTICS.contractViolation(errors); } /** The env assets and secrets an `env:` or `secret:` names must exist, and an env asset's own bindings with them. */ function checkOptionRefs(options, where) { for (const entry of options.env ?? []) { if (typeof entry !== "string") continue; try { resolveEnvBinding(entry, { locateOnly: true }); } catch (cause) { throw inContext(where, cause); } } for (const spec of options.secret ?? []) { try { resolveSecretPath(parseSecretSpec(spec).ref); } catch (cause) { throw inContext(where, cause); } } } /** A `cwd:` names a folder that can be made, read from the bundle the task is in. */ function checkWorkingFolder(options, bundle, where) { if (options.cwd === undefined) return; try { assertWorkingFolderCanBeMade(path.resolve(bundle.dir, options.cwd)); } catch (cause) { throw inContext(where, cause); } } /** The same error, with where it was found in front of its message. */ function inContext(where, cause) { if (cause instanceof NotFoundError) return new NotFoundError(`${where}: ${cause.message}`, cause.code); if (cause instanceof UsageError) return new UsageError(`${where}: ${cause.message}`, cause.code); return cause; }