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
194 lines (193 loc) • 9.87 kB
JavaScript
// 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/.
/**
* A task is an asset, named by its ref. A bare task id is CLI sugar for it, resolved here and nowhere else: through
* the bundle's task assets, by concept id as written, else by name (the concept id without the task type's folder).
* No caller computes where an adapter keeps its tasks. This is the one function the ref qualifier replaces.
*/
import { stashDirFor, withoutTypeHead } from "../core/asset/asset-placement.js";
import { makeBundleRef, parseBundleRef } from "../core/asset/asset-ref.js";
import { conceptIdFromTypeName } from "../core/asset/resolve-ref.js";
import { adapterNameOf, adapterWrites, bundleNameOf, placedPrefixOf } from "../core/assets/gate.js";
import { findAsset, listAssets, readAsset, requireAsset } from "../core/assets/read.js";
import { assetTypes } from "../core/assets/type.js";
import { addressOf } from "../core/assets/write.js";
import { bundleAt } from "../core/bundle-at-dir.js";
import { loadConfig } from "../core/config/config.js";
import { bundleAtDir } from "../core/config/config-sources.js";
import { ConfigError, NotFoundError, UsageError } from "../core/errors.js";
/**
* The scope of one source, under the id its refs use. A source no config entry names (a directory a command was
* handed) is the scope itself, which the facade takes as it is.
*/
export function taskScopeOf(source) {
return { bundle: taskBundle(source) };
}
/**
* The bundle `source` is, which the facade takes. A configured bundle held at its own directory (or a store) is that
* bundle; the same name held elsewhere (a scratch copy) is the bundle of that directory, never the configured one; an
* unconfigured directory is its own source under its name.
*/
function taskBundle(source) {
const config = loadConfig();
const configured = config.bundles?.[source.name];
const own =
// asset-io: config a config entry with a location is held at no directory
configured !== undefined && (configured.location !== undefined || bundleAtDir(config, source.path) === source.name);
return bundleAt(source.path, config, {
...(configured === undefined || own ? { name: source.name } : {}),
...(source.adapterId !== undefined ? { adapterId: source.adapterId } : {}),
});
}
/** The file that holds a task, for messages and for the parser to name; the ref of a task no file holds. */
export function taskFileOf(asset) {
// asset-io: display
return asset.entry.file ?? asset.ref;
}
/** `ref` as the facade takes it: a ref to the bundle held at `source` names it by the id the facade holds it under. */
function heldRef(source, ref) {
const parsed = parseBundleRef(ref);
return parsed.bundle === source.name
? makeBundleRef(bundleNameOf(taskBundle(source)), parsed.conceptId, parsed.fragment)
: ref;
}
/** The asset `ref` names in the bundle held at `source`; a `NotFoundError` when it holds none. */
export function requireAssetIn(source, ref) {
return requireAsset(heldRef(source, ref), taskBundle(source));
}
/**
* The asset of `type` named `name` that a task names in its own bundle, held at `source`, found as one in another
* bundle is (`resolveBundleAsset`): through the asset facade, by ref. Its file is the authored path, not a link's target.
*/
export function resolveOwnBundleAsset(source, { type, name }) {
const ref = makeBundleRef(source.name, conceptIdFromTypeName(type, name));
const asset = findAsset(heldRef(source, ref), taskBundle(source));
if (!asset)
throw taskAssetNotFound(ref);
return { file: taskAssetFile(asset), bundleRoot: source.path };
}
/** The file a task hands to a program (a script's interpreter); refused for an asset no file holds. */
export function taskAssetFile(asset) {
// asset-io: exec the file is handed to the script interpreter
const file = asset.entry.file;
if (file === undefined)
throw new UsageError(`Asset ${asset.ref} is not kept in a file.`);
return file;
}
/** A task asset no bundle holds, named by its ref. */
export function taskAssetNotFound(ref) {
return new NotFoundError(`Task asset ${ref} was not found.`, "ASSET_NOT_FOUND");
}
/** The task assets of `candidates` (a listing made without a type), typed by the index. */
export function taskAssetsAmong(candidates) {
const types = assetTypes(candidates);
return candidates.filter((asset) => types.get(asset) === "task");
}
/**
* What the bundle's adapter puts before a task's name in its concept id (`tasks/`, or nothing): where it places a task
* named so, when it writes tasks. Asked of the adapter, never assumed from its id.
*/
function taskPrefixIn(source) {
return taskPrefixOf(taskBundle(source));
}
function taskPrefixOf(bundle) {
// An adapter that does not write tasks places none: a task there is named by its concept id.
return adapterWrites(bundle, "task") ? placedPrefixOf(bundle, "task") : "";
}
/**
* A task's id: its name in the bundle, which is what a scheduler row, a log and a history row call it. The concept id
* without the prefix the bundle's adapter places tasks under.
*/
export function taskIdOf(asset, source) {
const prefix = taskPrefixIn(source);
return prefix !== "" && asset.conceptId.startsWith(prefix) ? asset.conceptId.slice(prefix.length) : asset.conceptId;
}
/** The concept ids `input` can name: as written, or under the prefix tasks are placed under. */
function spellingsOf(scope, input) {
let prefix;
try {
prefix = taskPrefixOf(scope.bundle);
}
catch (error) {
if (!(error instanceof ConfigError))
throw error;
// A bundle no config names has no adapter to ask: the task type's own folder.
const folder = stashDirFor("task");
prefix = folder !== undefined ? `${folder}/` : "";
}
return [...new Set([input, `${prefix}${input}`])];
}
/** The task `input` names in a scope; undefined when no task of the scope has that id. */
export function findTask(scope, input) {
const spellings = spellingsOf(scope, input);
// Only the assets the input can name are typed, not the whole bundle.
const named = taskAssetsAmong(listAssets(scope).filter((asset) => spellings.includes(asset.conceptId)));
const listed = spellings.map((spelling) => named.find((asset) => asset.conceptId === spelling)).find(Boolean);
if (listed)
return listed;
// A spelling the adapter reads but does not list under (another letter case). One with a type folder in front is
// not tried: reading it would resolve an outdated spelling of another asset, with a warning.
for (const spelling of spellings) {
if (withoutTypeHead(spelling) !== undefined)
continue;
let asset;
try {
asset = readAsset(scope.bundle, spelling);
}
catch (error) {
if (!(error instanceof ConfigError))
throw error;
}
if (asset && taskAssetsAmong([asset]).length > 0)
return asset;
}
return undefined;
}
/**
* The name `input` gives a task in the bundle: the id without the prefix its adapter places tasks under. An adapter
* that places tasks names one by a bare id or by `tasks/<id>`, nothing deeper.
*/
export function taskNameOf(source, input) {
if (!adapterWrites(taskBundle(source), "task"))
return input;
const prefix = taskPrefixIn(source);
const name = prefix !== "" && input.startsWith(prefix) ? input.slice(prefix.length) : input;
if (name.includes("/")) {
throw new UsageError(`The native akm adapter accepts only a bare task id or tasks/<id>, got "${input}".`, "INVALID_FLAG_VALUE");
}
return name;
}
/** The task `input` names in a source's bundle, with its id; undefined when it holds none. */
export function resolveTask(source, input) {
const asset = findTask(taskScopeOf(source), taskNameOf(source, input));
if (asset === undefined)
return undefined;
return { asset, id: taskIdOf(asset, source) };
}
/** The sentence for a task a bundle does not hold, naming the id and the adapter. */
export function taskNotFound(source, shown) {
return new NotFoundError(`Task ${JSON.stringify(shown)} was not found in the configured ${JSON.stringify(adapterNameOf(taskBundle(source)))} bundle.`, "ASSET_NOT_FOUND");
}
/** The lowercase ids of the tasks held in a `.yml` file, among a bundle's `listing`: a task held in another spelling of the extension yields to them. */
export function ymlHeldIds(listing, source) {
const held = listing.filter((asset) => taskFileOf(asset).endsWith(".yml"));
return new Set(taskAssetsAmong(held).map((asset) => taskIdOf(asset, source).toLowerCase()));
}
/** Whether `asset`, held in an off-case file, is shadowed by a `.yml`-held task of the same id (compared case-insensitively). */
export function isShadowedByYml(asset, id, claimed) {
return !taskFileOf(asset).endsWith(".yml") && claimed.has(id.toLowerCase());
}
/**
* The ref of the task `input` names in `source`'s bundle: the task's own, else the one a task of that id would have
* (where its adapter would place it), so a task whose file is gone still has the ref its activation was stored under.
*/
export function taskRefIn(source, input) {
const name = taskNameOf(source, input);
const found = findTask(taskScopeOf(source), name);
if (found)
return found.ref;
// An adapter that writes no task places none: a task there is named by its concept id.
const bundle = taskBundle(source);
return makeBundleRef(bundleNameOf(bundle), adapterWrites(bundle, "task") ? addressOf(bundle, conceptIdFromTypeName("task", name)).conceptId : name);
}