UNPKG

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

365 lines (364 loc) • 15.6 kB
// 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/. /** * How a native scheduler row invokes akm. * * A row is `<launcher…> run <bundle//concept-id> --scheduled * [--<input> <value>…]`, or `<launcher…> workflow run <qualified-ref>`, and it * carries its own context: the environment the scheduled process needs, * set inline by the row itself (a cron `VAR=value` prefix, a launchd * `EnvironmentVariables` entry, a PowerShell `$env:` assignment). * * - `AKM_BUNDLE_DIR`: the working stash of the process that ran * `akm task sync`, on every row. The scheduled run uses the same working * stash, `--bundle <name>` finds a stash no config names, and sync * attributes the row to the installation that wrote it (#846). * - `AKM_CONFIG_DIR`, `AKM_DATA_DIR`, `AKM_CACHE_DIR` and `AKM_STATE_DIR` * only when the directory the process that ran `akm task sync` resolved * differs from the default one, whatever set it (an `AKM_*_DIR` variable * or an `XDG_*_HOME`). A default resolves at fire time exactly as it does * for an interactive command. `AKM_CONFIG_FILE`, when selected, is carried * as an absolute path. * * That is exactly what the `--scheduler-context` descriptor held. * * `PATH` is the scheduler's own: the crontab's `# akm:env` block, the plist's * `EnvironmentVariables`. * * A row written before 0.10.261135 runs `task run <bundle//concept-id> --scheduled …` (Deprecated), and one written * before that names its task by id, `task run <id> --bundle <bundle> --scheduled`; both are read until 0.11, and the * next sync rewrites them. * * Rows written by 0.9.0 through 0.9.17-alpha.6 name a * `--scheduler-context <descriptor>` file instead. The CLI still accepts that * argument and applies the file's environment, so such a row keeps firing * until the next `akm task sync` rewrites it. */ import fs from "node:fs"; import path from "node:path"; import { createParsedInvocation } from "../cli/invocation.js"; import { bundleRefToString, parseBundleRef } from "../core/asset/asset-ref.js"; import { resolveStashDir } from "../core/common.js"; import { ConfigError } from "../core/errors.js"; import { getCacheDir, getConfigDir, getDataDir, getStateDir } from "../core/paths.js"; import { INPUT_NAME_PATTERN } from "../execution/input-contract.js"; import { normaliseTaskConceptId } from "./task-id.js"; export const SCHEDULED_TASK_CONTEXT_KEYS = [ "AKM_BUNDLE_DIR", "AKM_CONFIG_DIR", "AKM_CONFIG_FILE", "AKM_DATA_DIR", "AKM_CACHE_DIR", "AKM_STATE_DIR", ]; /** * The directories a row carries when the one the syncing process resolved is not the default one. The default is what * the scheduler's own environment resolves, which names none of the variables below. */ const RESOLVED_DIRECTORIES = [ ["AKM_CONFIG_DIR", getConfigDir], ["AKM_DATA_DIR", getDataDir], ["AKM_CACHE_DIR", getCacheDir], ["AKM_STATE_DIR", getStateDir], ]; const DIRECTORY_VARIABLES = [ "AKM_CONFIG_DIR", "AKM_DATA_DIR", "AKM_CACHE_DIR", "AKM_STATE_DIR", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME", ]; /** A directory as `resolve` gives it, or undefined when it cannot be resolved here. */ function resolveOrUndefined(resolve, env) { try { return resolve(env); } catch { return undefined; } } /** The AKM directory context of the current process, so nested AKM commands stay in the same installation. */ export function scheduledTaskContextEnv(env = process.env) { const out = {}; for (const key of SCHEDULED_TASK_CONTEXT_KEYS) { const value = env[key]; if (value) out[key] = value; } return out; } /** * The environment every row a sync writes sets inline: `AKM_BUNDLE_DIR`, * the syncing process's working stash, plus each of its config, data, cache and * state directories that differs from the default. With no working stash to * resolve (no default bundle, no `AKM_BUNDLE_DIR`), rows name their bundle by * `--bundle` alone. */ export function scheduledRowEnvironment(env = process.env) { const out = {}; try { out.AKM_BUNDLE_DIR = path.resolve(resolveStashDir(env)); } catch { // No working stash: there is no primary bundle to attribute rows to either. } const defaults = { ...env }; for (const name of DIRECTORY_VARIABLES) delete defaults[name]; for (const [key, resolve] of RESOLVED_DIRECTORIES) { const resolved = resolveOrUndefined(resolve, env); if (resolved !== undefined && resolved !== resolveOrUndefined(resolve, defaults)) out[key] = path.resolve(resolved); } const configFile = env.AKM_CONFIG_FILE?.trim(); if (configFile) out.AKM_CONFIG_FILE = path.resolve(configFile); return out; } /** A row environment's entries, in {@link SCHEDULED_TASK_CONTEXT_KEYS} order. */ export function scheduledRowEnvironmentEntries(environment) { const entries = []; for (const key of SCHEDULED_TASK_CONTEXT_KEYS) { const value = environment?.[key]; if (value) entries.push([key, value]); } return entries; } /** Keep the {@link SCHEDULED_TASK_CONTEXT_KEYS} a parsed row set; `undefined` when there are none. */ export function scheduledRowEnvironmentFrom(variables) { const out = {}; for (const key of SCHEDULED_TASK_CONTEXT_KEYS) { const value = variables[key]; if (value) out[key] = value; } return Object.keys(out).length > 0 ? out : undefined; } /** * The task a row's tail runs and where the tail's flags start: `run <ref> --scheduled …`, or the `task run <ref|id> …` * an earlier row holds. Undefined for any other tail. */ export function scheduledTaskSubject(invocation) { if (invocation?.[0] === "run" && invocation[1]) return { subject: invocation[1], flagsFrom: 2 }; if (invocation?.[0] === "task" && invocation[1] === "run" && invocation[2]) return { subject: invocation[2], flagsFrom: 3 }; return undefined; } const SCHEDULER_CONTEXT_ARG = "--scheduler-context"; /** The start flags of a version 5 schedule entry that may repeat in a tail: one `--env` ref or `--secret` spec each. */ const REPEATABLE_START_FLAGS = new Set(["env", "secret"]); /** The installed argv: the launcher, then one already-validated public scheduler tail. */ export function buildScheduledInvocation(akmArgv, invocation) { const parsed = parsePublicSchedulerInvocation(invocation); if (!parsed) throw invalidSchedulerInvocation(); return [...akmArgv, ...parsed.invocation]; } /** * Parse an installed row's argv (after any inline environment): the current * shape, the `--scheduler-context <descriptor>` shape 0.9.0 – 0.9.17-alpha.6 * wrote, or the bare shape before that. A row that carries * `--scheduler-context` but does not parse around it is never reread as * another shape. */ export function parseScheduledInvocationArgv(argv) { const contextIndex = argv.indexOf(SCHEDULER_CONTEXT_ARG); if (contextIndex !== -1) { if (contextIndex < 1 || argv.indexOf(SCHEDULER_CONTEXT_ARG, contextIndex + 1) !== -1) return undefined; const contextPath = argv[contextIndex + 1]; if (!contextPath) return undefined; const publicInvocation = parsePublicSchedulerInvocation(argv.slice(contextIndex + 2)); if (!publicInvocation) return undefined; return { binding: argv.slice(0, contextIndex), contextPath, ...publicInvocation }; } for (let index = 1; index < argv.length - 1; index += 1) { const verb = argv[index + 1]; if ((argv[index] === "task" && (verb === "run" || verb === "dispatch")) || (argv[index] === "workflow" && verb === "run")) { const publicInvocation = parsePublicSchedulerInvocation(argv.slice(index)); return publicInvocation ? { binding: argv.slice(0, index), ...publicInvocation } : undefined; } // `run <ref> --scheduled …`: a launcher may hold a `run` of its own (`bun run …`), so only a whole tail counts. if (argv[index] === "run") { const publicInvocation = parsePublicSchedulerInvocation(argv.slice(index)); if (publicInvocation) return { binding: argv.slice(0, index), ...publicInvocation }; } } return undefined; } /** * The environment a `--scheduler-context` descriptor names: its `AKM_*_DIR` * keys and, in one written before 0.9.17, `PATH`. It is read as plain JSON — * the file is this user's own, next to the data it names. */ export function readLegacySchedulerContext(file) { let parsed; try { // asset-io: state scheduler context file parsed = JSON.parse(fs.readFileSync(file, "utf8")); } catch (error) { throw new ConfigError(`Cannot read scheduler context "${file}": ${error instanceof Error ? error.message : String(error)}. ` + "Run `akm doctor scheduler sync` to rewrite this scheduled row.", "INVALID_CONFIG_FILE"); } const environment = parsed !== null && typeof parsed === "object" ? parsed.environment : undefined; const out = {}; if (environment === null || typeof environment !== "object") return out; for (const key of [...SCHEDULED_TASK_CONTEXT_KEYS, "PATH"]) { const value = environment[key]; if (typeof value === "string" && value.length > 0) out[key] = value; } return out; } /** * Apply and remove a row's `--scheduler-context <descriptor>` before citty * parses argv. Only a row written by 0.9.0 – 0.9.17-alpha.6 passes it. */ export function consumeSchedulerContextArg(argv, env = process.env, invocation = createParsedInvocation(argv)) { const index = argv.slice(0, 2 + invocation.ownArgs.length).indexOf(SCHEDULER_CONTEXT_ARG); if (index === -1) return argv; const file = argv[index + 1]; if (!file) { throw new ConfigError(`${SCHEDULER_CONTEXT_ARG} requires a descriptor path.`, "INVALID_CONFIG_FILE"); } Object.assign(env, readLegacySchedulerContext(file)); return [...argv.slice(0, index), ...argv.slice(index + 2)]; } /** * Parse just the public `run …` / `workflow run …` / `task dispatch` tail (or an * earlier row's `task run …`), the part of a row that names what it runs. */ function parsePublicSchedulerInvocation(invocation) { // The one row of a host in dispatch mode: it names no task and no bundle. if (invocation.length === 2 && invocation[0] === "task" && invocation[1] === "dispatch") return { invocation: [...invocation] }; const task = scheduledTaskSubject(invocation); if (task) { const { subject } = task; let index = task.flagsFrom; let target; if (subject.includes("//")) { // The current form: the task's own ref. try { const parsed = parseBundleRef(subject); if (!parsed.bundle || parsed.fragment !== undefined || bundleRefToString(parsed) !== subject) return undefined; if (normaliseTaskConceptId(parsed.conceptId) !== parsed.conceptId) return undefined; target = parsed.bundle; } catch { return undefined; } } else { // Before 0.11: the task's id, with the bundle it is in after it. Only a `task run` row names one. if (invocation[0] !== "task") return undefined; try { if (normaliseTaskConceptId(subject) !== subject) return undefined; } catch { return undefined; } if (invocation[index] === "--bundle") { target = invocation[index + 1]; if (!target) return undefined; index += 2; } } if (invocation[index] !== "--scheduled") return undefined; // Zero or more `--<name> <value>` schedule-supplied input flags may follow // `--scheduled` — the same trailing tail `compileTaskSchedulerBindings` // compiles from `schedule[i].inputs`. Absent/empty is the earlier, // byte-identical shape. if (!isValidSchedulerInputFlagTail(invocation.slice(index + 1))) return undefined; return { invocation: [...invocation], ...(target !== undefined ? { target } : {}) }; } if (invocation[0] !== "workflow" || invocation[1] !== "run" || invocation.length !== 3) { return undefined; } const ref = invocation[2]; if (!ref) return undefined; try { const parsed = parseBundleRef(ref); if (!parsed.bundle || parsed.fragment !== undefined || bundleRefToString(parsed) !== ref) return undefined; return { invocation: [...invocation], target: parsed.bundle }; } catch { return undefined; } } /** * Validate an OPTIONAL trailing schedule-input flag tail: empty is valid * (the earlier shape). Otherwise the tail is a sequence of * entries, each EITHER: * * - a single inline `--<name>=<value>` token (the ONLY encoding a * dash-leading value's exact text can round-trip through, since `<value>` * here is everything after the first `=`, whatever its leading character); * or * - a `(--<name>, <value>)` pair, where `<value>` is a single non-flag * token (does not start with `-`) — the earlier shape. * * In both forms `<name>` matches {@link INPUT_NAME_PATTERN} and no name * repeats, except `--env` and `--secret`, which a version 5 entry gives once per ref. A bare flag, a repeated name, a flag-shaped value in the pair * form, or a malformed token are all refused. This validates SHAPE only; * the real materialization against the task's declared contract happens * through the same `parseTaskInputFlags` + `materializeInputFlags` path * `akm task run --<name>` already uses — `parseTaskInputFlags` * accepts both forms natively (its inline-`=` branch never inspects the * value's leading character). */ function isValidSchedulerInputFlagTail(tail) { if (tail.length === 0) return true; const seen = new Set(); let index = 0; while (index < tail.length) { const token = tail[index]; if (!token?.startsWith("--")) return false; const body = token.slice(2); const equalsAt = body.indexOf("="); if (equalsAt !== -1) { const name = body.slice(0, equalsAt); if (!INPUT_NAME_PATTERN.test(name) || seen.has(name)) return false; seen.add(name); index += 1; continue; } if (!INPUT_NAME_PATTERN.test(body) || (seen.has(body) && !REPEATABLE_START_FLAGS.has(body))) return false; const value = tail[index + 1]; if (value === undefined || value.startsWith("-")) return false; seen.add(body); index += 2; } return true; } function invalidSchedulerInvocation() { return new ConfigError("Invalid scheduler invocation; expected public " + "`task run <bundle//concept-id> --scheduled [--<input> <value>…]`, `workflow run <qualified-ref>` or `task dispatch` argv.", "INVALID_CONFIG_FILE"); }