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

164 lines (163 loc) • 10.2 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/. import { createHash } from "node:crypto"; import fs from "node:fs"; import path from "node:path"; // asset-io: base the file the index row names, read as the row's adapter indexed it (not the facade's winner for the ref, which assetAtKey would give when two rows share a ref); the facade may not build a file context (facade-fs) import { buildFileContext } from "../../core/adapter/directory/file-context.js"; import { parseBundleRef } from "../../core/asset/asset-ref.js"; import { renderIndexedExecutionSource } from "../../core/assets/gate.js"; import { isContainedResolvedPath, isWithin } from "../../core/common.js"; import { loadConfig } from "../../core/config/config.js"; import { bundlesToSourceEntries } from "../../core/config/config-sources.js"; import { ConfigError, NotFoundError, UsageError } from "../../core/errors.js"; import { warnOnce } from "../../core/warn.js"; import { lookupBundleRef } from "../../indexer/indexer.js"; import { resolveEntryContent, resolveSourceEntries } from "../../indexer/search/search-source.js"; async function defaultLookup(ref) { return lookupBundleRef(ref); } async function effectiveConfig(config) { if (config) return config; return loadConfig(); } function realDirectory(value, label) { let real; let stat; try { real = fs.realpathSync(value); // asset-io: bundle-root root probe stat = fs.statSync(real); } catch { throw new NotFoundError(`${label} is missing or unreadable. Rebuild the index and retry.`, "FILE_NOT_FOUND"); } if (!stat.isDirectory()) throw new ConfigError(`${label} is not a directory.`, "INVALID_CONFIG_FILE"); return real; } function realRegularFile(value, label) { let real; let stat; try { real = fs.realpathSync(value); // asset-io: exec the indexed file akm runs stat = fs.statSync(real); } catch { throw new NotFoundError(`${label} is stale, missing, or unreadable. Rebuild the index and retry.`, "FILE_NOT_FOUND"); } if (!stat.isFile()) throw new NotFoundError(`${label} is not a regular file.`, "FILE_NOT_FOUND"); return real; } function isLexicallyWithin(candidate, root) { const relative = path.relative(path.resolve(root), path.resolve(candidate)); return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative)); } function implicitBundleForEntry(entry, config) { const source = resolveSourceEntries(undefined, config).find(({ bundleId }) => bundleId === entry.bundleId); if (source?.path === undefined) return undefined; const root = realDirectory(source.path, `Canonical implicit source root for ${entry.bundleId}`); const { adapterId } = source; if (adapterId !== entry.adapterId) { warnOnce(`execution-source-adapter-drift:${entry.itemRef}`, `[command] Indexed adapter ${JSON.stringify(entry.adapterId)} for ${JSON.stringify(entry.itemRef)} no longer matches the working source's adapter ${JSON.stringify(adapterId)}; re-resolving from live config. Run \`akm index --full\` to refresh it.`); } return Object.freeze({ id: source.bundleId, root }); } function bundleForEntry(entry, config, realRoot) { const configured = config.bundles?.[entry.bundleId]; if (!configured) { const implicit = implicitBundleForEntry(entry, config); if (implicit) return implicit; throw new ConfigError(`Indexed execution source ${JSON.stringify(entry.itemRef)} belongs to unconfigured bundle ${JSON.stringify(entry.bundleId)}.`, "INVALID_CONFIG_FILE", "Refresh the bundle configuration and rebuild the index before dispatching this asset."); } const configuredAdapter = configured.adapter; if (configuredAdapter && configuredAdapter !== entry.adapterId) { warnOnce(`execution-source-adapter-drift:${entry.itemRef}`, `[command] Indexed adapter ${JSON.stringify(entry.adapterId)} for ${JSON.stringify(entry.itemRef)} no longer matches the bundle config's adapter ${JSON.stringify(configuredAdapter)}; re-resolving from live config. Run \`akm index --full\` to refresh it.`); } const configuredSource = bundlesToSourceEntries(config)?.find((source) => source.name === entry.bundleId); const configuredContent = configuredSource ? resolveEntryContent(configuredSource) : undefined; const configuredContentRoot = configuredContent && "dir" in configuredContent ? configuredContent.dir : undefined; if (!configuredSource || !configuredContentRoot) { const why = configuredContent && "error" in configuredContent ? ` (${configuredContent.error})` : ""; warnOnce(`execution-source-unresolved:${entry.itemRef}`, `[command] Configured source for ${JSON.stringify(entry.itemRef)} no longer resolves to materialized content${why}; dispatching from the indexed location instead. Run \`akm index --full\` after restoring or updating the bundle.`); } else { const lexicalSourceRoot = path.resolve(configuredContentRoot); const lexicalConfiguredRoot = path.resolve(configuredContentRoot, configured.root ?? "."); if (!isLexicallyWithin(lexicalConfiguredRoot, lexicalSourceRoot)) { throw new ConfigError(`Configured bundle root for ${JSON.stringify(entry.itemRef)} resolves outside its materialized bundle source.`, "INVALID_CONFIG_FILE", "Keep bundle roots inside their owning bundle source, then run `akm index --full`."); } const configuredSourceRoot = realDirectory(lexicalSourceRoot, `Configured source root for ${entry.bundleId}`); let configuredRoot; try { configuredRoot = realDirectory(lexicalConfiguredRoot, `Configured bundle root for ${entry.bundleId}`); } catch { throw new ConfigError(`Configured ${JSON.stringify(configuredSource.type)} source for ${JSON.stringify(entry.itemRef)} is not materialized at its current bundle root.`, "INVALID_CONFIG_FILE", "Restore or update the bundle, then run `akm index --full` before dispatching this asset."); } if (!isWithin(configuredRoot, configuredSourceRoot)) { throw new ConfigError(`Configured bundle root for ${JSON.stringify(entry.itemRef)} resolves outside its materialized bundle source.`, "INVALID_CONFIG_FILE", "Remove the escaping symlink or root path, then run `akm index --full`."); } } const writable = configured.writable ?? configured.path !== undefined; return Object.freeze({ id: entry.bundleId, root: realRoot, writable, }); } function expectedIndexedType(kind) { return kind === "command" ? "command" : "agent"; } function assertRenderedIdentity(source, entry, root, content) { const expectedFile = path.relative(path.resolve(root), path.resolve(entry.filePath)).replace(/\\/g, "/"); const expectedHash = createHash("sha256").update(content, "utf8").digest("hex"); if (source.identity.ref !== entry.itemRef || source.identity.bundle !== entry.bundleId || source.identity.adapter !== entry.adapterId || source.identity.file !== expectedFile || source.identity.hash !== expectedHash) { throw new ConfigError(`Execution renderer identity drift for ${JSON.stringify(entry.itemRef)}.`, "INVALID_CONFIG_FILE", "Run `akm index --full`; if the mismatch remains, repair the owning bundle adapter."); } } export async function loadAdapterExecutionSource(refInput, expectedKind, options = {}) { const parsed = parseBundleRef(refInput); if (parsed.fragment !== undefined) { throw new UsageError(`Execution source ${JSON.stringify(refInput)} cannot select a fragment.`, "INVALID_FLAG_VALUE"); } const entry = await (options.lookup ?? defaultLookup)(parsed); if (!entry) { throw new NotFoundError(`Execution source ${JSON.stringify(refInput)} was not found in the local index.`, "ASSET_NOT_FOUND", `Run \`akm index --full\`, then retry, or check the ${expectedKind === "persona" ? "agent" : "command"} ref ${JSON.stringify(refInput)}.`); } const indexedType = expectedIndexedType(expectedKind); if (entry.type !== indexedType) { throw new UsageError(`Execution source ${JSON.stringify(refInput)} resolves to type ${JSON.stringify(entry.type)}, expected ${JSON.stringify(indexedType)}.`, "INVALID_FLAG_VALUE"); } const config = await effectiveConfig(options.config); const root = entry.stashDir; if (root === undefined) { throw new ConfigError(`Indexed execution source ${JSON.stringify(entry.itemRef)} has no filesystem root.`, "INVALID_CONFIG_FILE"); } const realRoot = realDirectory(root, `Indexed bundle root for ${entry.itemRef}`); realRegularFile(entry.filePath, `Indexed execution source ${entry.itemRef}`); // An index row must name a file inside its own bundle root. Checked on the // authored path, so a file that is a symlink to one elsewhere still loads. if (!isContainedResolvedPath(path.resolve(entry.filePath), path.resolve(root))) { throw new ConfigError(`Indexed execution source ${JSON.stringify(entry.itemRef)} resolves outside its bundle root.`, "INVALID_CONFIG_FILE", "Remove the escaping path and rebuild the index."); } const bundle = bundleForEntry(entry, config, realRoot); // asset-io: exec the indexed file akm runs const fileContext = buildFileContext(root, entry.filePath); const rendered = (options.render ?? renderIndexedExecutionSource)(entry, bundle, fileContext); if (!rendered || rendered.kind !== expectedKind) { throw new ConfigError(`Bundle adapter ${JSON.stringify(entry.adapterId)} did not render ${JSON.stringify(entry.itemRef)} as a ${expectedKind}.`, "INVALID_CONFIG_FILE", "Rebuild the index; if the mismatch remains, repair the source file or owning adapter."); } assertRenderedIdentity(rendered, entry, root, fileContext.content()); return rendered; }