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
121 lines (120 loc) • 5.55 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/.
/**
* Freeze a compiled workflow plan into the plan a run executes. Every step's
* authored spec resolves through the shared command/task authorities into a
* frozen `root` (connection or harness, model, timeout, concurrency, dispatch target and
* environment descriptors); gates get their judge; the compile-only fields are
* dropped; the source file's sha256 is recorded. Nothing is published here.
*/
import { createHash } from "node:crypto";
import { SHIPPED_ALIAS } from "../../core/config/model-aliases.js";
import { UsageError } from "../../core/errors.js";
import { resolveExecution, shippedAlias } from "../../integrations/agent/execution.js";
import { checkWorkflowPlan } from "../compile.js";
import { defaultMapConcurrency, workflowMaxConcurrency } from "../concurrency-policy.js";
import { canonicalJson } from "../ir/plan-hash.js";
import { WORKFLOW_PLAN_VERSION, } from "../plan.js";
import { baseUnitOf } from "./step-values.js";
import { childWorkflowDispatch } from "./targets/child-workflow.js";
import { commandDispatch, commandResult } from "./targets/command.js";
import { directShell } from "./targets/shell.js";
/** Resolve and freeze one workflow (and, recursively, every child it composes). */
export async function freezeWorkflow(asset, config, refPath = [asset.ref]) {
const compiled = asset.plan;
const checked = checkWorkflowPlan(compiled);
if (!checked.ok) {
throw new UsageError(checked.errors.map((error) => `${asset.path}:${error.line}: ${error.message}`).join("\n"), "WORKFLOW_SOURCE_INVALID");
}
const context = {
asset,
config,
plan: compiled,
refPath,
freezeChild: (child, childRefPath) => freezeWorkflow(child, config, childRefPath),
};
const steps = [];
for (const step of compiled.steps) {
const { spec, ...frozenStep } = step;
const source = { ...(spec ?? { source: { path: asset.path, start: 1, end: 1 } }), id: step.stepId };
const resolved = await resolveStep(source, context);
const root = frozenRoot(step.stepId, source, resolved, compiled, config);
let frozenJudge = null;
if (step.gate.criteria.length > 0) {
const judge = resolveJudge(source, step.gate.criteria[0] ?? "", context);
frozenJudge = judge.target;
}
steps.push({ ...frozenStep, root, gate: { ...step.gate, frozenJudge } });
}
const plan = {
irVersion: WORKFLOW_PLAN_VERSION,
title: asset.title,
...(compiled.params ? { params: compiled.params } : {}),
...(compiled.paramSchemas ? { paramSchemas: compiled.paramSchemas } : {}),
...(compiled.budget ? { budget: compiled.budget } : {}),
execution: { maxConcurrency: workflowMaxConcurrency(config.workflow?.maxConcurrency) },
sourceHash: asset.sourceHash,
steps,
};
return { plan, warnings: checked.warnings };
}
async function resolveStep(source, context) {
const baseUnit = baseUnitOf(source);
if (source.exec)
return directShell(source, baseUnit, context);
if (source.workflow) {
return childWorkflowDispatch({ source, baseUnit, childRefInput: source.workflow, context });
}
// A prose step: its body is the `akm/command` literal content (`parser.ts` `stepSpec`).
return commandDispatch(source, baseUnit, source.with, context);
}
/** The gate judge's frozen command target: a model call, so it runs where model work runs. */
function resolveJudge(source, rubric, context) {
const prepared = resolveExecution({
content: rubric.trim() || "Judge workflow completion.",
config: context.config,
layers: [shippedAlias(SHIPPED_ALIAS.judge)],
modelWork: true,
});
return commandResult(source, { onError: "fail", source: source.source }, prepared);
}
function frozenRoot(stepId, source, resolved, plan, config) {
const unit = resolved.unit;
const target = resolved.target.kind === "shell"
? {
...resolved.target,
contentHash: createHash("sha256")
.update("akm.workflow.shell.v1\0")
.update(canonicalJson({
exec: resolved.target.exec,
environment: resolved.environment,
}))
.digest("hex"),
}
: resolved.target;
const node = {
kind: "unit",
id: source.map ? `${stepId}.unit` : stepId,
instructions: resolved.instructions,
...(source.inputs && source.inputs.length > 0 ? { inputs: [...source.inputs] } : {}),
...(unit.output !== undefined ? { schema: unit.output } : {}),
...(unit.retry ? { retry: { max: unit.retry.max, on: [...unit.retry.on] } } : {}),
onError: unit.onError ?? plan.defaults?.onError ?? "fail",
...(unit.env ? { env: [...unit.env] } : {}),
source: { ...source.source },
frozenTarget: target,
environment: [...resolved.environment],
};
if (!source.map)
return node;
return {
kind: "map",
id: `${stepId}.map`,
over: source.map.over,
template: node,
concurrency: source.map.concurrency ?? defaultMapConcurrency(config.workflow?.defaultMapConcurrency),
reducer: source.map.reducer ?? "collect",
source: { ...source.source },
};
}