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

174 lines (173 loc) • 9.43 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/. /** * Load and project one task asset into immutable executable work: id * validation, adapter detection, owner resolution, source read, strict task * source parsing, config selection, bundle-name resolution, and the * `prepareTaskV3Execution` call. Everything here is non-mutating — run-task.ts * records a failed scheduled activation if this rejects, or reserves an execution after it resolves. */ import { makeBundleRef } from "../../core/asset/asset-ref.js"; import { conceptIdFromTypeName } from "../../core/asset/resolve-ref.js"; import { activeSources } from "../../core/assets/gate.js"; import { findAsset } from "../../core/assets/read.js"; import { bundleSourceAt } from "../../core/bundle-at-dir.js"; import { loadConfig } from "../../core/config/config.js"; import { UsageError } from "../../core/errors.js"; import { assertBundleNotDisabled } from "../../core/write-source.js"; import { applyInputDefaults, materializeInputFlags, validateInputs, } from "../../execution/input-contract.js"; import { sourceOfBundle } from "../../indexer/installations.js"; import { resolveSourcesForOrigin } from "../../registry/origin-resolve.js"; import { prepareTaskV3Execution } from "../prepare/prepare.js"; import { scheduledTaskContextEnv } from "../scheduler-invocation.js"; import { parseTaskSource, taskValueInputs } from "../source/parse-task-source.js"; import { projectTaskSourceV4 } from "../source/project-v4.js"; import { TASK_INPUT_DIAGNOSTICS } from "../source/task-input-diagnostics.js"; import { validateTaskConceptId } from "../task-id.js"; import { resolveOwnBundleAsset, resolveTask, taskAssetFile, taskAssetNotFound, taskNameOf, taskNotFound, } from "../task-ref.js"; /** * The literal bundle-name fallback, hoisted to a named constant. The value is * user-visible data, so it must not change. */ export const DEFAULT_BUNDLE_NAME = "stash"; const CONFIG_FREE_TASK_RUNTIME = Object.freeze({ configVersion: "0.9.0", semanticSearchMode: "off", }); /** * The active source set a task read walks. A working stash that is a disabled * configured bundle makes that set throw; it is simply not in the set, so the * other bundles still resolve. */ export function activeTaskSources(config) { return activeSources(config); } /** * Resolve an asset a task names in another bundle (`uses:`) through the one * ref-to-file walk. Reading needs no write target, so a bundle of any kind * (git, npm, website) resolves. The file is the authored path, not the symlink * target, so the script interpreter follows the name the author gave it. */ export function resolveBundleAsset(config, { bundle, type, name }) { const conceptId = conceptIdFromTypeName(type, name); const sources = activeTaskSources(config); const asset = findAsset(makeBundleRef(bundle, conceptId)); if (asset) { const file = taskAssetFile(asset); const bundleRoot = sourceOfBundle(sources, asset.bundle).path; if (bundleRoot === undefined) throw new UsageError(`Bundle "${asset.bundle}" has no resolved directory.`); return { file, bundleRoot }; } if (resolveSourcesForOrigin(bundle, sources).length === 0) { assertBundleNotDisabled(config, bundle); throw new UsageError(`Bundle ${JSON.stringify(bundle)} is not configured. Run \`akm bundle list\` to see available bundles.`, "INVALID_FLAG_VALUE"); } throw taskAssetNotFound(makeBundleRef(bundle, conceptId)); } /** Resolve, parse, and project one task-v3 asset into a frozen, executable projection. */ export async function loadPreparedTask(id, options) { const bundleDir = options.bundleDir; validateTaskConceptId(id); const bundle = bundleSourceAt(bundleDir); const taskSource = { name: options.bundleName ?? bundle.name, path: bundleDir, adapterId: options.adapterId ?? bundle.adapterId, }; const found = resolveTask(taskSource, id); if (!found) throw taskNotFound(taskSource, taskNameOf(taskSource, id)); const { asset } = found; const taskConceptId = asset.conceptId; // asset-io: display the file names the task source in messages const filePath = asset.entry.file; if (filePath === undefined) throw new UsageError(`Asset ${asset.ref} is not kept in a file.`); const yaml = asset.entry.content(); const parsed = parseTaskSource({ yaml, filePath }); if (parsed.version !== 4) { return Object.freeze({ kind: "v5", taskId: id, ref: taskConceptId, valueInputs: taskValueInputs(parsed), bundle: Object.freeze({ name: options.bundleName ?? loadConfig().defaultBundle ?? DEFAULT_BUNDLE_NAME, dir: bundleDir, }), }); } const source = projectTaskSourceV4(parsed.v4); const requiresCommandConfig = (source.target.kind === "uses" && (source.target.uses.kind === "builtin-command" || source.target.uses.kind === "command")) || (source.target.kind === "steps" && source.target.steps.some((step) => step.kind === "prompt")); const config = requiresCommandConfig ? loadConfig() : CONFIG_FREE_TASK_RUNTIME; const bundleName = options.bundleName ?? config.defaultBundle ?? DEFAULT_BUNDLE_NAME; // Stage 2: materialize akm task run's raw input flags (Stage 1, // src/commands/tasks/tasks-cli.ts) against the task's own declared // inputs: contract (empty when the document declares none, so any input // flag on such a task fails UNKNOWN_FLAG — there is nothing declared to // match against). // materializeInputFlags already validates the flag-supplied values; a // required input satisfied only by its own default (never supplied as a // flag) needs the SEPARATE validateInputs call below, run after defaults // are applied — materializeInputFlags returns {} immediately for zero // flags, before ever checking `required` (input-contract.ts's own // header). const inputContract = parsed.v4.inputs ?? {}; // `--resume` is a flag of a steps task only (such a task cannot declare an input named `resume`); // for every other task it stays an ordinary input flag. const isStepsTask = source.target.kind === "steps"; const givenFlags = options.inputFlags?.(taskValueInputs(parsed)) ?? []; const resumeRequested = isStepsTask && givenFlags.some((flag) => flag.name === "resume" && flag.value !== false && flag.value !== "false"); const inputFlags = isStepsTask ? givenFlags.filter((flag) => flag.name !== "resume") : givenFlags; const materializedInputs = materializeInputFlags(inputContract, inputFlags, TASK_INPUT_DIAGNOSTICS); const defaultedInputs = applyInputDefaults(inputContract, materializedInputs); const requiredErrors = validateInputs(inputContract, defaultedInputs); if (requiredErrors.length > 0) throw TASK_INPUT_DIAGNOSTICS.contractViolation(requiredErrors); const inputBindings = Object.entries(defaultedInputs).map(([name, value]) => Object.freeze({ kind: "literal", name, value })); if (options.captureTaskInvocation) { const invocation = Object.freeze({ taskRef: makeBundleRef(bundleName, taskConceptId), caller: Object.freeze({ kind: "cli" }), ...(inputBindings.length > 0 ? { inputs: Object.freeze(inputBindings) } : {}), }); options.captureTaskInvocation(invocation); } // A task source v4 document's own declared `inputs:` deliver into a // `uses: workflows/<ref>` target's child-run params through the EXISTING // with-> params path (prepare.ts's workflow branch already reads // `document.target.with`) — task source v4 never authors `with:` on a // workflow target itself (task-source-v4.ts's own parser accepts `with:` // only on `uses: akm/command`), so this // override is purely additive for a workflow-target task. const deliverySource = source.target.kind === "uses" && source.target.uses.kind === "workflow" ? { ...source, target: { ...source.target, with: defaultedInputs } } : source; const prepared = await prepareTaskV3Execution(deliverySource, { taskId: id, taskRef: makeBundleRef(bundleName, taskConceptId), bundleName, bundleRoot: bundleDir, config, // Freeze the AKM directory context the scheduled row set before command preparation. ...(options.scheduled ? { schedulerContext: scheduledTaskContextEnv() } : {}), resolveAsset: async ({ bundle, type, name }) => { if (bundle === bundleName) { return resolveOwnBundleAsset({ name: bundleName, path: bundleDir, adapterId: taskSource.adapterId }, { type, name }); } return resolveBundleAsset(requiresCommandConfig ? config : loadConfig(), { bundle, type, name }); }, }); // Experimental steps task: every step receives the run's defaulted inputs as AKM_PARAMS. return prepared.kind === "steps" ? Object.freeze({ ...prepared, params: Object.freeze({ ...defaultedInputs }), ...(resumeRequested ? { resume: true } : {}), }) : prepared; }