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

319 lines (318 loc) • 16.4 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/. /** * `akm env` command family. The ref-resolution helpers * (parseEnvRef / makeEnvRef / resolveEnvPath) live in src/core/env-secret-ref.ts so env + secret share one * copy. * * `akm env` manages whole `.env` files under each stash's env/ directory. * Values and comment text are NEVER written to stdout or structured output — * only key NAMES are surfaced (comments routinely contain commented-out * credentials). akm does not manage individual entries; * you edit the `.env` file yourself and akm loads it. */ import fs from "node:fs"; import path from "node:path"; import { getParsedInvocation } from "../../cli/invocation.js"; import { getStringArg } from "../../cli/parse-args.js"; import { defineGroupCommand, defineJsonCommand, output, reportChildExit } from "../../cli/shared.js"; import { addressOf } from "../../core/assets/write.js"; import { writeFileAtomic } from "../../core/common.js"; import { findWriteTargetAsset, listEnvsRecursive, makeEnvRef, resolveEnvPath, resolveEnvWriteTarget, writeEnvSecret, } from "../../core/env-secret-ref.js"; import { NotFoundError, UsageError } from "../../core/errors.js"; import { stderr, stdout } from "../../core/stdio.js"; import { assertWritePathsInsideSource, requireWriteTargetPath } from "../../core/write-source.js"; import { readStdin } from "../../runtime.js"; import { buildChildEnv } from "./child-env.js"; import { runProgram } from "./injection.js"; const envListCommand = defineJsonCommand({ meta: { name: "list", description: "List all env files across all bundles with their key names (no values)" }, async run() { output("env-list", { envs: listEnvsRecursive() }); }, }); const envCreateCommand = defineJsonCommand({ meta: { name: "create", description: "Create an env file (empty by default; seed an existing `.env` with --from-file or --from-stdin). No-op if it already exists and no source is given.", }, args: { name: { type: "positional", description: "Env ref (flat name, e.g. env/prod → prod.env; use --path for a subdirectory)", required: true, }, path: { type: "string", description: "Subdirectory under env/ (e.g. 'staging')", }, "from-file": { type: "string", description: "Seed the env file from an existing .env at this path" }, "from-stdin": { type: "boolean", description: "Seed the env file from stdin", default: false }, bundle: { type: "string", description: "Write destination: a source name (default: defaultWriteTarget)", }, }, async run({ args }) { // `--path` is the subdirectory; `--bundle` selects the writable destination bundle. const resolution = resolveEnvWriteTarget(args.name, args.bundle, { subPath: getStringArg(args, "path") }); const { ref } = resolution; const { source } = resolution.target; const held = addressOf(source, `${resolution.type}/${resolution.name}`); const exists = held.exists; const fromFile = args["from-file"]; const fromStdin = args["from-stdin"] === true; if (fromFile !== undefined && fromStdin) { throw new UsageError("Pass only one of --from-file or --from-stdin.", "INVALID_FLAG_VALUE"); } let content; if (fromFile !== undefined || fromStdin) { // Ingest path: never silently clobber an existing env file. if (exists) { throw new UsageError(`Env "${ref}" already exists. Remove it first (\`akm env remove\`) or edit the file directly.`, "RESOURCE_ALREADY_EXISTS"); } if (fromFile !== undefined) { // asset-io: user-input --from-file, --out if (!fs.existsSync(fromFile)) { throw new NotFoundError(`Source file not found: ${fromFile}`, "FILE_NOT_FOUND"); } // asset-io: user-input --from-file, --out content = fs.readFileSync(fromFile, "utf8"); } else { const buf = await readStdin(); content = buf.toString("utf8"); } } // Without content, an env kept in the file a create writes is left as it is; one kept under another spelling is refused. if (exists && content === undefined && held.file !== undefined && held.heldElsewhere === true) { throw new UsageError(`Env "${ref}" already exists as ${path.relative(requireWriteTargetPath(source), held.file).split(path.sep).join("/")}. Remove it first (\`akm env remove\`) or edit the file directly.`, "RESOURCE_ALREADY_EXISTS"); } if (!exists || content !== undefined) { writeEnvSecret(resolution, { op: "create", content: content ?? "", exclusive: true }); } else { // Left as it is after the same path check a create would apply. if (held.file !== undefined) assertWritePathsInsideSource(source, [held.file]); } output("env-create", { ref }); }, }); const envPathCommand = defineJsonCommand({ meta: { name: "path", description: "Print the absolute env file path (Docker `_FILE` convention / `--env-file`). To inject values, run a script with `akm run --env <ref> scripts/<file>` — do NOT `source` the raw file.", }, args: { ref: { type: "positional", description: "Env ref", required: true }, quiet: { type: "boolean", alias: "q", description: "Suppress the unsafe-source warning", default: false }, }, async run({ args }) { const { asset } = resolveEnvPath(args.ref); // asset-io: display `env path` prints the file const absPath = asset.entry.file; if (absPath === undefined) throw new UsageError(`"${asset.ref}" is not kept in a file, so it has no path.`); // The raw `.env` may contain `X=$(cmd)`, which executes if `source`d. // Warning goes to stderr (never contaminates the path on stdout) and is // suppressed with --quiet for the legitimate `_FILE` / `--env-file` use. if (args.quiet !== true) { stderr().write(`warning: this is the raw file path. Do NOT \`source\` it (shell substitutions in the file would execute).\n` + ` To inject values run a script: akm run --env ${args.ref} scripts/<file>\n`); } // F3/B3: this stdout write IS the payload — a bare absolute path for // shell substitution (`$(akm env path <ref>)`, Docker `_FILE` / // `--env-file`) — not a field inside a result envelope. `env path` is // now declared format-exempt (src/output/format-exempt.ts, same // classification as `env run`/`secret run`/`help`), so `--format` // WARNS rather than doing anything to this write (src/cli.ts's startup // `isFormatExemptCommand` check). An earlier version of this fix routed // this through `output()` with a `{ path }` envelope so `--format` // "worked" — but the CLI's process-wide default format is `json`, so a // bare `akm env path <ref>` (exactly how `$(akm env path foo)` is // written, with no explicit `--format`) started emitting // `{"path":"..."}` instead of the raw path, breaking every existing // shell substitution silently. Declaring the exemption is the correct // fix: it keeps this byte-identical to history and makes the // already-broken combination (`--format` + this command) loud instead // of silent, per STABILITY.md's promise for exempt commands. stdout().write(`${absPath}\n`); }, }); const envExportCommand = defineJsonCommand({ meta: { name: "export", description: "Write safe `export KEY='value'` lines to a file (mode 0600) for `source`-ing — requires --out <path>. Values are re-serialised single-quoted so a raw `.env` cannot execute on load, and are NEVER printed to stdout. To use values directly, put the command in a script asset and run it with `akm run --env <ref> scripts/<file>`.", }, args: { ref: { type: "positional", description: "Env ref", required: true }, out: { type: "string", alias: "o", description: "Destination file (required). Written at mode 0600." }, }, async run({ args }) { const outPath = args.out; if (!outPath) { throw new UsageError("`akm env export` writes to a file — pass --out <path>.\n" + " To use values directly, put the command in a script asset and run it with\n" + " `akm run --env <ref> scripts/<file>`. export never prints values to stdout, to avoid leaking them into a captured context.", "MISSING_REQUIRED_ARGUMENT"); } const { written, asset } = resolveEnvPath(args.ref); const { buildShellExportScript } = await import("./env.js"); const resolvedOut = path.resolve(outPath); // asset-io: user-input --from-file, --out writeFileAtomic(resolvedOut, buildShellExportScript(asset.entry.content()), 0o600); output("env-export", { ref: makeEnvRef(written, asset.bundle), out: resolvedOut }); }, }); /** * Shared implementation for `env run`. Injects an entire env file's values into * the child process env — never via a shell. */ async function runEnvInjected(target, opts) { const command = getParsedInvocation().passthroughArgs(); if (command.length === 0) { throw new UsageError("Missing command. Usage: akm env run <ref> -- <command>"); } try { resolveEnvPath(target); } catch (error) { if (!(error instanceof NotFoundError)) throw error; // Help users who reach for the removed single-key `ref/KEY` form. const slash = target.lastIndexOf("/"); if (slash > 0) { const maybeKey = target.slice(slash + 1); if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(maybeKey)) { let baseExists = false; try { resolveEnvPath(target.slice(0, slash)); baseExists = true; } catch { baseExists = false; } if (baseExists) { throw new UsageError(`'akm env run' injects the whole file; the single-key '<ref>/${maybeKey}' form was removed.\n` + ` For one value use a secret: \`akm run --secret secrets/${maybeKey}:${maybeKey} scripts/<file>\`.`, "INVALID_FLAG_VALUE"); } } } throw error; } // Load → filter → secret-substitute → keys-only // audit event. Shared with the workflow engine's per-unit env bindings — // see env-binding.ts for the extracted core and its safety invariants. const { resolveEnvBinding } = await import("./env-binding.js"); const { values: envValues } = resolveEnvBinding(target, { only: opts.only, except: opts.except, }); const mergedEnv = buildChildEnv(process.env, { clean: opts.clean === true, inherit: opts.inherit ?? [], }); for (const [envKey, envValue] of Object.entries(envValues)) { mergedEnv[envKey] = envValue; } const result = await runProgram({ argv: command, env: mergedEnv, capture: false }); // Set `process.exitCode` and return rather than calling `process.exit`, which // would skip the `finally { disposeLlmUsageSink(); }` block in src/cli.ts's // `runCommand`. The process still exits with the child's exact status once the // event loop drains, the pattern `emitJsonError` (src/cli/shared.ts) uses. reportChildExit(result.exitCode ?? 0); return; } /** Parse a comma/space-separated key list flag into a trimmed, non-empty array. */ function parseKeyListFlag(raw) { if (raw === undefined) return undefined; const keys = raw .split(/[,\s]+/) .map((k) => k.trim()) .filter(Boolean); return keys.length > 0 ? keys : undefined; } const envRunCommand = defineJsonCommand({ meta: { name: "run", description: "Deprecated; put the command in a script asset under scripts/, run with `akm run --env <ref> scripts/<file>`; removed in 0.11. Run a command with the env file injected into its environment: `akm env run <ref> -- <command>`. Use `-- $SHELL` for an interactive session. Restrict which variables are injected with --only / --except. Values may embed `${ref}` tokens, replaced at run time: a `${secrets/NAME}` (or `${bundle//secrets/NAME}`) token with the secret's value, any other asset ref with its absolute path. Pass --clean to start the child with a minimal inherited environment instead of the full parent environment.", }, args: { target: { type: "positional", description: "Env ref", required: true }, only: { type: "string", description: "Inject ONLY these keys (comma-separated). Mutually exclusive with --except.", }, except: { type: "string", description: "Inject all keys EXCEPT these (comma-separated)." }, clean: { type: "boolean", description: "Start the child with a minimal inherited environment", default: false, }, inherit: { type: "string", description: "With --clean, also inherit these parent env vars (comma-separated)", }, // Deprecated no-op, accepted through 0.10 so scripts that pass it do not // fail with UNKNOWN_FLAG. Installing a bundle is the trust decision: env // run no longer blocks process-hijacking keys. "allow-dangerous-env-keys": { type: "boolean", description: "Deprecated, no effect (accepted through 0.10)", default: false, }, }, async run({ args }) { await runEnvInjected(args.target, { only: parseKeyListFlag(args.only), except: parseKeyListFlag(args.except), clean: args.clean === true, inherit: parseKeyListFlag(args.inherit) ?? [], }); }, }); const envRemoveCommand = defineJsonCommand({ meta: { name: "remove", description: "Remove an env file" }, args: { ref: { type: "positional", description: "Env ref", required: true }, yes: { type: "boolean", alias: "y", description: "Skip confirmation prompt", default: false }, bundle: { type: "string", description: "Write destination: a source name (default: defaultWriteTarget)", }, }, async run({ args }) { const resolution = resolveEnvWriteTarget(args.ref, args.bundle); const { ref } = resolution; const { confirmDestructive } = await import("../../cli/confirm.js"); const confirmed = await confirmDestructive(`Remove env "${args.ref}"? This cannot be undone.`, { yes: args.yes === true, }); if (!confirmed) { stderr().write("Aborted.\n"); return; } if (!findWriteTargetAsset(resolution)) throw new NotFoundError(`Env not found: ${ref}`); writeEnvSecret(resolution, { op: "delete" }); output("env-remove", { ref, removed: true }); }, }); export const envCommand = defineGroupCommand({ meta: { name: "env", description: "Manage `.env` files — configuration values an app loads together (URLs, flags, and any credentials it needs).\n\n" + "Values may or may not be sensitive; akm protects them all the same way — key names are visible, values never appear in structured output. For a single sensitive value used on its own (an auth token, key, or cert), use `akm secret`.", }, subCommands: { list: envListCommand, path: envPathCommand, export: envExportCommand, run: envRunCommand, create: envCreateCommand, remove: envRemoveCommand, }, // Bare `akm env` runs `akm env list` (see insertBareListSubcommand in src/cli.ts). });