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
108 lines (107 loc) • 5.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/.
/**
* Env-ref → resolved values, shared between `akm env run` and the workflow
* engine's per-unit env bindings (orchestration plan, *Dispatch context*).
*
* Extracted from `env-cli.ts`'s `runEnvInjected` so the native executor
* REUSES the exact same machinery instead of forking it. Every safety
* invariant carries over unchanged:
*
* - `${ref}` tokens resolve through the one ref walk (a `secrets/` ref to the
* secret's trimmed value, any other asset ref to its absolute path); a
* missing ref is a hard error and NOTHING is injected (no partial injection).
* - An `env_access` audit event records key NAMES only, never values.
* - Resolved values must never be written to stdout or logs by callers.
*/
import { unindexedHint } from "../../core/assets/read.js";
import { assetType } from "../../core/assets/type.js";
import { isInstalledBundle, makeEnvRef, resolveEnvPath, resolveRefOwner, secretValueOf, } from "../../core/env-secret-ref.js";
import { NotFoundError, UsageError } from "../../core/errors.js";
import { appendEvent } from "../../core/events.js";
import { substituteRefTokens } from "../../core/ref-token.js";
import { stderr } from "../../core/stdio.js";
import { warnOnce } from "../../core/warn.js";
import { parseEnvText } from "./env.js";
/** The retired `${secret:NAME}` env-value token (see `resolveEnvBinding`). */
const LEGACY_SECRET_TOKEN_RE = /\$\{secret:([^}\s]+)\}/g;
/**
* What a `${ref}` token stands for: a `secrets/` ref yields the secret's
* trimmed value, any other asset ref its absolute path, a ref no bundle owns
* `undefined`. The one resolver behind env values and exec argv.
*/
export function resolveRefToken(ref, from) {
const asset = resolveRefOwner(ref, from);
if (asset === undefined)
return undefined;
if (assetType(asset) === "secret")
return { kind: "secret", value: secretValueOf(asset) };
// asset-io: exec a `${ref}` token is the asset's path, handed to a program
if (asset.entry.file === undefined)
throw new UsageError(`"${asset.ref}" is not kept in a file, so it has no path.`);
return { kind: "path", path: asset.entry.file }; // asset-io: exec
}
/**
* Resolve an env ref to its injectable values: load the file, apply key
* filtering, substitute `${ref}` tokens, and append the keys-only
* `env_access` audit event.
*/
export function resolveEnvBinding(target, options = {}) {
const warn = options.warn ?? ((message) => stderr().write(`warning: ${message}\n`));
const { written, asset } = resolveEnvPath(target);
const bundleId = asset.bundle;
const envRef = makeEnvRef(written, bundleId);
const allValues = parseEnvText(asset.entry.content());
// Value-safe key filtering (--only / --except operate on key NAMES only).
let envValues = allValues;
if (options.only && options.except) {
throw new UsageError("Pass only one of --only or --except.", "INVALID_FLAG_VALUE");
}
if (options.only) {
const wanted = new Set(options.only);
const missing = options.only.filter((k) => !(k in allValues));
if (missing.length > 0) {
warn(`--only key(s) not present in ${envRef}: ${missing.join(", ")}`);
}
envValues = Object.fromEntries(Object.entries(allValues).filter(([k]) => wanted.has(k)));
}
else if (options.except) {
const excluded = new Set(options.except);
envValues = Object.fromEntries(Object.entries(allValues).filter(([k]) => !excluded.has(k)));
}
// Read-compat: env files written for 0.9 / early 0.10 spell a secret
// `${secret:NAME}`, meaning `secrets/NAME` in this env asset's own bundle.
// Read it as the `${ref}` it stands for; the file is bundle content and is
// never rewritten.
let firstLegacy;
envValues = Object.fromEntries(Object.entries(envValues).map(([key, value]) => [
key,
value.replace(LEGACY_SECRET_TOKEN_RE, (_token, secretName) => {
const spelling = `\${${bundleId}//secrets/${secretName}}`;
firstLegacy ??= spelling;
return spelling;
}),
]));
if (firstLegacy !== undefined) {
warnOnce(`legacy-secret-token:${envRef}`, `Env "${envRef}" uses the retired \${secret:NAME} spelling; reading it as ${firstLegacy}. Write the full ref in the env file.`);
}
// Substitute `${ref}` tokens. A missing ref is a hard error — inject NOTHING.
const { values: substituted, missing, secretValues, } = substituteRefTokens(envValues,
// A ref in the env file is looked up in the env's own bundle first, then in the configured order (§0.2 A9).
options.locateOnly
? (ref) => (resolveRefOwner(ref, { bundle: bundleId }) ? { kind: "path", path: "" } : undefined)
: (ref) => resolveRefToken(ref, { bundle: bundleId }), isInstalledBundle);
if (missing.length > 0) {
throw new NotFoundError(`Env "${envRef}" references asset(s) that no bundle owns: ${missing.join(", ")}. Nothing was injected.`, "FILE_NOT_FOUND", [
"Write each `${ref}` as a full akm ref that exists, e.g. `${secrets/name}` or `${team//scripts/run.sh}`.",
...new Set(missing.map(unindexedHint).filter((hint) => hint !== undefined)),
].join(" "));
}
envValues = substituted;
const keys = Object.keys(envValues);
// Audit trail: keys only, never values; the ref is the asset's, not the spelling the caller wrote.
if (!options.locateOnly)
appendEvent({ eventType: "env_access", ref: makeEnvRef(asset.conceptId, bundleId), metadata: { keys } });
return { ref: envRef, values: envValues, keys, secretValues };
}