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
156 lines (155 loc) • 8.47 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/.
/**
* Dispatch mode for `akm doctor scheduler sync`: which mode a host is in, the plan for each mode, and the order a
* plan is applied in.
*
* A host in dispatch mode holds one row, `akm task dispatch` every minute ({@link DISPATCH_BINDING}), instead of a
* row per schedule entry. The mode is what the installed rows show: this installation's dispatch row is installed or
* it is not. A per-task row names this installation's working stash (`AKM_BUNDLE_DIR`), which is how its rows are told
* from another installation's. The dispatch row names no stash: `akm task dispatch` reads the config, and an
* installation is its config, so the row is told apart by the config directory or file it carries, none for the
* default one. A host never holds both kinds of row: switching removes one kind before it writes the other, and a
* write after a failed removal is held.
*/
import { UsageError } from "../core/errors.js";
import { DISPATCH_BINDING, isDispatchRow, } from "./scheduler-binding.js";
import { scheduledTaskSubject } from "./scheduler-invocation.js";
import { installedRowNativeId, installedRowOwner, } from "./scheduler-sync.js";
export const ROWS_DEPRECATED_WARNING = "Per-task scheduler rows are deprecated and removed in 0.11. `akm doctor scheduler sync --dispatch` switches this host to one row that runs `akm task dispatch` every minute.";
/** The config a row's installation reads: its `AKM_CONFIG_FILE` or `AKM_CONFIG_DIR`, undefined for the default one. */
function configOf(environment) {
return environment?.AKM_CONFIG_FILE ?? environment?.AKM_CONFIG_DIR;
}
/**
* The environment the dispatch row sets: the sync's own without `AKM_BUNDLE_DIR`, which is Deprecated, unless the
* syncing process was given it, as the stash it still selects that way.
*/
function dispatchRowEnvironment(environment, env = process.env) {
if (environment === undefined || env.AKM_BUNDLE_DIR?.trim())
return environment;
const { AKM_BUNDLE_DIR: _derived, ...rest } = environment;
return Object.keys(rest).length > 0 ? rest : undefined;
}
/** The mode a sync works in: `requested` (`--dispatch` / `--no-dispatch`), else the one the installed rows show. */
export function schedulerModeOf(rows, ownEnvironment, requested) {
const dispatchRow = rows.find(isDispatchRow);
const ownDispatchRow = dispatchRow !== undefined && configOf(dispatchRow.environment) === configOf(ownEnvironment)
? dispatchRow
: undefined;
const dispatch = requested ?? ownDispatchRow !== undefined;
if (dispatch && dispatchRow !== undefined && ownDispatchRow === undefined) {
const config = configOf(dispatchRow.environment);
const owner = config === undefined ? "the default config" : JSON.stringify(config);
throw new UsageError(`Scheduler id "dispatch" is already scheduled by the installation that reads ${owner}; one installation per user can use dispatch mode. Run this installation without \`--dispatch\`.`, "INVALID_FLAG_VALUE");
}
return {
dispatch,
...(ownDispatchRow !== undefined ? { ownDispatchRow } : {}),
taskRows: rows.filter((row) => !isDispatchRow(row)),
};
}
/** Row mode: the per-task plan, after removing this installation's dispatch row when switching back. */
export function planRowMode(rowPlan, mode) {
const warnings = rowPlan.operations.some((operation) => operation.kind !== "remove") ? [ROWS_DEPRECATED_WARNING] : [];
const own = mode.ownDispatchRow;
if (own === undefined)
return { plan: rowPlan, failures: [], warnings };
const removal = Object.freeze({ kind: "remove", id: own.id, nativeId: installedRowNativeId(own) });
const plan = { ...rowPlan, removed: [removal.id, ...rowPlan.removed], operations: [removal, ...rowPlan.operations] };
return { plan, failures: [], warnings };
}
/**
* Dispatch mode: remove every row this installation wrote, then install or update the dispatch row, which keeps its
* launcher unless `rebind`, as a task row does. An `@reboot` entry is a failure: dispatch has no minute for it. A
* row of another installation that runs an enabled task is left, with a warning: dispatch starts that task too.
*/
export function planDispatchMode(input) {
const { mode, ownBundleDir } = input;
const failures = input.desired
.filter((binding) => binding.cron.trim().toLowerCase() === "@reboot")
.map((binding) => ({
path: binding.source,
ref: binding.logicalSource.ref,
reason: "`@reboot` runs once at startup, which `akm task dispatch` has no minute for: in dispatch mode this entry never starts.",
}));
const enabled = new Set(input.enabledRefs);
const warnings = mode.taskRows
.filter((row) => row.ownerBundlePath !== ownBundleDir && enabled.has(scheduledTaskSubject(row.invocation)?.subject ?? ""))
.map((row) => `Row ${JSON.stringify(installedRowNativeId(row))} runs ${scheduledTaskSubject(row.invocation)?.subject} from ${installedRowOwner(row)} and was left; \`akm task dispatch\` starts it too. Remove the row if it is this installation's.`);
const own = mode.taskRows.filter((row) => row.ownerBundlePath === ownBundleDir);
const removals = own.map((row) => Object.freeze({ kind: "remove", id: row.id, nativeId: installedRowNativeId(row) }));
const current = mode.ownDispatchRow;
const environment = dispatchRowEnvironment(input.installOptions.environment);
const binding = current !== undefined && !input.rebind ? current.binding : input.installOptions.binding;
const options = {
...(binding !== undefined ? { binding: [...binding] } : {}),
...(environment !== undefined ? { environment } : {}),
};
const expected = input.sched.expectedSignature?.(DISPATCH_BINDING, options);
const kind = current === undefined ? "install" : expected === undefined || current.signature === expected ? undefined : "update";
const write = kind === undefined
? []
: [
Object.freeze({
kind,
binding: DISPATCH_BINDING,
options,
...(current?.signature !== undefined && kind === "update" ? { installedSignature: current.signature } : {}),
...(expected !== undefined ? { expectedSignature: expected } : {}),
}),
];
const id = DISPATCH_BINDING.id;
const plan = {
desired: [DISPATCH_BINDING],
installed: kind === "install" ? [id] : [],
updated: kind === "update" ? [id] : [],
unchanged: kind === undefined ? [id] : [],
removed: own.map((row) => row.id),
operations: [...removals, ...write],
failures: [],
};
return { plan, failures, warnings };
}
/**
* Apply a plan's operations in order. With `guarded` (a plan that touches the dispatch row or is in dispatch mode),
* every write after a failed removal is held: with both kinds of row installed, tasks would run twice.
*/
export async function applySchedulerOperations(sched, operations, guarded) {
const failed = new Set();
const failures = [];
let removalFailed = false;
for (const operation of operations) {
if (operation.kind === "remove") {
try {
await sched.uninstall(operation.nativeId);
}
catch (cause) {
removalFailed = true;
failed.add(operation.id);
failures.push({ path: operation.nativeId, reason: errorMessage(cause) });
}
continue;
}
const { binding } = operation;
const failure = (reason) => {
failed.add(binding.id);
failures.push({ path: binding.source, ref: binding.logicalSource.ref, reason });
};
if (guarded && removalFailed) {
failure("Not written: a removal before it failed, and with both rows installed tasks would run twice.");
continue;
}
try {
await sched.install(binding, operation.options);
}
catch (cause) {
failure(errorMessage(cause));
}
}
return { failed, failures };
}
function errorMessage(cause) {
return cause instanceof Error ? cause.message : String(cause);
}