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
691 lines (690 loc) • 33.4 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/.
/**
* Running a version 5 task: a start or a `--resume`, its steps in order, the tasks they run as runs of their own, the
* state, the working folder, the lock and the history. What a start accepts is `checkTaskV5`'s (`./check.ts`), which
* is called with the start's inputs and flags before anything runs. Every other rule is called from the component that
* owns it: `runProgram` runs `exec:` and script steps, `akmAgentDispatch` and the command path run the agent steps,
* `buildChildEnv` makes a step's clean environment, `redactSensitiveValue` removes secret values from a result.
*
* A run keeps its state in `$AKM_STATE_DIR/runs/<task>/<run>.state.json` while it can be resumed, and works in
* `$AKM_STATE_DIR/runs/<task>/<run>/` unless `cwd:` or `--cwd` names a folder. Both are removed when the run succeeds.
*/
import { createHash, randomBytes } from "node:crypto";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { parseTimeoutValue } from "../../cli/parse-args.js";
import { selectionFromArgs } from "../../cli/selection.js";
import { akmAgentDispatch } from "../../commands/agent/agent-dispatch.js";
import { dispatchPreparedCommandInvocation, executeCommandInvocation, prepareCommandInvocation, } from "../../commands/command/command-execution.js";
import { buildChildEnv } from "../../commands/env/child-env.js";
import { ensureWorkingFolder, resolveInjectionRefs, runProgram } from "../../commands/env/injection.js";
import { makeBundleRef, parseBundleRef } from "../../core/asset/asset-ref.js";
import { loadConfig } from "../../core/config/config.js";
import { rethrowIfTestIsolationError, TransientError, UsageError } from "../../core/errors.js";
import { releaseLock } from "../../core/file-lock.js";
import { childProcessEnv } from "../../core/paths.js";
import { collectInferredSecretValues, collectSensitiveValues, redactSensitiveValue } from "../../core/redaction.js";
import { REF_TOKEN_RE } from "../../core/ref-token.js";
import { formatLockHolderPid, tryAcquireRunLock } from "../../core/run-lock.js";
import { streamCaptureFailure } from "../../core/subprocess.js";
import { applyInputDefaults, materializeInputFlags, validateInputs, } from "../../execution/input-contract.js";
import { withRetries } from "../../execution/retry.js";
import { scriptProgram } from "../frozen-script.js";
import { abortOnTermination, acquireTaskRunLock, reserveTaskAttempt, runRecordPath, runsFolder, taskRunLockPath, } from "../run/attempt-lifecycle.js";
import { resolveProvenanceContext, taskEventSource } from "../run/provenance.js";
import { reconcileAbandonedExecutionState } from "../run/reconcile-abandoned.js";
import { shellCommand } from "../run/run-native-task.js";
import { expectLoop } from "../run/run-steps-task.js";
import { appendHistory, readTaskHistory } from "../run/task-history.js";
import { appendStreamLines, persistRunLog, processFailure, resolveTaskLogPath } from "../run/task-log.js";
import { parseTaskSource } from "../source/parse-task-source.js";
import { TASK_V5_INPUT_DIAGNOSTICS } from "../source/task-input-diagnostics.js";
import { checkTaskV5, locateTaskV5Asset } from "./check.js";
import { TASK_V5_SINGLE_STEP, taskV5StepKey, taskV5StepLabel, } from "./source.js";
/** The limit of a step that has no `timeout:` on it or at the top of its task. */
const DEFAULT_STEP_TIMEOUT = "30m";
const WHOLE_TOKEN = /^\$\{([^}\s]+)\}$/;
/** A value as text: text as it is, anything else as JSON. */
const asText = (value) => (typeof value === "string" ? value : JSON.stringify(value));
function taskIdOf(ref) {
const { conceptId } = parseBundleRef(ref);
return conceptId.slice(conceptId.indexOf("/") + 1);
}
/** `[bundle//]tasks/<name>` read from `bundle`, as `bundle//tasks/<name>`: the identity of a task across bundles. */
function qualifiedRef(bundle, ref) {
return makeBundleRef(bundle.name, parseBundleRef(ref).conceptId);
}
function newRunId(at) {
return `${at.toISOString().replace(/[:.]/g, "-")}-${randomBytes(3).toString("hex")}`;
}
function writeRecord(record) {
const file = runRecordPath(record.taskId, record.runId);
fs.mkdirSync(path.dirname(file), { recursive: true });
const pending = `${file}.${process.pid}.tmp`;
// asset-io: state run record
fs.writeFileSync(pending, JSON.stringify(record));
// asset-io: state run record
fs.renameSync(pending, file);
}
function readRecord(taskId, runId) {
try {
// asset-io: state run record
return JSON.parse(fs.readFileSync(runRecordPath(taskId, runId), "utf8"));
}
catch (error) {
if (error.code === "ENOENT")
return undefined;
throw error;
}
}
/** A run that will not be resumed: the folder akm made for it and for the runs it started, and what is kept of it. */
function discard(record) {
// asset-io: scratch run folder akm made
if (record.madeDir)
fs.rmSync(record.dir, { recursive: true, force: true });
// asset-io: state run record
fs.rmSync(runRecordPath(record.taskId, record.runId), { force: true });
for (const child of Object.values(record.children)) {
const kept = readRecord(child.task, child.run);
if (kept)
discard(kept);
}
}
/** The failed or interrupted runs of a task (by its bundle and id) that were started directly, newest first, that can still be resumed. */
function resumableRuns(task) {
const found = [];
for (const row of readTaskHistory({ id: task.taskId, limit: 500 })) {
if (!row.run || row.run.parent || (row.status !== "failed" && row.status !== "interrupted"))
continue;
const kept = readRecord(task.taskId, row.run.id);
if (kept &&
qualifiedRef(kept.bundle, kept.ref) === task.ref &&
!found.some((earlier) => earlier.runId === kept.runId))
found.push(kept);
}
return found;
}
/**
* The inputs a run has: those given, converted to their types, with their defaults; one not given is empty text.
* `literals` are values a calling step gives that no flag can carry: an input that declares no type takes them as they are.
*/
function resolveInputs(document, flags, literals = {}) {
const contract = document.inputs ?? {};
const given = { ...materializeInputFlags(contract, flags, TASK_V5_INPUT_DIAGNOSTICS), ...literals };
const defaulted = applyInputDefaults(contract, given);
const errors = validateInputs(contract, defaulted);
if (errors.length > 0)
throw TASK_V5_INPUT_DIAGNOSTICS.contractViolation(errors);
const state = {};
for (const name of Object.keys(contract))
state[name] = name in defaulted ? defaulted[name] : "";
return state;
}
/** What a calling step's `args:` give a task: as the command line gives them, or, for a value of no type, as it is. */
function stepInputs(child, step, state) {
const flags = [];
const literals = {};
for (const { name, value } of step.taskInputs ?? []) {
const given = argument(value, state);
if (typeof given === "boolean") {
// As `--name true` binds on the command line: text for a typed input, and as it is for one that declares no type.
flags.push({ name, value: child.inputs?.[name]?.schema.type === undefined ? given : String(given) });
}
else if (typeof given === "string")
flags.push({ name, value: given });
else if (typeof given === "object" && given !== null && child.inputs?.[name]?.schema.type === undefined) {
literals[name] = given;
}
else
flags.push({ name, value: JSON.stringify(given) });
}
return resolveInputs(child, flags, literals);
}
function parseDocument(found) {
const parsed = parseTaskSource({ yaml: found.asset.entry.content(), filePath: found.file });
if (parsed.version === 4) {
throw new UsageError(`${found.file} is a version 4 task, and a version 5 task does not run one.`, "TASK_SOURCE_INVALID");
}
return parsed.v5;
}
/** The options of a step: its own, or those at the top of its task. */
function option(document, step, key) {
return step.options[key] ?? document.options[key];
}
/**
* Everything checked before anything runs: the task and every task it runs, for this start's inputs and flags
* (`checkTaskV5`), and, for a `--resume`, that there is a run to continue.
*/
export async function prepareRunV5(task, options) {
const start = options.start?.(task.valueInputs) ?? {
flags: {},
resume: false,
skipIfLocked: false,
inputs: options.inputFlags?.(task.valueInputs) ?? [],
};
try {
reconcileAbandonedExecutionState();
}
catch (error) {
rethrowIfTestIsolationError(error);
// Settling abandoned state is housekeeping; it never prevents a run.
}
if (start.resume) {
const dropped = [
...start.inputs.map((input) => `--${input.name}`),
...Object.keys(start.flags).map((key) => `--${key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}`),
];
if (dropped.length > 0) {
throw new UsageError(`A resumed run uses the inputs and flags it was started with, so --resume does not take ${dropped.join(", ")}.`, "INVALID_FLAG_VALUE", "Run the task without --resume to start it again with other inputs or flags.");
}
const [resume] = resumableRuns({ taskId: task.taskId, ref: qualifiedRef(task.bundle, task.ref) });
if (!resume)
throw noRunToResume(task.taskId);
const document = await checkTaskV5({
ref: task.ref,
bundle: task.bundle,
inputs: resume.inputs,
flags: resume.flags,
});
return { task, start, document, resume, flagged: resume.inputs };
}
const document = await checkTaskV5({ ref: task.ref, bundle: task.bundle, inputs: start.inputs, flags: start.flags });
return { task, start, document, inputs: resolveInputs(document, start.inputs), flagged: start.inputs };
}
/** Run a prepared start. A held lock is `RUN_LEASE_HELD` (exit 75), or a skipped start when `--scheduled` or `--skip-if-locked` says so. */
export async function runPreparedV5(prepared, options) {
const { task, start, document } = prepared;
const provenance = resolveProvenanceContext(options.provenance, options.scheduled === true);
const now = options.now ?? (() => new Date());
const host = options.hostEnv ?? process.env;
const flags = prepared.resume?.flags ?? start.flags;
const lock = document.lock === true
? acquireTaskRunLock(task.taskId, qualifiedRef(task.bundle, task.ref), {
skip: provenance.scheduled || start.skipIfLocked,
at: now(),
})
: undefined;
if (lock && "skipped" in lock)
return lock.skipped;
const termination = abortOnTermination();
const context = {
options,
host,
now,
scheduled: provenance.scheduled,
provenance,
secrets: new Set(),
abort: termination.abort,
environments: new Map(),
};
let runLock;
try {
await collectSecrets(context, task.ref, task.bundle, flags, new Set());
let record;
if (prepared.resume) {
runLock = lockRun(prepared.resume);
const kept = readRecord(task.taskId, prepared.resume.runId);
if (!kept)
throw noRunToResume(task.taskId);
record = kept;
}
else {
record = newRecord(context, task.ref, task.taskId, task.bundle, document, flags, prepared.inputs ?? {}, prepared.flagged);
}
const until = flags.timeout === undefined ? Number.POSITIVE_INFINITY : Date.now() + parseTimeoutValue(String(flags.timeout));
const result = await runAttempt(context, record, document, until);
if (result.status === "completed")
discardEarlierFailedRuns(record);
return result;
}
finally {
termination.stop();
if (runLock)
releaseLock(runLock);
if (lock)
releaseLock(lock.ownership);
}
}
function noRunToResume(taskId) {
return new UsageError(`Task ${JSON.stringify(taskId)} has no failed run to resume. Run it without --resume.`, "INVALID_FLAG_VALUE");
}
/** One attempt at a run at a time: a run that is being resumed is not resumed again until that attempt ends. */
function lockRun(record) {
const acquired = tryAcquireRunLock(path.join(runsFolder(record.taskId), `${record.runId}.lock`), {
label: "task run",
});
if (acquired.state === "held") {
throw new TransientError(`Run ${record.runId} of task ${record.taskId} is still running (PID ${formatLockHolderPid(acquired.holder)}, started ${acquired.holder.startedAt}); not resuming it again.`, "RUN_LEASE_HELD");
}
return acquired.ownership;
}
/** When a run of a task succeeds, the failed runs before it are not resumed: what is kept of them goes too. */
function discardEarlierFailedRuns(record) {
if (record.parent)
return;
for (const earlier of resumableRuns({ taskId: record.taskId, ref: qualifiedRef(record.bundle, record.ref) }))
if (earlier.runId !== record.runId)
discard(earlier);
}
/** A new run: its inputs, and a working folder of its own unless `--cwd` or the task's `cwd:` names one. */
function newRecord(context, ref, taskId, bundle, document, flags, state, inputs, parent, stepName) {
const runId = newRunId(context.now());
const named = parent === undefined && flags.cwd !== undefined
? flags.cwd
: document.options.cwd === undefined
? undefined
: path.resolve(bundle.dir, document.options.cwd);
// A folder that is named is made if it is not there, and never removed.
const dir = named === undefined ? path.join(runsFolder(taskId), runId) : ensureWorkingFolder(named);
if (named === undefined)
fs.mkdirSync(dir, { recursive: true });
const record = {
ref,
taskId,
bundle,
runId,
...(parent ? { parent: { task: parent.taskId, run: parent.runId, step: stepName } } : {}),
inputs,
state,
steps: document.steps.map((step) => ({
name: step.name,
status: "pending",
kind: taskV5StepKey(step),
hash: stepHash(step),
})),
children: {},
flags,
dir,
madeDir: named === undefined,
};
writeRecord(record);
return record;
}
// ── Running ─────────────────────────────────────────────────────────────────
function stepHash(step) {
return createHash("sha256").update(JSON.stringify(step)).digest("hex");
}
/** A run is resumed only when its task has the steps it had, and each step it finished is as it was: what a recorded step finished belongs to that step. */
function assertSameSteps(record, document) {
const recorded = record.steps.map((step) => step.name);
if (recorded.length !== document.steps.length ||
document.steps.some((step, index) => step.name !== recorded[index])) {
throw new UsageError(`Task ${JSON.stringify(record.taskId)} changed its steps since the failed run. Run it without --resume.`, "INVALID_FLAG_VALUE");
}
const changed = document.steps.find((step, index) => {
const kept = record.steps[index];
return kept.status === "completed" && kept.hash !== undefined && kept.hash !== stepHash(step);
});
if (changed) {
throw new UsageError(`Task ${JSON.stringify(record.taskId)} changed step ${JSON.stringify(taskV5StepLabel(changed.name))}, which the failed run had finished. Run it without --resume.`, "INVALID_FLAG_VALUE");
}
}
/** One attempt at a run, from its first unfinished step: one history row, and the steps it ran. */
async function runAttempt(context, record, document, until) {
assertSameSteps(record, document);
const attempt = reserveTaskAttempt(record.taskId, context.now(), {
id: record.runId,
...(record.parent ? { parent: record.parent } : {}),
});
const startedAt = attempt.startedAt;
const lines = [`[akm task] task=${record.taskId} run=${record.runId} steps=${document.steps.length}`];
const dbLines = [{ line: lines[0] }];
const steps = [];
let failure;
let result;
for (const step of document.steps) {
const kept = record.steps.find((recorded) => recorded.name === step.name);
const kind = taskV5StepKey(step);
const name = taskV5StepLabel(step.name);
if (kept.status === "completed") {
result = record.state[step.name];
steps.push({ name, kind, status: "reused", durationMs: 0, attempts: 0 });
continue;
}
if (failure) {
steps.push({ name, kind, status: "skipped", durationMs: 0, attempts: 0 });
continue;
}
const begun = context.now();
const outcome = await runStep(context, record, document, step, until);
const durationMs = Math.max(0, context.now().getTime() - begun.getTime());
const reason = outcome.ok ? undefined : scrub(context, outcome.reason ?? "failed");
const header = `[akm task] step=${name} kind=${kind} attempts=${outcome.attempts} ok=${outcome.ok}`;
// Loops, not spreads: a step can print more lines than a call accepts as arguments.
lines.push(header);
for (const line of outcome.lines)
lines.push(line);
dbLines.push({ level: outcome.ok ? "info" : "error", line: header });
for (const row of outcome.dbLines)
dbLines.push(row);
steps.push({
name,
kind,
status: outcome.ok ? "completed" : "failed",
durationMs,
attempts: outcome.attempts,
...(reason ? { reason } : {}),
...(outcome.startedAt ? { startedAt: outcome.startedAt } : {}),
...(outcome.agent ? { agent: outcome.agent } : {}),
});
if (outcome.ok) {
result = outcome.value ?? "";
kept.status = "completed";
if (step.name !== TASK_V5_SINGLE_STEP)
record.state[step.name] = result;
writeRecord(record);
}
else {
failure = { name, reason: reason };
}
}
const finishedAt = context.now() < startedAt ? startedAt : context.now();
const logPath = resolveTaskLogPath(context.options.logDir, record.taskId, startedAt.toISOString());
persistRunLog({
taskId: record.taskId,
startedAtIso: startedAt.toISOString(),
finishedAtIso: finishedAt.toISOString(),
logPath,
fileText: `${lines.join("\n")}\n`,
dbLines,
});
const outcome = {
id: record.taskId,
status: failure ? "failed" : "completed",
startedAt: startedAt.toISOString(),
finishedAt: finishedAt.toISOString(),
durationMs: finishedAt.getTime() - startedAt.getTime(),
log: logPath,
target: { kind: "steps" },
bundle: record.bundle.name,
...(failure ? { detail: { reason: "step_failed", error: `${failure.name}: ${failure.reason}` } } : { result }),
steps,
run: { id: record.runId, ...(record.parent ? { parent: record.parent } : {}) },
};
appendHistory(outcome, attempt.historyReserved, context.scheduled);
if (!failure)
discard(record);
return outcome;
}
/** The limit of a step: its own `timeout:`, or its task's, or 30 minutes. The run's limit holds as well. */
function limitOf(until, document, step) {
const timeout = option(document, step, "timeout") ?? DEFAULT_STEP_TIMEOUT;
return Math.min(until, Date.now() + parseTimeoutValue(String(timeout)));
}
/** A step, run again as `max-retries:` says whatever made it fail; each try has the step's whole limit. */
async function runStep(context, record, document, step, until) {
const retries = option(document, step, "max-retries") ?? record.flags.maxRetries ?? 0;
const lines = [];
const dbLines = [];
const last = await withRetries(retries, async (attempts) => {
try {
const remaining = limitOf(until, document, step) - Date.now();
if (remaining <= 0)
return { ok: false, reason: "timeout", attempts, lines, dbLines };
const outcome = await doStep(context, record, document, step, remaining, until, { lines, dbLines });
return { ...outcome, attempts, lines, dbLines };
}
catch (error) {
return {
ok: false,
reason: scrub(context, error instanceof Error ? error.message : String(error)),
attempts,
lines,
dbLines,
};
}
}, (outcome) => !outcome.ok && !context.abort.signal.aborted);
return last;
}
async function doStep(context, record, document, step, timeoutMs, until, sink) {
if (step.kind === "tasks")
return runTaskStep(context, record, document, step, until, sink);
const { env } = environmentOf(context, record.flags, document, step);
// The task's ref, as taskProcessEnv sets it for the other runners: the cached env is this task's, so it never changes.
env.AKM_TASK_REF = qualifiedRef(record.bundle, record.ref);
const cwd = step.options.cwd === undefined
? record.dir
: ensureWorkingFolder(path.resolve(record.bundle.dir, step.options.cwd));
const run = { env, cwd, timeoutMs };
if (step.kind === "exec" || step.kind === "scripts")
return runProcessStep(context, record, step, run, sink);
return runAgentStep(context, record, document, step, run, sink);
}
/** `${name}` becomes that entry of the state, once: text as it is, anything else as JSON. */
function fill(text, state) {
return text.replace(REF_TOKEN_RE, (token, body) => (body in state ? asText(state[body]) : token));
}
/** An `args:` item when the step runs: a `${name}` item is that state entry, anything else is as written. */
function argument(item, state) {
const body = typeof item === "string" ? WHOLE_TOKEN.exec(item)?.[1] : undefined;
return body === undefined ? item : state[body];
}
function scrub(context, value) {
return context.secrets.size === 0 ? value : redactSensitiveValue(value, collectSensitiveValues(context.secrets));
}
/** A script or `exec:` command: a real process that reads the state from a file written for this step. */
async function runProcessStep(context, record, step, run, sink) {
const { argv, script } = step.kind === "scripts"
? scriptProgram(step.run, (await locateTaskV5Asset(record.bundle, step.run, "scripts", `${record.ref} step ${step.name}`))
.asset, (step.args ?? []).map((item) => asText(argument(item, record.state))))
: {
argv: shellCommand({ command: step.exec, shell: process.platform === "win32" ? "cmd" : "sh" }),
script: undefined,
};
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "akm-task-state-"));
const statePath = path.join(stateDir, "state.json");
// asset-io: scratch run folder akm made
fs.writeFileSync(statePath, JSON.stringify(record.state, null, 2));
try {
const result = await runProgram({
argv,
...(script ? { script } : {}),
env: { ...run.env, AKM_TASK_STATE: statePath },
cwd: run.cwd,
timeoutMs: run.timeoutMs,
capture: true,
signal: context.abort.signal,
});
const stdout = scrub(context, result.stdout);
const stderr = scrub(context, result.stderr);
sink.lines.push(`exit_code=${result.exitCode}`);
if (stdout) {
sink.lines.push("--- stdout ---", stdout);
appendStreamLines(sink.dbLines, stdout, "stdout", "info");
}
if (stderr) {
sink.lines.push("--- stderr ---", stderr);
appendStreamLines(sink.dbLines, stderr, "stderr", "error");
}
if (result.aborted || result.timedOut || result.exitCode !== 0) {
const { reason, error } = processFailure({ ...result, stderr });
return {
ok: false,
reason: reason === "non_zero_exit" || reason === "spawn_error" ? `${reason}: ${error}` : reason,
};
}
const incomplete = streamCaptureFailure(result.stdoutRead, result.stderrRead);
if (incomplete)
return { ok: false, reason: incomplete };
return { ok: true, value: stdout };
}
finally {
// asset-io: scratch run folder akm made
fs.rmSync(stateDir, { recursive: true, force: true });
}
}
/** A prompt, an agent or a prompt asset: the agent's reply is the result, held to `expect:` when the step has it. */
async function runAgentStep(context, record, document, step, run, sink) {
const selection = selectionFromArgs({
harness: option(document, step, "harness"),
connection: option(document, step, "connection"),
model: option(document, step, "model"),
});
const runAgent = context.options.runAgentImpl;
const dispatch = async (correction) => {
const extra = correction ? `\n\n${correction.text}` : "";
const reply = step.kind === "commands"
? await dispatchPromptAsset(context, step, `${fill(step.arguments ?? "", record.state)}${extra}`, selection, run)
: await akmAgentDispatch({
prompt: `${fill(step.prompt, record.state)}${extra}`,
...(step.kind === "agents" ? { agentRef: step.run } : {}),
agentConfig: loadConfig(),
baseEnv: run.env,
cwd: run.cwd,
timeoutMs: run.timeoutMs,
signal: context.abort.signal,
...(Object.keys(selection).length === 0 ? {} : { selection }),
}, runAgent
? {
executeCommand: (prepare, dispatchOptions) => executeCommandInvocation(prepare, { ...dispatchOptions, runAgent }),
}
: {});
const agent = {
engine: reply.engine,
...(reply.ok || reply.reason === undefined ? {} : { reason: reply.reason }),
};
sink.lines.push(`engine=${reply.engine} ok=${reply.ok} exit_code=${reply.exitCode ?? "null"}`);
const stdout = scrub(context, reply.stdout);
const stderr = scrub(context, reply.stderr);
if (stdout) {
sink.lines.push("--- agent stdout ---", stdout);
appendStreamLines(sink.dbLines, stdout, "stdout", "info");
}
if (stderr) {
sink.lines.push("--- agent stderr ---", stderr);
appendStreamLines(sink.dbLines, stderr, "stderr", "error");
}
if (!reply.ok) {
return {
ok: false,
failure: [reply.reason, reply.error].filter(Boolean).join(": ") || "dispatch failed",
agent,
};
}
return { ok: true, raw: reply.stdout, agent };
};
if (!step.expect) {
const reply = await dispatch();
return {
...(reply.ok ? { ok: true, value: scrub(context, reply.raw) } : { ok: false, reason: reply.failure }),
agent: reply.agent,
};
}
const loop = await expectLoop(step.expect, dispatch);
const { agent } = loop;
if (loop.ok)
return { ok: true, value: scrub(context, loop.value), agent };
if ("errors" in loop)
return { ok: false, reason: `reply_check_failed: ${loop.errors.join("; ")}`, agent };
return { ok: false, reason: loop.failure, agent };
}
async function dispatchPromptAsset(context, step, text, selection, run) {
const prepared = await prepareCommandInvocation({
action: { ref: step.run, ...(text === "" ? {} : { arguments: text }) },
config: loadConfig(),
current: { ...selection, workspace: run.cwd, timeout: run.timeoutMs },
});
return dispatchPreparedCommandInvocation(prepared, {
...(context.options.runAgentImpl ? { runAgent: context.options.runAgentImpl } : {}),
baseEnv: run.env,
signal: context.abort.signal,
eventSource: context.provenance.eventSource,
});
}
/** A task that a step runs is a run of its own: its own state, options, working folder and history. */
async function runTaskStep(context, record, document, step, until, sink) {
const ref = step.run;
const found = await locateTaskV5Asset(record.bundle, ref, "tasks", `${record.ref} step ${step.name}`);
const child = parseDocument(found);
const taskId = taskIdOf(ref);
const limit = limitOf(until, document, step);
const lock = child.lock === true
? tryAcquireRunLock(taskRunLockPath(qualifiedRef(found.bundle, ref)), { label: "task" })
: undefined;
if (lock?.state === "held")
throw new Error(`task ${ref} is still running, and it runs one at a time`);
try {
const kept = record.children[step.name];
let run = kept === undefined ? undefined : readRecord(kept.task, kept.run);
if (run === undefined) {
run = newRecord(context, ref, taskId, found.bundle, child, record.flags, stepInputs(child, step, record.state), [], record, step.name);
record.children[step.name] = { task: taskId, run: run.runId };
writeRecord(record);
}
const result = await runAttempt(context, run, child, limit);
sink.lines.push(`task=${ref} status=${result.status} started_at=${result.startedAt}`);
if (result.status === "completed")
return { ok: true, value: result.result, startedAt: result.startedAt };
return {
ok: false,
reason: `task ${ref} ${result.status}${result.detail?.error ? `: ${result.detail.error}` : ""}`,
startedAt: result.startedAt,
};
}
finally {
if (lock)
releaseLock(lock.ownership);
}
}
// ── The environment and secrets ─────────────────────────────────────────────
/**
* A step's environment. A script or `exec:` step starts with what `--clean` keeps, akm's own location variables, and
* what `inherit:` and `--inherit` name. An agent step starts with akm's environment as it is, which `inherit:` has
* nothing to add to. Then the task's `env:` and `secret:`, then the step's, then what the run was started with, each
* over the one before.
*/
function environmentOf(context, flags, document, step) {
const key = `${document.source.path}#${step.name}#${JSON.stringify(flags)}`;
const cached = context.environments.get(key);
if (cached)
return cached;
const inherit = [...(flags.inherit ?? []), ...(document.options.inherit ?? []), ...(step.options.inherit ?? [])];
// An agent step runs the user's harness as the user would: akm's environment as it is, with the directories this akm resolved.
const startsClean = step.kind === "exec" || step.kind === "scripts";
const env = {};
const base = startsClean ? buildChildEnv(context.host, { clean: true, inherit }) : childProcessEnv(context.host);
for (const [name, value] of Object.entries(base)) {
if (value !== undefined)
env[name] = value;
}
env.AKM_EVENT_SOURCE = taskEventSource(context.host, context.provenance);
const secretValues = [];
const apply = (refs) => {
const injected = resolveInjectionRefs(refs);
Object.assign(env, injected.values);
secretValues.push(...injected.secretValues);
};
for (const layer of [document.options, step.options, flags]) {
for (const entry of layer.env ?? []) {
if (typeof entry === "string")
apply({ env: [entry] });
else
for (const [name, value] of Object.entries(entry))
env[name] = String(value);
}
if (layer.secret?.length)
apply({ secret: [...layer.secret] });
}
secretValues.push(...collectInferredSecretValues(env));
const resolved = { env, secretValues };
context.environments.set(key, resolved);
return resolved;
}
/** Every secret value the run can set, in its task and every task it runs, is known from the start. */
async function collectSecrets(context, ref, bundle, flags, seen) {
const found = await locateTaskV5Asset(bundle, ref, "tasks", ref);
if (seen.has(found.file))
return;
seen.add(found.file);
const document = parseDocument(found);
for (const step of document.steps) {
if (step.kind === "tasks")
await collectSecrets(context, step.run, found.bundle, flags, seen);
else
for (const value of environmentOf(context, flags, document, step).secretValues)
context.secrets.add(value);
}
}