Skip to content

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

feat(cli): adicionar omniroute memory (Fase 3.1)

diegosouzapw33ad5012c6b1
diff --git a/bin/cli/commands/memory.mjs b/bin/cli/commands/memory.mjs
new file mode 100644
index 0000000000..052ed68c99
--- /dev/null
+++ b/bin/cli/commands/memory.mjs
@@ -0,0 +1,210 @@
+import { readFileSync } from "node:fs";
+import { apiFetch } from "../api.mjs";
+import { emit } from "../output.mjs";
+import { t } from "../i18n.mjs";
+
+const VALID_TYPES = ["user", "feedback", "project", "reference"];
+
+function truncate(v, len = 60) {
+ if (v == null) return "-";
+ const s = String(v);
+ return s.length > len ? s.slice(0, len - 1) + "…" : s;
+}
+
+function fmtTs(v) {
+ if (!v) return "-";
+ try {
+ return new Date(v).toLocaleString();
+ } catch {
+ return String(v);
+ }
+}
+
+const memorySchema = [
+ { key: "id", header: "ID", width: 14 },
+ { key: "type", header: "Type", width: 12 },
+ { key: "content", header: "Content", width: 60, formatter: truncate },
+ { key: "score", header: "Score", formatter: (v) => (v != null ? v.toFixed(3) : "-") },
+ { key: "createdAt", header: "Created", formatter: fmtTs },
+];
+
+function parseDuration(s) {
+ const m = String(s).match(/^(\d+)(d|m|y)$/i);
+ if (!m) return null;
+ const n = parseInt(m[1], 10);
+ const unit = m[2].toLowerCase();
+ const now = Date.now();
+ if (unit === "d") return new Date(now - n * 86400000).toISOString();
+ if (unit === "m") return new Date(now - n * 30 * 86400000).toISOString();
+ if (unit === "y") return new Date(now - n * 365 * 86400000).toISOString();
+ return null;
+}
+
+async function confirm(question) {
+ return new Promise((resolve) => {
+ process.stdout.write(`${question} (yes/no) `);
+ process.stdin.setEncoding("utf8");
+ process.stdin.once("data", (chunk) => {
+ resolve(chunk.toString().trim().toLowerCase().startsWith("y"));
+ });
+ });
+}
+
+export async function runMemorySearch(query, opts, cmd) {
+ const globalOpts = cmd.optsWithGlobals();
+ const params = new URLSearchParams({ q: query, limit: String(opts.limit ?? 20) });
+ if (opts.type) params.set("type", opts.type);
+ if (opts.apiKey) params.set("apiKey", opts.apiKey);
+ if (opts.tokenBudget) params.set("tokenBudget", String(opts.tokenBudget));
+ const res = await apiFetch(`/api/memory?${params}`);
+ if (!res.ok) {
+ process.stderr.write(`Error: ${res.status}\n`);
+ process.exit(1);
+ }
+ const data = await res.json();
+ emit(data.items ?? data, globalOpts, memorySchema);
+}
+
+export async function runMemoryAdd(opts, cmd) {
+ const globalOpts = cmd.optsWithGlobals();
+ const content = opts.content ?? (opts.file ? readFileSync(opts.file, "utf8") : null);
+ if (!content) {
+ process.stderr.write("--content or --file required\n");
+ process.exit(2);
+ }
+ const body = {
+ content,
+ type: opts.type ?? "user",
+ ...(opts.metadata ? { metadata: JSON.parse(opts.metadata) } : {}),
+ ...(opts.apiKey ? { apiKey: opts.apiKey } : {}),
+ };
+ const res = await apiFetch("/api/memory", { method: "POST", body });
+ if (!res.ok) {
+ process.stderr.write(`Error: ${res.status}\n`);
+ process.exit(1);
+ }
+ const created = await res.json();
+ emit(created, globalOpts, memorySchema);
+}
+
+export async function runMemoryClear(opts, cmd) {
+ const globalOpts = cmd.optsWithGlobals();
+ if (!opts.yes) {
+ const ok = await confirm("This will delete memories. Continue?");
+ if (!ok) process.exit(0);
+ }
+ const params = new URLSearchParams();
+ if (opts.type) params.set("type", opts.type);
+ if (opts.olderThan) {
+ const iso = parseDuration(opts.olderThan);
+ if (!iso) {
+ process.stderr.write(`Invalid --older-than value: ${opts.olderThan}\n`);
+ process.exit(2);
+ }
+ params.set("olderThan", iso);
+ }
+ if (opts.apiKey) params.set("apiKey", opts.apiKey);
+ const res = await apiFetch(`/api/memory?${params}`, { method: "DELETE" });
+ const data = await res.json();
+ emit(data, globalOpts);
+}
+
+export async function runMemoryList(opts, cmd) {
+ const globalOpts = cmd.optsWithGlobals();
+ const params = new URLSearchParams({ limit: String(opts.limit ?? 100) });
+ if (opts.type) params.set("type", opts.type);
+ if (opts.apiKey) params.set("apiKey", opts.apiKey);
+ const res = await apiFetch(`/api/memory?${params}`);
+ if (!res.ok) {
+ process.stderr.write(`Error: ${res.status}\n`);
+ process.exit(1);
+ }
+ const data = await res.json();
+ emit(data.items ?? data, globalOpts, memorySchema);
+}
+
+export async function runMemoryGet(id, opts, cmd) {
+ const globalOpts = cmd.optsWithGlobals();
+ const res = await apiFetch(`/api/memory/${id}`);
+ if (!res.ok) {
+ process.stderr.write(`Not found: ${id}\n`);
+ process.exit(1);
+ }
+ const data = await res.json();
+ emit(data, globalOpts, memorySchema);
+}
+
+export async function runMemoryDelete(id, opts, cmd) {
+ const globalOpts = cmd.optsWithGlobals();
+ if (!opts.yes) {
+ const ok = await confirm(`Delete memory ${id}?`);
+ if (!ok) process.exit(0);
+ }
+ const res = await apiFetch(`/api/memory/${id}`, { method: "DELETE" });
+ if (!res.ok) {
+ process.stderr.write(`Error: ${res.status}\n`);
+ process.exit(1);
+ }
+ process.stdout.write(`Deleted: ${id}\n`);
+}
+
+export async function runMemoryHealth(opts, cmd) {
+ const globalOpts = cmd.optsWithGlobals();
+ const res = await apiFetch("/api/memory/health");
+ if (!res.ok) {
+ process.stderr.write(`Error: ${res.status}\n`);
+ process.exit(1);
+ }
+ const data = await res.json();
+ emit(data, globalOpts);
+}
+
+export function registerMemory(program) {
+ const memory = program.command("memory").description(t("memory.description"));
+
+ memory
+ .command("search <query>")
+ .description(t("memory.search.description"))
+ .option("--type <type>", t("memory.search.type"))
+ .option("--limit <n>", t("memory.search.limit"), parseInt, 20)
+ .option("--api-key <key>", t("memory.search.api_key"))
+ .option("--token-budget <n>", t("memory.search.token_budget"), parseInt)
+ .action(runMemorySearch);
+
+ memory
+ .command("add")
+ .description(t("memory.add.description"))
+ .option("--content <text>", t("memory.add.content"))
+ .option("--file <path>", t("memory.add.file"))
+ .option("--type <type>", t("memory.add.type"))
+ .option("--metadata <json>", t("memory.add.metadata"))
+ .option("--api-key <key>", t("memory.add.api_key"))
+ .action(runMemoryAdd);
+
+ memory
+ .command("clear")
+ .description(t("memory.clear.description"))
+ .option("--type <type>", t("memory.clear.type"))
+ .option("--older-than <duration>", t("memory.clear.older"))
+ .option("--api-key <key>", t("memory.clear.api_key"))
+ .option("--yes", t("memory.clear.yes"))
+ .action(runMemoryClear);
+
+ memory
+ .command("list")
+ .description(t("memory.list.description"))
+ .option("--type <type>", t("memory.list.type"))
+ .option("--limit <n>", t("memory.list.limit"), parseInt, 100)
+ .option("--api-key <key>", t("memory.list.api_key"))
+ .action(runMemoryList);
+
+ memory.command("get <id>").description(t("memory.get.description")).action(runMemoryGet);
+
+ memory
+ .command("delete <id>")
+ .description(t("memory.delete.description"))
+ .option("--yes", t("memory.delete.yes"))
+ .action(runMemoryDelete);
+
+ memory.command("health").description(t("memory.health.description")).action(runMemoryHealth);
+}
diff --git a/bin/cli/commands/registry.mjs b/bin/cli/commands/registry.mjs
index 03099fe0c7..d4a8cb20c2 100644
--- a/bin/cli/commands/registry.mjs
+++ b/bin/cli/commands/registry.mjs
@@ -1,3 +1,4 @@
+import { registerMemory } from "./memory.mjs";
import { registerChat } from "./chat.mjs";
import { registerStream } from "./stream.mjs";
import { registerSimulate } from "./simulate.mjs";
@@ -30,6 +31,7 @@ import { registerTestProvider } from "./test-provider.mjs";
import { registerCompletion } from "./completion.mjs";
export function registerCommands(program) {
+ registerMemory(program);
registerChat(program);
registerStream(program);
registerSimulate(program);
diff --git a/bin/cli/locales/en.json b/bin/cli/locales/en.json
index af144fc735..60e77ced6a 100644
--- a/bin/cli/locales/en.json
+++ b/bin/cli/locales/en.json
@@ -274,6 +274,47 @@
"noServer": "Server not running. Start with: omniroute serve",
"noModels": "No models found."
},
+ "memory": {
+ "description": "Manage OmniRoute conversational memory (FTS5 + vector)",
+ "search": {
+ "description": "Search memory entries by semantic query",
+ "type": "Filter by memory type (user|feedback|project|reference)",
+ "limit": "Maximum results (default: 20)",
+ "api_key": "Filter by API key",
+ "token_budget": "Limit total tokens in results"
+ },
+ "add": {
+ "description": "Add a new memory entry",
+ "content": "Memory text content",
+ "file": "Read content from file",
+ "type": "Memory type (default: user)",
+ "metadata": "JSON metadata object",
+ "api_key": "Associate with API key"
+ },
+ "clear": {
+ "description": "Delete memory entries matching filters",
+ "type": "Filter by type",
+ "older": "Delete entries older than duration (30d, 6m, 1y)",
+ "api_key": "Filter by API key",
+ "yes": "Skip confirmation prompt"
+ },
+ "list": {
+ "description": "List memory entries without search ranking",
+ "type": "Filter by type",
+ "limit": "Maximum results (default: 100)",
+ "api_key": "Filter by API key"
+ },
+ "get": {
+ "description": "Get a single memory entry by ID"
+ },
+ "delete": {
+ "description": "Delete a memory entry by ID",
+ "yes": "Skip confirmation prompt"
+ },
+ "health": {
+ "description": "Show memory subsystem health (FTS5 + Qdrant)"
+ }
+ },
"program": {
"description": "OmniRoute — Smart AI Router with Auto Fallback",
"version": "Print version and exit",
diff --git a/bin/cli/locales/pt-BR.json b/bin/cli/locales/pt-BR.json
index 2328cc6f3e..61c498a890 100644
--- a/bin/cli/locales/pt-BR.json
+++ b/bin/cli/locales/pt-BR.json
@@ -274,6 +274,47 @@
"noServer": "Servidor não está em execução. Inicie com: omniroute serve",
"noModels": "Nenhum modelo encontrado."
},
+ "memory": {
+ "description": "Gerenciar memória conversacional do OmniRoute (FTS5 + vetorial)",
+ "search": {
+ "description": "Buscar entradas de memória por query semântica",
+ "type": "Filtrar por tipo (user|feedback|project|reference)",
+ "limit": "Máximo de resultados (padrão: 20)",
+ "api_key": "Filtrar por chave de API",
+ "token_budget": "Limitar total de tokens nos resultados"
+ },
+ "add": {
+ "description": "Adicionar nova entrada de memória",
+ "content": "Conteúdo textual da memória",
+ "file": "Ler conteúdo de arquivo",
+ "type": "Tipo de memória (padrão: user)",
+ "metadata": "Objeto JSON de metadados",
+ "api_key": "Associar a chave de API"
+ },
+ "clear": {
+ "description": "Deletar entradas de memória que correspondem aos filtros",
+ "type": "Filtrar por tipo",
+ "older": "Deletar entradas mais antigas que a duração (30d, 6m, 1y)",
+ "api_key": "Filtrar por chave de API",
+ "yes": "Pular confirmação"
+ },
+ "list": {
+ "description": "Listar entradas de memória sem ranking de busca",
+ "type": "Filtrar por tipo",
+ "limit": "Máximo de resultados (padrão: 100)",
+ "api_key": "Filtrar por chave de API"
+ },
+ "get": {
+ "description": "Obter entrada de memória por ID"
+ },
+ "delete": {
+ "description": "Deletar entrada de memória por ID",
+ "yes": "Pular confirmação"
+ },
+ "health": {
+ "description": "Exibir saúde do subsistema de memória (FTS5 + Qdrant)"
+ }
+ },
"program": {
"description": "OmniRoute — Roteador de IA com Fallback Automático",
"version": "Exibir versão e sair",
diff --git a/tests/unit/cli-memory-commands.test.ts b/tests/unit/cli-memory-commands.test.ts
new file mode 100644
index 0000000000..39c6a64dc5
--- /dev/null
+++ b/tests/unit/cli-memory-commands.test.ts
@@ -0,0 +1,177 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+const MEMORY_ITEMS = [
+ {
+ id: "mem_001",
+ type: "user",
+ content: "User prefers dark mode",
+ score: 0.95,
+ createdAt: "2026-05-10T10:00:00Z",
+ },
+ {
+ id: "mem_002",
+ type: "project",
+ content: "Project uses Next.js 16",
+ score: 0.88,
+ createdAt: "2026-05-09T12:00:00Z",
+ },
+];
+
+function makeResp(data: unknown, status = 200) {
+ const obj = {
+ ok: status < 400,
+ status,
+ exitCode: status < 400 ? 0 : 1,
+ json: () => Promise.resolve(data),
+ text: () => Promise.resolve(JSON.stringify(data)),
+ headers: new Headers(),
+ };
+ obj.json = obj.json.bind(obj);
+ obj.text = obj.text.bind(obj);
+ return obj;
+}
+
+async function captureStdout(fn: () => Promise<void>): Promise<string> {
+ const chunks: string[] = [];
+ const orig = process.stdout.write.bind(process.stdout);
+ process.stdout.write = (c: string | Uint8Array) => {
+ chunks.push(typeof c === "string" ? c : c.toString());
+ return true;
+ };
+ try {
+ await fn();
+ } finally {
+ process.stdout.write = orig;
+ }
+ return chunks.join("");
+}
+
+function makeCmd(output = "json") {
+ return { optsWithGlobals: () => ({ output, quiet: output !== "table" }) };
+}
+
+test("runMemorySearch retorna items como array JSON", async () => {
+ const origFetch = globalThis.fetch;
+ globalThis.fetch = (() => Promise.resolve(makeResp({ items: MEMORY_ITEMS }))) as any;
+
+ const { runMemorySearch } = await import("../../bin/cli/commands/memory.mjs");
+ const out = await captureStdout(() =>
+ runMemorySearch("dark mode", { limit: 20 }, makeCmd() as any)
+ );
+
+ globalThis.fetch = origFetch;
+ const parsed = JSON.parse(out);
+ assert.ok(Array.isArray(parsed));
+ assert.equal(parsed[0].id, "mem_001");
+ assert.equal(parsed[0].type, "user");
+});
+
+test("runMemorySearch envia q e type na query", async () => {
+ let capturedUrl = "";
+ const origFetch = globalThis.fetch;
+ globalThis.fetch = ((url: string) => {
+ capturedUrl = url;
+ return Promise.resolve(makeResp({ items: MEMORY_ITEMS }));
+ }) as any;
+
+ const { runMemorySearch } = await import("../../bin/cli/commands/memory.mjs");
+ await captureStdout(() =>
+ runMemorySearch("react hooks", { limit: 10, type: "project" }, makeCmd() as any)
+ );
+
+ globalThis.fetch = origFetch;
+ assert.ok(capturedUrl.includes("q=react") && capturedUrl.includes("hooks"));
+ assert.ok(capturedUrl.includes("type=project"));
+ assert.ok(capturedUrl.includes("limit=10"));
+});
+
+test("runMemoryAdd envia POST com content e type", async () => {
+ let capturedUrl = "";
+ let capturedInit: any = null;
+ const origFetch = globalThis.fetch;
+ globalThis.fetch = ((url: string, init: any) => {
+ capturedUrl = url;
+ capturedInit = init;
+ return Promise.resolve(makeResp({ id: "mem_new", type: "user", content: "test content" }));
+ }) as any;
+
+ const { runMemoryAdd } = await import("../../bin/cli/commands/memory.mjs");
+ await captureStdout(() =>
+ runMemoryAdd({ content: "test content", type: "user" }, makeCmd() as any)
+ );
+
+ globalThis.fetch = origFetch;
+ assert.ok(capturedUrl.includes("/api/memory"));
+ assert.equal(capturedInit?.method, "POST");
+ const body = JSON.parse(capturedInit?.body);
+ assert.equal(body.content, "test content");
+ assert.equal(body.type, "user");
+});
+
+test("runMemoryList retorna items sem q", async () => {
+ let capturedUrl = "";
+ const origFetch = globalThis.fetch;
+ globalThis.fetch = ((url: string) => {
+ capturedUrl = url;
+ return Promise.resolve(makeResp({ items: MEMORY_ITEMS }));
+ }) as any;
+
+ const { runMemoryList } = await import("../../bin/cli/commands/memory.mjs");
+ const out = await captureStdout(() => runMemoryList({ limit: 100 }, makeCmd() as any));
+
+ globalThis.fetch = origFetch;
+ assert.ok(!capturedUrl.includes("q="));
+ const parsed = JSON.parse(out);
+ assert.ok(Array.isArray(parsed));
+ assert.equal(parsed.length, 2);
+});
+
+test("runMemoryGet busca /api/memory/:id", async () => {
+ let capturedUrl = "";
+ const origFetch = globalThis.fetch;
+ globalThis.fetch = ((url: string) => {
+ capturedUrl = url;
+ return Promise.resolve(makeResp(MEMORY_ITEMS[0]));
+ }) as any;
+
+ const { runMemoryGet } = await import("../../bin/cli/commands/memory.mjs");
+ const out = await captureStdout(() => runMemoryGet("mem_001", {}, makeCmd() as any));
+
+ globalThis.fetch = origFetch;
+ assert.ok(capturedUrl.includes("/api/memory/mem_001"));
+ const parsed = JSON.parse(out);
+ assert.equal(parsed.id, "mem_001");
+});
+
+test("runMemoryHealth retorna status do subsistema", async () => {
+ const origFetch = globalThis.fetch;
+ globalThis.fetch = (() =>
+ Promise.resolve(makeResp({ status: "healthy", fts5: true, qdrant: true }))) as any;
+
+ const { runMemoryHealth } = await import("../../bin/cli/commands/memory.mjs");
+ const out = await captureStdout(() => runMemoryHealth({}, makeCmd() as any));
+
+ globalThis.fetch = origFetch;
+ const parsed = JSON.parse(out);
+ assert.equal(parsed.status, "healthy");
+});
+
+test("runMemoryClear --yes envia DELETE com filtro de type", async () => {
+ let capturedUrl = "";
+ let capturedInit: any = null;
+ const origFetch = globalThis.fetch;
+ globalThis.fetch = ((url: string, init: any) => {
+ capturedUrl = url;
+ capturedInit = init;
+ return Promise.resolve(makeResp({ deleted: 5 }));
+ }) as any;
+
+ const { runMemoryClear } = await import("../../bin/cli/commands/memory.mjs");
+ await captureStdout(() => runMemoryClear({ yes: true, type: "project" }, makeCmd() as any));
+
+ globalThis.fetch = origFetch;
+ assert.ok(capturedUrl.includes("/api/memory"));
+ assert.equal(capturedInit?.method, "DELETE");
+ assert.ok(capturedUrl.includes("type=project"));
+});