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
176 lines (175 loc) • 8.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/.
/**
* Agent CLI spawn wrapper.
*
* Single helper that owns:
* • Process spawn (Bun's subprocess API).
* • Captured vs interactive stdio.
* • Hard timeout (per-call override or profile default).
* • Structured failure reasons — `timeout`, `aborted`, `spawn_failed`,
* `non_zero_exit`.
*
* The command comes from the harness (`harness.build`); this module never
* touches a model. Agents are reachable only via shell-out.
*/
import path from "node:path";
import { stripVTControlCharacters } from "node:util";
import { ConfigError } from "../../core/errors.js";
import { childProcessEnv } from "../../core/paths.js";
import { runManagedSubprocess, streamCaptureFailure } from "../../core/subprocess.js";
import { getHarness } from "../harnesses/index.js";
import { DEFAULT_AGENT_TIMEOUT_MS } from "./config.js";
/**
* The child's env, lowest precedence first: the call's `baseEnv`, else the environment akm runs in with the
* directories this akm resolved set over it, so a child that runs `akm` uses the
* same installation ({@link childProcessEnv}); then the call's `env`. The one
* environment policy for anything an agent run starts: a CLI harness's child, and
* the shell of an embedded session.
*/
export function buildChildEnv(options) {
return { ...(options.baseEnv ?? childProcessEnv()), ...options.env };
}
/**
* This path's phrasing of the SHARED incomplete-capture verdict
* ({@link streamCaptureFailure} in `core/subprocess.ts`). The classification
* lives in the primitive so the agent path and the workflow `exec` path cannot
* drift apart on what "the capture did not complete" means; only the sentence
* naming what ran is local.
*/
function streamFailureMessage(label, stdout, stderr) {
const failures = streamCaptureFailure(stdout, stderr);
return failures === undefined ? undefined : `${label} output capture failed: ${failures}`;
}
/**
* A spawn error's message. An argument list the system refuses (`E2BIG`) names the prompt only when the prompt is what
* the command line carries: a harness that reads it from stdin has another argument to blame.
*/
function spawnFailure(error, stdin, prompt) {
if (error.code !== "E2BIG")
return error.message;
if (stdin === undefined && prompt !== undefined) {
return `the command line is longer than the system allows (${Buffer.byteLength(prompt)} bytes in the prompt argument); this harness takes the prompt on its command line`;
}
return "the command line is longer than the system allows";
}
function failed(reason, error, rest = {}) {
return { ok: false, exitCode: null, stdout: "", stderr: "", durationMs: 0, reason, error, ...rest };
}
/**
* Spawn the agent CLI `profile` names, with the command its harness builds from
* `options.dispatch`, and return a structured result.
*
* Failure modes (see {@link AgentFailureReason}):
*
* • `spawn_failed` — the spawn call threw, or its output could not be captured.
* • `timeout` — exceeded the resolved timeout.
* • `aborted` — the caller's signal fired.
* • `non_zero_exit` — child exited with a non-zero code.
*
* `ok === true` requires exit code 0.
*/
export async function runAgent(profile, options = {}) {
const platform = profile.platform ?? profile.name;
const harness = getHarness(platform);
if (!harness) {
throw new ConfigError(`Agent platform "${platform}" has no registered command builder.`, "INVALID_CONFIG_FILE", "Select a canonical agent platform in harnesses.<name>.platform.");
}
const built = harness.build(profile, options.dispatch ?? {});
const command = {
argv: built.argv,
env: { ...buildChildEnv(options), ...built.env },
stdin: built.stdin,
...(built.failureStream ? { failureStream: built.failureStream } : {}),
};
const label = `agent CLI "${profile.name}"`;
const stdioMode = options.stdio ?? profile.stdio;
const result = await runBuiltCommand(label, command, options, stdioMode);
return built.report && stdioMode === "captured" ? withReport(label, result, built.report(result.stdout)) : result;
}
/**
* The run's result as its harness's own report of it: the reply the program printed, its session id, and the failures
* it reported. A reported error or an unfinished turn is never shown as success.
*/
function withReport(label, result, report) {
const reported = { ...result, stdout: report.reply, ...(report.sessionId ? { sessionId: report.sessionId } : {}) };
const errors = report.errors.join("; ");
if (!result.ok) {
return errors ? { ...reported, error: `${result.error}: ${errors}` } : reported;
}
if (errors) {
return { ...reported, ok: false, reason: "parse_error", error: `${label} reported an error: ${errors}` };
}
if (report.unfinished) {
return {
...reported,
ok: false,
reason: "parse_error",
error: `${label} ended its turn unfinished: ${report.unfinished}`,
};
}
return reported;
}
/** The longest line of a program's own failure message that an error carries. */
const FAILURE_LINE_LIMIT = 300;
/** The last non-empty line of `text`, terminal escapes stripped, cut to {@link FAILURE_LINE_LIMIT}; undefined when there is none. The one reader of a program's own failure line. */
export function lastOutputLine(text) {
const lines = stripVTControlCharacters(text)
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => line !== "");
return lines.at(-1)?.slice(0, FAILURE_LINE_LIMIT);
}
/**
* Run a command that is already built and return a structured result: the part
* of {@link runAgent} that does not depend on which harness built the command,
* which akm's own runtime (`harnesses/opencode/runtime/`) shares. `label` names
* what ran in the failure messages.
*/
export async function runBuiltCommand(label, { argv, env, stdin, failureStream }, options, stdioMode = options.stdio ?? "captured") {
// null = explicitly disabled (no kill timer). undefined = runtime default.
const timeoutMs = options.timeoutMs !== undefined ? options.timeoutMs : DEFAULT_AGENT_TIMEOUT_MS;
// Cooperative cancel: refuse to spawn at all when the caller's signal is
// already aborted (e.g. the run's budget was exhausted before this unit).
if (options.signal?.aborted) {
return failed("aborted", `${label} not started: caller signal already aborted`);
}
// Spawn/timeout/abort/capture are owned by the managed-subprocess primitive
// (src/core/subprocess.ts): process-GROUP spawn (detached in captured mode),
// the SIGINT→SIGTERM→SIGKILL kill ladder on timeout/abort, bounded output capture,
// and the optional stdin payload. This keeps the agent-specific surface:
// the failure taxonomy.
const start = Date.now();
// A program started after `cd <dir>` has PWD equal to <dir>, and OpenCode takes its directory from PWD before its
// own working directory: the PWD akm inherits names where akm was started, so a run given a directory names it. One
// path is both, so they agree even where the kernel would resolve a `..` after a symbolic link elsewhere.
const cwd = options.cwd ? path.resolve(options.cwd) : undefined;
const result = await runManagedSubprocess([...argv], {
capture: stdioMode === "captured",
env: { ...env, ...(cwd ? { PWD: cwd } : {}) },
...(cwd ? { cwd } : {}),
...(stdin !== undefined ? { stdin } : {}),
timeoutMs,
...(options.signal ? { signal: options.signal } : {}),
});
const durationMs = Date.now() - start;
if (result.spawnError)
return failed("spawn_failed", spawnFailure(result.spawnError, stdin, options.dispatch?.prompt), { durationMs });
const { exitCode, stdout, stderr } = result;
const output = { exitCode, stdout, stderr, durationMs };
if (result.aborted) {
return failed("aborted", `${label} aborted by caller signal`, output);
}
if (result.timedOut) {
return failed("timeout", `${label} timed out after ${timeoutMs ?? 0}ms`, output);
}
const captureFailure = streamFailureMessage(label, result.stdoutRead, result.stderrRead);
if (captureFailure)
return failed("spawn_failed", captureFailure, output);
if (exitCode !== 0) {
const said = failureStream ? lastOutputLine(failureStream === "stdout" ? stdout : stderr) : undefined;
return failed("non_zero_exit", `${label} exited with code ${exitCode}${said ? `: ${said}` : ""}`, output);
}
return { ok: true, ...output };
}