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

244 lines (243 loc) • 11.3 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/. import { ConfigError } from "../../core/errors.js"; import { PORTABLE_INFERENCE_KEYS } from "../../core/llm-inference.js"; import { createInlineResolvedCommand, createResolvedExecutionRequest, decodeResolvedExecutionRequest, } from "../../execution/resolved-request.js"; import { isPortableExecutionAgentSelector } from "../../execution/source.js"; import { getHarness } from "../harnesses/index.js"; import { harnessProfile, runtimeProfile } from "./profiles.js"; import { lowerRequest, untranslated } from "./request-lowering.js"; import { mergeLayerInference, parseTimeout, resolveTarget, withReasoningEffort } from "./resolution.js"; import { decodeFrozenRunnerSpec } from "./runner.js"; import { agentRuntime } from "./runtime.js"; /** The farthest layer of a call: the alias its kind of work asks for until something nearer names a model. */ export function shippedAlias(alias) { return { id: "shipped-alias", kind: "installation", values: { model: alias } }; } /** The layer for a call's own flags and arguments: nearer than every other. */ export function currentLayer(values) { return { id: "current-invocation", kind: "current", values }; } function has(values, key) { return (values !== null && values !== undefined && Object.hasOwn(values, key) && values[key] !== undefined); } function nearest(layers, key) { for (let index = layers.length - 1; index >= 0; index -= 1) { const layer = layers[index]; if (layer && has(layer.values, key)) return layer; } return undefined; } function explicit(layer) { return { layer: layer.id, kind: layer.kind, via: layer.kind === "installation" ? "default" : "explicit" }; } /** Record which layer set each inference key, mirroring {@link mergeLayerInference}. */ function recordInferenceProvenance(layers, provenance) { for (const layer of layers) { if (!has(layer.values, "inference")) continue; const source = explicit(layer); provenance["/inference"] = source; const inference = layer.values.inference ?? null; if (inference === null) { for (const key of Object.keys(provenance)) if (key.startsWith("/inference/")) delete provenance[key]; continue; } for (const key of Object.keys(withReasoningEffort(inference))) { provenance[`/inference/${key.replaceAll("~", "~0").replaceAll("/", "~1")}`] = source; } } } /** A journaled runner under this call's layers: the nearest layer's timeout and (exact) model replace its own. */ function applyLayers(runner, layers) { const timeout = nearest(layers, "timeout")?.values.timeout; const model = nearest(layers, "model")?.values.model; return { ...runner, ...(timeout !== undefined ? { timeoutMs: parseTimeout(timeout) } : {}), ...(typeof model === "string" && model ? { model } : {}), }; } /** * Resolve one execution: pick where it runs and the model (`resolveTarget`), merge * the caller's other layers (nearest wins), and build the request for that target. */ export function resolveExecution(input) { const command = input.command ?? createInlineResolvedCommand({ template: input.content ?? "", ...(input.argumentInput !== undefined ? { argumentInput: input.argumentInput } : {}), content: input.content ?? "", }); const layers = input.layers ?? []; const modelWork = input.modelWork === true; let runner; if (input.runner) runner = applyLayers(input.runner, layers); else if (input.config) { runner = resolveTarget({ config: input.config, modelWork, layers: layers.map((layer) => layer.values) }); } else throw new TypeError("resolveExecution needs a config or a runner"); const provenance = {}; const targetLayer = [...layers] .reverse() .find((layer) => has(layer.values, "connection") || has(layer.values, "harness") || has(layer.values, "engine")); provenance.target = targetLayer ? explicit(targetLayer) : { layer: "installation-defaults", kind: "installation", via: "explicit" }; provenance.command = { layer: command.source?.ref ?? "inline", kind: "command", via: "source" }; let persona = input.persona; // The harness's own `agent` is only a default for a request that names none: it never replaces a // persona, and model work keeps its confined agent. let agent; const agentLayer = nearest(layers, "agent"); if (agentLayer) { agent = agentLayer.values.agent; provenance.agent = explicit(agentLayer); // A native selector (or an explicit null) replaces any persona. if (typeof agent !== "string" || !isPortableExecutionAgentSelector(agent)) persona = null; } else if (runner.kind === "harness" && runner.agent !== undefined && !persona && !modelWork) { agent = runner.agent; provenance.agent = { layer: runner.name, kind: "installation", via: "explicit" }; } if (persona) provenance.persona = { layer: persona.source.ref, kind: "agent", via: "source" }; const modelLayer = nearest(layers, "model"); if (modelLayer) provenance.model = explicit(modelLayer); const requested = modelLayer?.values.model; let model; if (runner.model !== undefined) { model = { model: runner.model, ...(typeof requested === "string" && requested !== runner.model ? { alias: requested } : {}), }; } const inference = mergeLayerInference(layers.map((layer) => layer.values)); recordInferenceProvenance(layers, provenance); const select = (key, field) => { const layer = nearest(layers, key); if (layer) provenance[field] = explicit(layer); return layer; }; const schemaLayer = select("outputSchema", "outputSchema"); const timeoutLayer = select("timeout", "runtime.timeoutMs"); const workspaceLayer = select("workspace", "runtime.workspace"); const environmentLayer = select("environment", "runtime.environment"); const workspace = workspaceLayer ? (workspaceLayer.values.workspace ?? null) : runner.kind === "harness" ? runner.workspace : undefined; if (!timeoutLayer) { const targets = runner.kind === "connection" ? input.config?.connections : input.config?.harnesses; const configured = input.config === undefined || Object.hasOwn(targets?.[runner.name] ?? {}, "timeoutMs"); provenance["runtime.timeoutMs"] = { layer: runner.name, kind: "installation", via: configured ? "explicit" : "default", }; } const request = createResolvedExecutionRequest({ command, ...(input.conversation !== undefined ? { conversation: input.conversation } : {}), ...(agent !== undefined ? { agent } : {}), ...(persona !== undefined ? { persona } : {}), target: { name: runner.name, kind: runner.kind, ...(runner.kind === "harness" ? { platform: runner.platform } : {}), }, ...(model ? { model } : {}), ...(inference !== undefined ? { inference } : {}), ...(schemaLayer ? { outputSchema: schemaLayer.values.outputSchema ?? null } : {}), modelWork, runtime: { timeoutMs: runner.timeoutMs, ...(workspace !== undefined ? { workspace } : {}), ...(environmentLayer ? { environment: environmentLayer.values.environment ?? null } : {}), }, }); const sorted = Object.fromEntries(Object.entries(provenance).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))); return { request, runner, provenance: sorted }; } function nonEmpty(value) { return value !== null && value !== undefined && Object.keys(value).length > 0; } function buildChat(request, runner, options) { if (typeof request.agent === "string" && request.persona === null) { throw new ConfigError(`A direct model call cannot consume native agent selector ${JSON.stringify(request.agent)}.`, "INVALID_CONFIG_FILE"); } const notices = []; const skip = (field) => { notices.push(untranslated("connection", field)); }; for (const key of Object.keys(request.inference ?? {}).sort()) { if (!PORTABLE_INFERENCE_KEYS.includes(key)) skip(`inference.${key}`); } const chatOptions = {}; // Sent unless the call opts out; chatCompletion drops it once if the provider rejects it. if (request.outputSchema) chatOptions.responseSchema = request.outputSchema; if (request.runtime.workspace) skip("runtime.workspace"); if (nonEmpty(request.runtime.environment)) skip("runtime.environment"); const messages = [ ...(request.persona ? [{ role: "system", content: request.persona.content }] : []), ...(request.conversation ?? []).map((message) => ({ role: message.role, content: message.content })), { role: "user", content: request.command.content }, ]; return { request, runner, options, messages, chatOptions, notices }; } /** * Build a request for its runner's transport: chat messages for model work on a * connection; otherwise the harness's own builder, which for agent work on a * connection is akm's internal runtime. */ export function buildExecution(request, runner) { const environment = request.runtime.environment; const workspace = request.runtime.workspace; const options = { stdio: "captured", ...(request.runtime.timeoutMs !== undefined ? { timeoutMs: request.runtime.timeoutMs } : {}), ...(typeof workspace === "string" ? { cwd: workspace } : {}), ...(environment ? { env: { ...environment } } : {}), }; if (runner.kind === "connection" && request.modelWork) return buildChat(request, runner, options); // Agent work on a connection runs on akm's own runtime, which is no harness and has its own lowering target. const profile = runner.kind === "harness" ? harnessProfile(runner) : runtimeProfile(runner); const target = runner.kind === "connection" ? agentRuntime.lowering : getHarness(runner.platform); if (!target) { throw new ConfigError(`Agent platform ${JSON.stringify(profile.platform)} has no registered request builder.`, "INVALID_CONFIG_FILE"); } const built = lowerRequest(target, request); return { request, runner, options: { ...options, dispatch: built.dispatch }, profile, notices: built.notices, }; } /** * Resume: build a journaled `{ request, runner }` exactly as frozen. Never * reads config or credentials, so a config edit after the freeze cannot change * what a resumed unit runs. */ export function buildExecutionFromWire(wire) { return buildExecution(decodeResolvedExecutionRequest(wire.request), decodeFrozenRunnerSpec(wire.runner)); }