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

150 lines (149 loc) • 6.98 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/. /** * LLM helper for the `akm index` memory-inference pass (#201). * * Compresses a single memory body into one higher-signal derived memory. The * pass itself (in `src/indexer/passes/memory-inference.ts`) is responsible for * deciding which memories are pending, persisting the derived memory with the * correct frontmatter (`inferred: true`, `source: <parent-ref>`), and marking * the parent as processed for idempotency. * * This module is intentionally tiny and stateless so tests can stub it via * `mock.module("../src/llm/memory-infer", ...)` without hitting a network. * * The symbolic LLM runner comes from the current index-pass execution * resolution and is passed straight through. */ import memoryInferSystemPrompt from "../assets/prompts/memory-infer-system.md" with { type: "text" }; import memoryInferUserPrompt from "../assets/prompts/memory-infer-user.md" with { type: "text" }; import { effectiveRequestFields } from "../core/llm-inference.js"; import { parseEmbeddedJsonResponse } from "../core/parse.js"; import { warn } from "../core/warn.js"; import { callStructured } from "./structured-call.js"; const SYSTEM_PROMPT = memoryInferSystemPrompt; const USER_PROMPT_PREFIX = memoryInferUserPrompt; const PROMPT_PLACEHOLDERS = new Set([ "short title string", "one sentence summary string", "tag1", "tag2", "search phrase 1", "search phrase 2", "2-3 sentence compressed body preserving key facts verbatim", ]); export const MEMORY_INFER_NO_CHANGE = Object.freeze({ noChange: true }); export function isMemoryInferNoChange(value) { return typeof value === "object" && value !== null && value.noChange === true; } /** * Strict JSON Schema for the derived-memory payload. Sent as `response_format` * and the client drops it once for a provider that rejects it. * * Every property is required (a strict provider refuses otherwise), so the * explicit no-change decision is `noChange: true` with the other fields empty. * That also means the schema cannot demand non-empty fields: the parser below * is the gate that requires a complete payload whenever `noChange` is false. */ export const DERIVED_MEMORY_JSON_SCHEMA = { type: "object", properties: { noChange: { type: "boolean" }, title: { type: "string" }, description: { type: "string" }, content: { type: "string" }, tags: { type: "array", items: { type: "string" }, maxItems: 8 }, searchHints: { type: "array", items: { type: "string" }, maxItems: 6 }, }, required: ["noChange", "title", "description", "content", "tags", "searchHints"], additionalProperties: false, }; /** The temperature a connection's request fields set, if any. */ function configuredTemperature(runner) { const temperature = runner.kind === "connection" ? effectiveRequestFields(runner.request, runner.inference).temperature : undefined; return typeof temperature === "number" ? temperature : undefined; } /** Read the model's reply: a draft, an explicit no-change decision, or `undefined` for one that is unusable. */ function parseDerivedMemory(raw) { if (!raw) return undefined; const parsed = parseEmbeddedJsonResponse(raw); if (!parsed) { warn("memory inference: invalid JSON response from LLM; skipping memory."); return undefined; } // Only a literal boolean `true` is a decision; anything else falls through // to the complete-payload checks, so a malformed reply is never restraint. if (parsed.noChange === true) return MEMORY_INFER_NO_CHANGE; const title = typeof parsed.title === "string" ? parsed.title.trim() : ""; const description = typeof parsed.description === "string" ? parsed.description.trim() : ""; const content = typeof parsed.content === "string" ? parsed.content.trim() : ""; const tags = Array.isArray(parsed.tags) ? parsed.tags .filter((t) => typeof t === "string") .map((t) => t.trim()) .filter(Boolean) .slice(0, 8) : []; const searchHints = Array.isArray(parsed.searchHints) ? parsed.searchHints .filter((h) => typeof h === "string") .map((h) => h.trim()) .filter(Boolean) .slice(0, 6) : []; if (!title || !description || !content || tags.length === 0 || searchHints.length === 0) { warn("memory inference: incomplete derived memory payload from LLM; skipping memory."); return undefined; } if ([title, description, content, ...tags, ...searchHints].some((value) => PROMPT_PLACEHOLDERS.has(value.toLowerCase()))) { warn("memory inference: prompt placeholder response from LLM; skipping memory."); return undefined; } return { title, description, tags, searchHints, content }; } /** * Compress a single memory into one derived memory via the configured LLM. * `body` is the pass's effective input (a `Source context:` section, then the * raw body after `Body:`), appended verbatim to the user prompt. * * Returns the draft, or {@link MEMORY_INFER_NO_CHANGE} when the model explicitly * decides the memory needs no derived memory. Returns `undefined` on any failure * (timeout, invalid JSON, empty or incomplete response, HTML, abort), which is * never the same thing as no-change. Failures are logged via `warn()` but never * thrown — a failed split for one memory must not abort the rest of the index * pass. Whether the pass runs at all is the pass's decision, not this helper's. */ export async function compressMemoryToDerivedMemory(llmRunner, body, signal, telemetry, onRetryAttempt, onNotices) { const trimmedBody = body.trim(); if (!trimmedBody) return undefined; const outcome = await callStructured({ runner: llmRunner, messages: [ { role: "system", content: SYSTEM_PROMPT }, { role: "user", content: `${USER_PROMPT_PREFIX}${trimmedBody}` }, ], request: { // The connection's or the process's configured temperature; 0.1 only when neither sets one. temperature: configuredTemperature(llmRunner) ?? 0.1, signal, responseSchema: DERIVED_MEMORY_JSON_SCHEMA, onRetryAttempt, }, onNotices, }); if (outcome.ok) return parseDerivedMemory(outcome.raw); if (outcome.result?.llmErrorCode === "provider_html_error") { if (telemetry) telemetry.htmlErrorCount = (telemetry.htmlErrorCount ?? 0) + 1; warn(`memory inference: provider returned HTML instead of JSON; skipping memory: ${outcome.error}`); } else { warn(`memory inference failed: ${outcome.error}`); } return undefined; }