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
162 lines (161 loc) • 6.72 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/.
/**
* Secret-free input to every native scheduler backend, and the backend
* contract itself.
*
* A binding carries only stable source identity, trigger identity, and the
* public CLI tail; its install options add the launcher and the AKM
* directory environment the row sets inline. Source content, action inputs,
* task environment values, and credentials never cross this boundary or
* reach an OS scheduler.
*/
import { createHash } from "node:crypto";
import { stashDirFor } from "../core/asset/asset-placement.js";
import { bundleRefToString, parseBundleRef } from "../core/asset/asset-ref.js";
import { UsageError } from "../core/errors.js";
import { canonicalInputJson } from "../execution/input-contract.js";
import { scheduledTaskSubject } from "./scheduler-invocation.js";
import { normaliseTaskConceptId } from "./task-id.js";
/**
* The one row of a host in dispatch mode (`akm doctor scheduler sync --dispatch`): `akm task dispatch` every minute,
* which starts each enabled task that is due. A task whose id is `dispatch` has the same native id: switching mode
* removes the one row before it writes the other.
*/
export const DISPATCH_BINDING = freezeBinding({
id: "dispatch",
nativeId: "dispatch",
logicalSource: { kind: "task", ref: "dispatch" },
cron: "*/1 * * * *",
source: "akm task dispatch",
ordinal: 0,
enabled: true,
invocation: ["task", "dispatch"],
});
/** Whether an installed row is the dispatch row. */
export function isDispatchRow(row) {
return row.invocation?.length === 2 && row.invocation[0] === "task" && row.invocation[1] === "dispatch";
}
export function compileTaskSchedulerBindings(input) {
const id = normaliseTaskConceptId(input.id);
const ref = assertQualifiedRef(input.qualifiedRef, "task");
return Object.freeze(input.schedules.map((schedule) => {
const bindingId = schedule.ordinal === 0 ? id : digestBindingId("task", ref, schedule.ordinal);
return freezeBinding({
id: bindingId,
nativeId: schedulerNativeBindingId(bindingId),
logicalSource: { kind: "task", ref },
cron: schedule.cron,
source: schedule.source,
ordinal: schedule.ordinal,
enabled: true,
invocation: [
"run",
ref,
"--scheduled",
...schedulerInputFlagTail(schedule.inputs),
...schedulerStartFlagTail(schedule.start),
],
});
}));
}
/**
* The canonically-sorted input flags of one schedule entry's `inputs`, each value as the text the tail carries. The
* check of a schedule entry reads these same flags, so it checks what the scheduled start is given.
*/
export function schedulerInputFlags(inputs) {
if (!inputs)
return [];
return Object.keys(inputs)
.sort()
.map((name) => ({ name, value: schedulerInputFlagValueText(inputs[name]) }));
}
/**
* The `--<name> <value>` flag tail for one schedule entry's `inputs`. A value whose text starts with `-` uses the
* inline `--<name>=<value>` form, the only spelling `parseTaskInputFlags` cannot mistake for a flag.
*/
function schedulerInputFlagTail(inputs) {
const tail = [];
for (const { name, value } of schedulerInputFlags(inputs)) {
const text = value;
if (text.startsWith("-"))
tail.push(`--${name}=${text}`);
else
tail.push(`--${name}`, text);
}
return tail;
}
/** `--env`, `--secret` and `--timeout`, in the order the entry wrote them: a later env ref wins over an earlier one. */
function schedulerStartFlagTail(start) {
if (!start)
return [];
return [
...(start.env ?? []).flatMap((ref) => ["--env", ref]),
...(start.secret ?? []).flatMap((spec) => ["--secret", spec]),
...(start.timeout !== undefined ? ["--timeout", String(start.timeout)] : []),
];
}
function schedulerInputFlagValueText(value) {
if (typeof value === "string")
return value;
if (typeof value === "number" || typeof value === "boolean")
return String(value);
return canonicalInputJson(value);
}
/**
* Map a logical binding id to the flat portable token persisted by native
* schedulers. Flat ids are byte-for-byte stable; only nested standalone
* component ids need an encoded native spelling.
*/
export function schedulerNativeBindingId(id) {
if (!id.includes("/"))
return id;
const digest = createHash("sha256")
.update(JSON.stringify(["nested-task", id]))
.digest("hex")
.slice(0, 32);
return `task-${digest}`;
}
export function schedulerBindingNativeId(binding) {
return binding.nativeId ?? schedulerNativeBindingId(binding.id);
}
/**
* Recover the logical id of an installed row from its native spelling and
* public invocation: an ordinal-zero task row is its task id (possibly a
* nested one behind a digest spelling); every other row is its native id.
*/
export function schedulerLogicalBindingId(nativeId, invocation) {
const subject = scheduledTaskSubject(invocation)?.subject;
if (subject === undefined)
return nativeId;
// A row names its task by ref (`<bundle>//<concept id>`); a row written before 0.11 by its id.
const conceptId = subject.includes("//") ? parseBundleRef(subject).conceptId : subject;
const folder = stashDirFor("task");
const candidates = folder !== undefined && conceptId.startsWith(`${folder}/`)
? [conceptId, conceptId.slice(folder.length + 1)]
: [conceptId];
return candidates.find((candidate) => schedulerNativeBindingId(candidate) === nativeId) ?? nativeId;
}
function digestBindingId(kind, ref, ordinal) {
const prefix = kind === "workflow" ? "wf" : "task";
const digest = createHash("sha256")
.update(JSON.stringify([kind, ref, ordinal]))
.digest("hex")
.slice(0, 32);
return `${prefix}-${digest}`;
}
function assertQualifiedRef(value, kind) {
const parsed = parseBundleRef(value);
if (!parsed.bundle || parsed.fragment !== undefined || bundleRefToString(parsed) !== value) {
throw new UsageError(`${kind} scheduler bindings require one canonical fully-qualified ref.`, "INVALID_FLAG_VALUE");
}
return value;
}
function freezeBinding(binding) {
return Object.freeze({
...binding,
logicalSource: Object.freeze({ ...binding.logicalSource }),
invocation: Object.freeze([...binding.invocation]),
});
}