Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
feat(agent-skills): add openapiParser and cliRegistryParser
diegosouzapw0a95372746a2
diff --git a/src/lib/agentSkills/cliRegistryParser.ts b/src/lib/agentSkills/cliRegistryParser.tsnew file mode 100644index 0000000000..88c61fb5b8--- /dev/null+++ b/src/lib/agentSkills/cliRegistryParser.ts@@ -0,0 +1,242 @@+/**+ * cliRegistryParser.ts — regex-based parser for bin/cli/commands/*.mjs files.+ *+ * Extracts command families and their subcommands WITHOUT importing the modules+ * (Commander.js has side-effects when required as a program instance, D15).+ *+ * Parse strategy:+ * - Read all *.mjs files under bin/cli/commands/+ * - Detect top-level command name from `.command("<name>")` patterns+ * - Detect subcommands from chained `.command("<sub>")` patterns+ * - Map file basename → SkillArea family via FAMILY_MAP+ */++import fs from "node:fs";+import path from "node:path";+import type { SkillArea } from "./types";++// ── Types ────────────────────────────────────────────────────────────────────++export interface CliCommand {+ /** Canonical command string, e.g. "providers list" */+ name: string;+ /** Description extracted from .description("...") */+ description: string;+ /** Flags extracted from .option("--flag", "...") */+ flags: string[];+ /** Whether this is a top-level command (depth 0) or subcommand (depth > 0) */+ isSubcommand: boolean;+}++export interface ParsedCliRegistry {+ /** All commands keyed by their full name, e.g. "providers list" */+ commands: Map<string, CliCommand>;+ /** Commands grouped by SkillArea family */+ families: Map<SkillArea, CliCommand[]>;+}++// ── Mapping: file basename → CLI SkillArea ───────────────────────────────────++/**+ * Maps a commands/*.mjs basename to its CLI SkillArea.+ * Files that don't map to a known family are ignored.+ */+const FILE_FAMILY_MAP: Record<string, SkillArea> = {+ "serve": "cli-serve",+ "dashboard": "cli-serve",+ "stop": "cli-serve",+ "restart": "cli-serve",+ "health": "cli-health",+ "status": "cli-health",+ "doctor": "cli-health",+ "providers": "cli-providers",+ "provider-cmd": "cli-providers",+ "test-provider": "cli-providers",+ "keys": "cli-keys",+ "oauth": "cli-keys",+ "models": "cli-models",+ "chat": "cli-chat",+ "stream": "cli-chat",+ "repl": "cli-chat",+ "combo": "cli-routing",+ "routing": "cli-routing",+ "resilience": "cli-resilience",+ "quota": "cli-resilience",+ "compression": "cli-compression",+ "context-eng": "cli-contexts",+ "contexts": "cli-contexts",+ "sessions": "cli-contexts",+ "cost": "cli-cost-usage",+ "usage": "cli-cost-usage",+ "pricing": "cli-cost-usage",+ "mcp": "cli-mcp",+ "a2a": "cli-a2a",+ "tunnel": "cli-tunnel",+ "backup": "cli-backup-sync",+ "sync": "cli-backup-sync",+ "cloud": "cli-backup-sync",+ "audit": "cli-policy-audit",+ "policy": "cli-policy-audit",+ "logs": "cli-policy-audit",+ "telemetry": "cli-policy-audit",+ "batches": "cli-batches",+ "files": "cli-batches",+ "eval": "cli-eval",+ "simulate": "cli-eval",+ "skills": "cli-plugins-skills",+ "plugin": "cli-plugins-skills",+ "memory": "cli-plugins-skills",+ "setup": "cli-setup",+ "config": "cli-setup",+ "env": "cli-setup",+ "update": "cli-setup",+ "autostart": "cli-setup",+};++// ── Regex patterns ───────────────────────────────────────────────────────────++// Matches: .command("name") or .command('name') — capture group 1 = name+const COMMAND_RE = /\.command\(\s*["']([^"']+)["']/g;++// Matches: .description("text") or .description('text') — capture group 1 = text+const DESCRIPTION_RE = /\.description\(\s*["']([^"']+)["']/g;++// Matches: .option("--flag ...", "desc") — capture group 1 = flag string+const OPTION_RE = /\.option\(\s*["']([^"']+)["']/g;++// ── Parser helpers ───────────────────────────────────────────────────────────++interface RawCommand {+ name: string;+ description: string;+ flags: string[];+}++/**+ * Extracts all commands (and their immediately following description + options)+ * from a single .mjs file content.+ *+ * Limitation: uses regex, not a full AST — deeply nested or dynamically+ * constructed commands may be missed. This is acceptable for the catalog use-case+ * where we want a list of known subcommand names, not runtime-validated metadata.+ */+function extractCommandsFromContent(content: string, topLevelName: string): RawCommand[] {+ const commands: RawCommand[] = [];++ // Find all .command() call positions+ COMMAND_RE.lastIndex = 0;+ let match: RegExpExecArray | null;+ const commandMatches: Array<{ name: string; index: number }> = [];++ while ((match = COMMAND_RE.exec(content)) !== null) {+ commandMatches.push({ name: match[1], index: match.index });+ }++ for (let i = 0; i < commandMatches.length; i++) {+ const { name: rawName, index: cmdIndex } = commandMatches[i];+ const nextIndex = commandMatches[i + 1]?.index ?? content.length;++ // Slice between this command call and the next to scope description/options+ const slice = content.slice(cmdIndex, nextIndex);++ // Extract description (first match in slice)+ DESCRIPTION_RE.lastIndex = 0;+ const descMatch = DESCRIPTION_RE.exec(slice);+ const description = descMatch ? descMatch[1] : "";++ // Extract flags in slice+ const flags: string[] = [];+ OPTION_RE.lastIndex = 0;+ let optMatch: RegExpExecArray | null;+ while ((optMatch = OPTION_RE.exec(slice)) !== null) {+ flags.push(optMatch[1]);+ }++ // Compose full command name:+ // - If rawName equals the top-level name (or is the isDefault pattern), use as-is+ // - Otherwise, qualify as "topLevel subname"+ const isTopLevel =+ rawName === topLevelName ||+ rawName.startsWith(topLevelName + " ") ||+ // Some files declare standalone root commands (e.g. serve, health)+ !rawName.includes(" ");++ const fullName = isTopLevel && i === 0 ? rawName : `${topLevelName} ${rawName}`;++ commands.push({ name: fullName.trim(), description, flags });+ }++ return commands;+}++// ── Main export ──────────────────────────────────────────────────────────────++/**+ * Reads all `bin/cli/commands/*.mjs` files and extracts CLI command metadata.+ *+ * Returns:+ * - `commands`: flat map of all commands by full name+ * - `families`: commands grouped by SkillArea+ */+export function parseCliRegistry(): ParsedCliRegistry {+ const commandsDir = path.resolve(process.cwd(), "bin", "cli", "commands");++ let files: string[];+ try {+ files = fs.readdirSync(commandsDir).filter((f) => f.endsWith(".mjs"));+ } catch (err) {+ throw new Error(+ `cliRegistryParser: could not read ${commandsDir}. ` ++ `Run from project root. Underlying error: ${err instanceof Error ? err.message : String(err)}`,+ );+ }++ const commands = new Map<string, CliCommand>();+ const families = new Map<SkillArea, CliCommand[]>();++ for (const file of files) {+ const basename = path.basename(file, ".mjs");+ const family = FILE_FAMILY_MAP[basename];+ if (!family) continue; // skip unrecognised files (e.g. runtime.mjs, repl.mjs)++ const filePath = path.join(commandsDir, file);+ let content: string;+ try {+ content = fs.readFileSync(filePath, "utf-8");+ } catch {+ continue; // skip unreadable files+ }++ const rawCmds = extractCommandsFromContent(content, basename);+ if (rawCmds.length === 0) continue;++ for (let i = 0; i < rawCmds.length; i++) {+ const rc = rawCmds[i];+ const cliCmd: CliCommand = {+ name: rc.name,+ description: rc.description,+ flags: rc.flags,+ isSubcommand: i > 0,+ };++ commands.set(rc.name, cliCmd);++ if (!families.has(family)) {+ families.set(family, []);+ }+ families.get(family)!.push(cliCmd);+ }+ }++ return { commands, families };+}++/**+ * Returns command name strings for a given CLI SkillArea family,+ * suitable for `AgentSkill.cliCommands`.+ */+export function getCommandsForFamily(family: SkillArea): string[] {+ const { families } = parseCliRegistry();+ const cmds = families.get(family) ?? [];+ return cmds.map((c) => c.name);+}diff --git a/src/lib/agentSkills/openapiParser.ts b/src/lib/agentSkills/openapiParser.tsnew file mode 100644index 0000000000..ffdf95ed84--- /dev/null+++ b/src/lib/agentSkills/openapiParser.ts@@ -0,0 +1,199 @@+/**+ * openapiParser.ts — parses docs/reference/openapi.yaml to extract endpoint info+ * grouped by SkillArea. Used by the catalog and the generator.+ *+ * Reads the OpenAPI YAML synchronously at runtime (same pattern as+ * src/app/api/openapi/spec/route.ts). Does NOT fetch via HTTP to remain+ * usable as a standalone script/CI tool (D15).+ */++import fs from "node:fs";+import path from "node:path";+import yaml from "js-yaml";+import type { SkillArea } from "./types";++// ── Types ────────────────────────────────────────────────────────────────────++export interface OpenapiPath {+ /** HTTP method (uppercase): "GET", "POST", etc. */+ method: string;+ /** OpenAPI path template, e.g. "/api/providers/{id}" */+ path: string;+ /** Summary from the operation object */+ summary: string;+ /** Description from the operation object (may be absent) */+ description?: string;+ /** OpenAPI tags */+ tags: string[];+}++export interface ParsedOpenapi {+ /** All endpoints keyed by "<METHOD> <path>" */+ paths: Map<string, OpenapiPath>;+ /** Endpoints grouped by SkillArea (only API-mapped areas) */+ areas: Map<SkillArea, OpenapiPath[]>;+}++// ── Mapping: path prefix → SkillArea ────────────────────────────────────────++/**+ * Maps an API path prefix to the corresponding SkillArea.+ * Order matters: more specific prefixes must come before generic ones.+ */+const PATH_AREA_MAP: Array<[string, SkillArea]> = [+ // Auth+ ["/api/auth", "auth"],+ ["/api/session", "auth"],+ // Providers+ ["/api/providers", "providers"],+ ["/api/provider-nodes", "providers"],+ ["/api/provider-models", "providers"],+ // Models+ ["/api/v1/models", "models"],+ ["/api/models", "models"],+ // Combos / routing+ ["/api/combos", "combos-routing"],+ ["/api/fallback", "combos-routing"],+ // API Keys+ ["/api/keys", "api-keys"],+ // Usage logs+ ["/api/usage", "usage-logs"],+ // Budget / rate limit+ ["/api/rate-limit", "budget"],+ ["/api/budget", "budget"],+ // Settings+ ["/api/settings", "settings"],+ ["/api/tags", "settings"],+ // Proxies+ ["/api/settings/proxy", "proxies"],+ // Cache+ ["/api/cache", "cache"],+ // Compression / RTK+ ["/api/settings/compression", "compression"],+ ["/api/compression", "compression"],+ ["/api/context/rtk", "context-rtk"],+ // Resilience+ ["/api/monitoring", "resilience"],+ ["/api/provider-metrics", "resilience"],+ ["/api/circuit-breakers", "resilience"],+ // CLI tools+ ["/api/cli-tools", "cli-tools"],+ // Tunnels+ ["/api/tunnel", "tunnels"],+ // Sync / cloud+ ["/api/cloud", "sync-cloud"],+ ["/api/sync", "sync-cloud"],+ // DB backups+ ["/api/system", "db-backups"],+ ["/api/backup", "db-backups"],+ // Webhooks+ ["/api/webhooks", "webhooks"],+ // MCP+ ["/api/mcp", "mcp"],+ // A2A+ ["/a2a", "agents-a2a"],+ // Version manager+ ["/api/services", "version-manager"],+ ["/api/version", "version-manager"],+ // Inference (catch-all for /api/v1/* proxy endpoints)+ ["/api/v1", "inference"],+];++// ── HTTP methods recognised as operations ────────────────────────────────────++const HTTP_METHODS = ["get", "post", "put", "patch", "delete", "head", "options"] as const;++// ── Parser ───────────────────────────────────────────────────────────────────++function resolveArea(urlPath: string): SkillArea | null {+ for (const [prefix, area] of PATH_AREA_MAP) {+ if (urlPath === prefix || urlPath.startsWith(prefix + "/") || urlPath.startsWith(prefix + "{")) {+ return area;+ }+ }+ return null;+}++// eslint-disable-next-line @typescript-eslint/no-explicit-any+function extractOperations(pathsObj: Record<string, any>): OpenapiPath[] {+ const ops: OpenapiPath[] = [];++ for (const [urlPath, pathItem] of Object.entries(pathsObj)) {+ if (!pathItem || typeof pathItem !== "object") continue;++ for (const method of HTTP_METHODS) {+ const operation = pathItem[method];+ if (!operation || typeof operation !== "object") continue;++ ops.push({+ method: method.toUpperCase(),+ path: urlPath,+ summary: String(operation.summary ?? ""),+ description: operation.description ? String(operation.description) : undefined,+ tags: Array.isArray(operation.tags) ? operation.tags.map(String) : [],+ });+ }+ }++ return ops;+}++/**+ * Parses `docs/reference/openapi.yaml` and returns:+ * - `paths`: all operations keyed by `"METHOD /path"`+ * - `areas`: operations grouped by SkillArea (api skills only)+ *+ * Reads the file synchronously so it can be called from both server context+ * and standalone scripts without async machinery.+ */+export function parseOpenapi(): ParsedOpenapi {+ const yamlPath = path.resolve(process.cwd(), "docs", "reference", "openapi.yaml");+ let rawContent: string;++ try {+ rawContent = fs.readFileSync(yamlPath, "utf-8");+ } catch (err) {+ throw new Error(+ `openapiParser: could not read ${yamlPath}. ` ++ `Run from project root. Underlying error: ${err instanceof Error ? err.message : String(err)}`,+ );+ }++ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const doc = yaml.load(rawContent) as Record<string, any>;++ if (!doc || typeof doc !== "object") {+ throw new Error("openapiParser: parsed YAML is not an object");+ }++ const pathsObj = doc.paths ?? {};+ const operations = extractOperations(pathsObj);++ const paths = new Map<string, OpenapiPath>();+ const areas = new Map<SkillArea, OpenapiPath[]>();++ for (const op of operations) {+ const key = `${op.method} ${op.path}`;+ paths.set(key, op);++ const area = resolveArea(op.path);+ if (area) {+ if (!areas.has(area)) {+ areas.set(area, []);+ }+ areas.get(area)!.push(op);+ }+ }++ return { paths, areas };+}++/**+ * Returns endpoint strings for a given SkillArea, suitable for `AgentSkill.endpoints`.+ * Format: `"GET /api/providers/{id}"`.+ */+export function getEndpointsForArea(area: SkillArea): string[] {+ const { areas } = parseOpenapi();+ const ops = areas.get(area) ?? [];+ return ops.map((op) => `${op.method} ${op.path}`);+}