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

218 lines (217 loc) • 8.43 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/. /** * Service detection utilities for the setup wizard. * * Pure detection functions with no user interaction — each returns * a result object describing what was found. */ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { defaultWhich, detectAgentCliProfiles } from "../integrations/agent/detect.js"; import { HARNESS_CONFIG_PLATFORMS, SESSION_LOG_HARNESSES } from "../integrations/harnesses/index.js"; import { listEndpointModels } from "../llm/model-list.js"; let detectOverrides; /** TEST-ONLY. Swap the network/host probes; pass undefined to restore. */ export function _setDetectForTests(fakes) { detectOverrides = fakes; } // ── Agent Platform Detection ──────────────────────────────────────────────── /** * Setup stash-source candidates, derived from the unified harness registry * (#567). * * The registry is the single source of which harnesses are real stash * sources: a candidate must (a) register a `sessionLogProvider` AND * (b) declare a `setupDetectionDir`. `SESSION_LOG_HARNESSES` already filters by * (a). Adding a new session-log harness with a detection dir makes it * appear here with no edit to this file. */ const AGENT_PLATFORMS = SESSION_LOG_HARNESSES.filter((h) => h.setupDetectionDir).map((h) => ({ name: h.displayName, relPath: h.setupDetectionDir })); /** * Scan the user's home directory for known agent platform config directories. * Supports both HOME (Unix) and USERPROFILE (Windows). */ export function detectAgentPlatforms() { if (detectOverrides?.detectAgentPlatforms) return detectOverrides.detectAgentPlatforms(); const home = process.env.HOME?.trim() || process.env.USERPROFILE?.trim(); if (!home) return []; return AGENT_PLATFORMS.filter((p) => { const fullPath = path.join(home, p.relPath); try { // asset-io: host harness and home probes return fs.statSync(fullPath).isDirectory(); } catch { return false; } }).map((p) => ({ name: p.name, path: path.join(home, p.relPath), })); } /** Local servers that usually speak the OpenAI-compatible API. */ const DEFAULT_LOCAL_ENDPOINTS = [ { baseUrl: "http://localhost:11434", label: "Ollama" }, { baseUrl: "http://localhost:1234", label: "LM Studio" }, { baseUrl: "http://localhost:8080", label: "Local (8080)" }, ]; /** * Probe a single OpenAI-compatible `/v1/models` endpoint. * * Tolerant of failure: any network/timeout/parse error yields an * `available: false` result rather than throwing. */ export async function probeLocalEndpoint(baseUrl, label, timeoutMs = 2000) { const listed = await listEndpointModels({ endpoint: `${baseUrl.replace(/\/$/, "")}/v1` }, timeoutMs); return listed.ok ? { baseUrl, label, available: true, models: [...listed.models].sort() } : { baseUrl, label, available: false, models: [] }; } /** * Probe the default local endpoints (Ollama 11434, LM Studio 1234, generic 8080). * * Never throws: every endpoint being down yields a list of unavailable * results, not an error. */ export async function detectLocalServers() { return Promise.all(DEFAULT_LOCAL_ENDPOINTS.map((e) => probeLocalEndpoint(e.baseUrl, e.label))); } /** * Suggest stash directories, ranked (lower rank = higher priority). * * Sources, in priority order: * 1. An existing config `stashDir` (always rank 0 — no-op / keep current). * 2. A `akm/` or `agent-stash/` directory in the CWD git repo. * 3. `~/akm` then `~/.akm` when they already exist. * * Pure function — filesystem reads only, no network. Tests inject `cwd`/`home`. */ export function detectStashDir(opts) { const cwd = opts?.cwd ?? process.cwd(); const home = opts?.home ?? os.homedir(); const suggestions = []; const seen = new Set(); const push = (p, reason, rank) => { const abs = path.resolve(p); if (seen.has(abs)) return; seen.add(abs); suggestions.push({ path: abs, reason, rank }); }; if (opts?.existingStashDir?.trim()) { push(opts.existingStashDir, "existing config stashDir", 0); } // CWD git repo containing akm/ or agent-stash/ const repoRoot = findGitRepoRoot(cwd); if (repoRoot) { for (const dirName of ["akm", "agent-stash"]) { const candidate = path.join(repoRoot, dirName); try { // asset-io: host harness and home probes if (fs.statSync(candidate).isDirectory()) { push(candidate, `git repo contains ${dirName}/`, 1); } } catch { // not present } } } // ~/akm then ~/.akm when they exist if (home) { for (const dirName of ["akm", ".akm"]) { const candidate = path.join(home, dirName); try { // asset-io: host harness and home probes if (fs.statSync(candidate).isDirectory()) { push(candidate, `${dirName} exists in home`, 2); } } catch { // not present } } } return suggestions.sort((a, b) => a.rank - b.rank); } /** Walk up from `start` looking for a directory containing `.git`. */ function findGitRepoRoot(start) { let dir = path.resolve(start); for (;;) { try { // asset-io: host harness and home probes if (fs.existsSync(path.join(dir, ".git"))) return dir; } catch { // ignore } const parent = path.dirname(dir); if (parent === dir) return undefined; dir = parent; } } /** * The agent programs on PATH that can be enabled as a harness, in registry * order. A harness is installed when its binary is found; OpenCode is detected * like any other. */ export function detectInstalledHarnesses(whichFn = defaultWhich) { const enableable = new Set(HARNESS_CONFIG_PLATFORMS); return detectAgentCliProfiles(undefined, whichFn).flatMap((found) => found.available && found.resolvedPath && enableable.has(found.name) ? [{ platform: found.name, bin: found.bin, path: found.resolvedPath }] : []); } /** * Run the full environment-detection pipeline once and return a single typed * result. Orchestrates harness detection, local-server probes, and stash-dir * suggestions. Tolerant of every detector failing. * * @param opts.existingStashDir Current config stashDir (no-op suggestion). * @param opts.whichFn Binary lookup. Tests inject a stub. * @param opts.probe Contact the local servers. False for an offline run. */ export async function detectEnvironment(opts) { const whichFn = opts?.whichFn ?? defaultWhich; const localServers = opts?.probe === false ? [] : await detectLocalServers().catch(() => []); let agentPlatforms = []; try { agentPlatforms = detectAgentPlatforms(); } catch { agentPlatforms = []; } return { harnesses: detectInstalledHarnesses(whichFn), localServers, stashSuggestions: detectStashDir({ existingStashDir: opts?.existingStashDir, cwd: opts?.cwd, home: opts?.home, }), agentPlatforms, }; } /** Render a compact, human-readable "Detected environment" summary block. */ export function renderDetectionSummary(env) { const lines = ["Detected environment:"]; lines.push(` Harnesses: ${env.harnesses.length > 0 ? env.harnesses.map((h) => h.platform).join(", ") : "none on PATH"}`); const liveServers = env.localServers.filter((s) => s.available); if (liveServers.length > 0) { lines.push(` Local servers: ${liveServers.map((s) => s.label).join(", ")}`); } else { lines.push(" Local servers: none reachable"); } const topStash = env.stashSuggestions[0]; if (topStash) { lines.push(` Stash suggest: ${topStash.path} (${topStash.reason})`); } return lines.join("\n"); }