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

269 lines (268 loc) • 12.5 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 { placementTypes, stashDirFor } from "../../core/asset/asset-placement.js"; import { assembleAsset } from "../../core/asset/asset-serialize.js"; import { parseFrontmatter } from "../../core/asset/frontmatter.js"; import { parsePlacementRef } from "../../core/asset/resolve-ref.js"; import { resolveStashDir } from "../../core/common.js"; import { SHIPPED_ALIAS } from "../../core/config/model-aliases.js"; import { generatedContentRejection } from "../../core/content-safety.js"; import { UsageError } from "../../core/errors.js"; import { appendEvent } from "../../core/events.js"; import { resolveStandardsContext } from "../../core/standards/resolve-standards-context.js"; import { warn } from "../../core/warn.js"; import { requireWriteTargetPath, resolveWriteTarget } from "../../core/write-source.js"; import { deriveEntryProvenance } from "../../indexer/installations.js"; import { fillMetadata, sameScope, scopeFromFrontmatter, stampScope } from "../../indexer/passes/metadata.js"; import { buildExecution, currentLayer, resolveExecution, shippedAlias } from "../../integrations/agent/execution.js"; import { buildProposePrompt, PROPOSAL_JSON_SCHEMA, validateProposalPayload, } from "../../integrations/agent/prompts.js"; import { runExecution } from "../../integrations/agent/runner-dispatch.js"; import { isRefused, jsonParser, structuredLoop } from "../../llm/structured.js"; import { outcomeOf } from "../../llm/structured-call.js"; import { baseFailureFields, enoentHintMessage, isEnoentFailure } from "../agent/agent-support.js"; import { createProposal, resolveProposalQueueTarget, } from "./repository.js"; function failureEnvelope(result, type, name, engine, notices, fallbackReason = "non_zero_exit") { return { ...baseFailureFields(result, fallbackReason), schemaVersion: 2, type, name, engine, ...(notices.length > 0 ? { notices } : {}), }; } function noticeFields(notices) { return notices.length > 0 ? { notices } : {}; } /** * Resolve, lower, and dispatch the already-rendered proposal prompt with the * proposal's JSON Schema as its output schema, and capture the reply. A reply * that is not a proposal gets one corrective retry. */ async function dispatchProposalPrompt(prompt, config, options, onDispatchReady) { const current = { ...options.selection, ...(options.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}), outputSchema: PROPOSAL_JSON_SCHEMA, }; // The target is resolved once; a corrective attempt rebuilds only the request, for the same runner. const prepared = resolveExecution({ content: prompt, config, layers: [shippedAlias(SHIPPED_ALIAS.agent), currentLayer(current)], }); const lowered = buildExecution(prepared.request, prepared.runner); const corrected = (content) => buildExecution(resolveExecution({ content, runner: prepared.runner, layers: [currentLayer(current)] }).request, prepared.runner); // Resolution and lowering come before the entry event opens durable state; provider and // runtime failures occur after it, preserving the command-attempt observability contract. const engineName = prepared.request.target.name; onDispatchReady(); options.onDispatchReady?.(); // The loop dispatches at least once, so there is a result. const results = []; const reply = await structuredLoop({ dispatch: async (correction) => { const execution = correction ? corrected(`${prompt}\n\n${correction.text}`) : lowered; const result = await runExecution(execution); results.push(result); return outcomeOf(result); }, parse: jsonParser(validateProposalPayload), }); return { result: results.at(-1), reply, durationMs: results.reduce((total, result) => total + result.durationMs, 0), engineName, ...(lowered.runner.kind === "harness" ? { engineBin: lowered.runner.bin } : {}), notices: lowered.notices, }; } /** * the fully-qualified `bundle//conceptId` item_ref for a proposal * target in `stashDir`. The conceptId is BUILT from the D-R2 static table * (`deriveEntryProvenance`), never looked up, so a propose target that does not * yet exist on disk still keys onto its final spelling; the bundle is the * write-target stash's installation id (same derivation the index write path * uses). Matches `createProposal`'s durable `proposals.ref` mint, so the entry * event, the fallback ref, and the stored proposal all carry one spelling. */ function proposeItemRef(bundleId, type, name) { return deriveEntryProvenance({ bundleId, adapterId: "akm" }, type, name).itemRef; } /** * The command-entry `propose_invoked` event. The ref carries the same * fully-qualified item_ref the durable proposal is minted under * (`proposeItemRef`), so the entry event and the stored proposal agree. */ function emitProposeInvoked(bundleId, options) { const named = options.selection?.connection ?? options.selection?.harness ?? options.selection?.engine; appendEvent({ eventType: "propose_invoked", ref: proposeItemRef(bundleId, options.type, options.name), metadata: { type: options.type, name: options.name, task: options.task, ...(named ? { engine: named } : {}), }, }); } export async function akmPropose(options) { if (!options.type?.trim()) { throw new UsageError("propose: <type> is required.", "MISSING_REQUIRED_ARGUMENT"); } if (!options.name?.trim()) { throw new UsageError("propose: <name> is required.", "MISSING_REQUIRED_ARGUMENT"); } if (!options.task?.trim()) { throw new UsageError("propose: --task is required.", "MISSING_REQUIRED_ARGUMENT"); } if (!stashDirFor(options.type)) { throw new UsageError(`propose: unknown asset type "${options.type}". Known types: ${[...placementTypes()].sort().join(", ")}.`, "INVALID_FLAG_VALUE"); } // 1. Resolve the write target. Connection, harness, model and inference resolution happens // exactly once below through the shared execution cascade. `--bundle` names a // configured, writable bundle (same resolver and errors as `akm remember // --bundle`); its root becomes the stash the proposal is queued for and the // prompt's standards are read from. const config = options.agentConfig ?? (await import("../../core/config/config.js")).loadConfig(); const stash = options.stashDir ?? (options.bundle ? requireWriteTargetPath(resolveWriteTarget(config, options.bundle).source) : resolveStashDir()); const target = resolveProposalQueueTarget(stash, config); // 2. Build terminal user content. // Standards "rulebook" for this target — wiki schema (wiki page) or stash // convention/meta facts (non-wiki asset); empty when neither fires. const standardsContext = resolveStandardsContext(options.type, stash); const prompt = buildProposePrompt({ type: options.type, name: options.name, task: options.task, ...(standardsContext.trim() ? { standardsContext } : {}), }); // 3. Preserve the fully-authored prompt as the terminal user content; the // proposal's JSON Schema crosses the shared resolved/lowered boundary as the // request's output schema, with no synthetic persona, conversation turn, or // tool selection. const dispatch = await dispatchProposalPrompt(prompt, config, options, () => emitProposeInvoked(target.source, options)); const { result, reply, engineName, notices } = dispatch; if (!reply.ok && !isRefused(reply)) { // The dispatch failed. B3: ENOENT / not-found gives an actionable hint. if (isEnoentFailure(result)) { return { ...failureEnvelope(result, options.type, options.name, engineName, notices), error: enoentHintMessage(dispatch.engineBin ?? engineName), }; } return failureEnvelope(result, options.type, options.name, engineName, notices); } // 5. The proposal the model returned on stdout, validated. if (!reply.ok) { return { schemaVersion: 2, ok: false, reason: "parse_error", error: `Engine "${engineName}" reply was not valid proposal JSON after ${reply.attempts} attempts: ${reply.errors.join("; ")}`, type: options.type, name: options.name, engine: engineName, exitCode: result.exitCode, stdout: result.stdout, ...(result.stderr ? { stderr: result.stderr } : {}), ...noticeFields(notices), }; } const payload = reply.value; const unsafeContent = generatedContentRejection(payload.content); if (unsafeContent) { return { schemaVersion: 2, ok: false, reason: "parse_error", error: unsafeContent, type: options.type, name: options.name, engine: engineName, exitCode: result.exitCode, ...noticeFields(notices), }; } // 6. Insert the proposal. Note: we allow the agent's `ref` to normalise the // asset name (e.g. path-cleanup), but only after validating that the ref is // well-formed and the type still matches the requested type. const expectedRef = proposeItemRef(target.source, options.type, options.name); let ref = expectedRef; if (payload.ref) { let parsedRef; try { parsedRef = parsePlacementRef(payload.ref); } catch (err) { return { schemaVersion: 2, ok: false, reason: "parse_error", error: err instanceof Error ? err.message : String(err), type: options.type, name: options.name, engine: engineName, exitCode: result.exitCode, stdout: result.stdout, ...(result.stderr ? { stderr: result.stderr } : {}), ...noticeFields(notices), }; } if (parsedRef.type !== options.type) { return { schemaVersion: 2, ok: false, reason: "parse_error", error: `Agent returned ref type ${parsedRef.type} but expected ${options.type}`, type: options.type, name: options.name, engine: engineName, exitCode: result.exitCode, stdout: result.stdout, ...(result.stderr ? { stderr: result.stderr } : {}), ...noticeFields(notices), }; } ref = proposeItemRef(target.source, parsedRef.type, parsedRef.name); } // Scope is the host's to set, never the model's: the flags' scope replaces what the model wrote. const scope = options.scope ?? {}; const parsedContent = parseFrontmatter(payload.content); const stamped = stampScope(parsedContent.data, scope); const data = fillMetadata(stamped.data, options.metadata); const content = sameScope(scopeFromFrontmatter(parsedContent.data), scope) && Object.keys(data).length === Object.keys(stamped.data).length ? payload.content : assembleAsset(data, parsedContent.content); if (stamped.replaced) warn(`[akm] propose: ignored scope set by the model for ${ref}.`); const frontmatter = payload.frontmatter ? fillMetadata(stampScope(payload.frontmatter, scope).data, options.metadata) : undefined; const createInput = { ref, source: "propose", sourceRun: `propose-${Date.now()}`, target, payload: { content, ...(frontmatter ? { frontmatter } : {}), }, ...(payload.confidence !== undefined ? { confidence: payload.confidence } : {}), }; const proposal = createProposal(stash, createInput, options.ctx); return { schemaVersion: 2, ok: true, proposal, ref: proposal.ref, engine: engineName, durationMs: dispatch.durationMs, ...noticeFields(notices), }; }