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(cli): fase 6.1+6.2 — batches e files API (upload/CRUD/output/errors)
diegosouzapw761ff3e78120
diff --git a/bin/cli/commands/batches.mjs b/bin/cli/commands/batches.mjsnew file mode 100644index 0000000000..808522b255--- /dev/null+++ b/bin/cli/commands/batches.mjs@@ -0,0 +1,235 @@+import { readFileSync, writeFileSync } from "node:fs";+import { createInterface } from "node:readline";+import { setTimeout as sleep } from "node:timers/promises";+import { apiFetch, getBaseUrl } from "../api.mjs";+import { emit } from "../output.mjs";+import { t } from "../i18n.mjs";++function fmtTs(v) {+ if (!v) return "-";+ return new Date(typeof v === "number" ? v * 1000 : v).toLocaleString();+}++async function confirm(q) {+ const rl = createInterface({ input: process.stdin, output: process.stdout });+ return new Promise((resolve) => {+ rl.question(`${q} [y/N] `, (a) => {+ rl.close();+ resolve(a.trim().toLowerCase() === "y");+ });+ });+}++function authHeaders(opts) {+ const h = { accept: "application/json" };+ if (opts.apiKey) h["Authorization"] = `Bearer ${opts.apiKey}`;+ return h;+}++const batchSchema = [+ { key: "id", header: "Batch ID", width: 28 },+ { key: "status", header: "Status", width: 14 },+ { key: "endpoint", header: "Endpoint", width: 26 },+ {+ key: "request_counts",+ header: "Total",+ formatter: (v) => (v?.completed != null ? `${v.completed}/${v.total}` : "-"),+ },+ { key: "created_at", header: "Created", formatter: fmtTs },+];++async function uploadFile(filePath, purpose) {+ const { fmtBytes } = await import("./files.mjs");+ const { statSync, readFileSync: readF } = await import("node:fs");+ const { basename } = await import("node:path");+ const stat = statSync(filePath);+ if (stat.size > 100 * 1024 * 1024) {+ process.stderr.write(`Warning: file is ${fmtBytes(stat.size)} (large)\n`);+ }+ const form = new FormData();+ form.append("purpose", purpose);+ form.append("file", new Blob([readF(filePath)]), basename(filePath));++ const res = await apiFetch("/v1/files", { method: "POST", body: form });+ if (!res.ok) {+ process.stderr.write(`Upload failed: ${res.status}\n`);+ process.exit(1);+ }+ return res.json();+}++async function fetchFile(fileId, globalOpts = {}) {+ const res = await fetch(`${getBaseUrl(globalOpts)}/v1/files/${fileId}/content`, {+ headers: authHeaders(globalOpts),+ });+ if (!res.ok) {+ process.stderr.write(`Error fetching file: ${res.status}\n`);+ process.exit(1);+ }+ return res.text();+}++async function waitBatch(id, opts, timeout = 3600000) {+ const deadline = Date.now() + timeout;+ while (Date.now() < deadline) {+ const res = await apiFetch(`/v1/batches/${id}`);+ if (!res.ok) {+ process.stderr.write(`Error: ${res.status}\n`);+ process.exit(1);+ }+ const b = await res.json();+ const done = b.request_counts?.completed ?? 0;+ const total = b.request_counts?.total ?? "?";+ process.stderr.write(`[${b.status}] ${done}/${total}\n`);+ if (["completed", "failed", "expired", "cancelled"].includes(b.status)) {+ emit(b, opts);+ return;+ }+ await sleep(5000);+ }+ process.stderr.write("Timeout\n");+ process.exit(124);+}++export function registerBatches(program) {+ const batches = program.command("batches").description(t("batches.description"));++ batches+ .command("list")+ .option("--status <s>", t("batches.list.status"))+ .option("--limit <n>", t("batches.list.limit"), parseInt, 50)+ .action(async (opts, cmd) => {+ const params = new URLSearchParams({ limit: String(opts.limit) });+ if (opts.status) params.set("status", opts.status);+ const res = await apiFetch(`/v1/batches?${params}`);+ if (!res.ok) {+ process.stderr.write(`Error: ${res.status}\n`);+ process.exit(1);+ }+ const data = await res.json();+ emit(data.data ?? data.items ?? data, cmd.optsWithGlobals(), batchSchema);+ });++ batches.command("get <batchId>").action(async (id, opts, cmd) => {+ const res = await apiFetch(`/v1/batches/${id}`);+ if (!res.ok) {+ process.stderr.write(`Error: ${res.status}\n`);+ process.exit(1);+ }+ emit(await res.json(), cmd.optsWithGlobals());+ });++ batches+ .command("create")+ .description(t("batches.create.description"))+ .requiredOption("--input-file <fileId>", t("batches.create.inputFile"))+ .option("--endpoint <e>", t("batches.create.endpoint"), "/v1/chat/completions")+ .option("--completion-window <w>", t("batches.create.window"), "24h")+ .option(+ "--metadata <kv>",+ t("batches.create.metadata"),+ (v, prev = {}) => {+ const eq = v.indexOf("=");+ if (eq < 0) return prev;+ const k = v.slice(0, eq);+ const val = v.slice(eq + 1);+ return { ...prev, [k]: val };+ },+ {}+ )+ .action(async (opts, cmd) => {+ const body = {+ input_file_id: opts.inputFile,+ endpoint: opts.endpoint,+ completion_window: opts.completionWindow,+ metadata: Object.keys(opts.metadata).length ? opts.metadata : undefined,+ };+ const res = await apiFetch("/v1/batches", { method: "POST", body });+ if (!res.ok) {+ process.stderr.write(`Error: ${res.status}\n`);+ process.exit(1);+ }+ emit(await res.json(), cmd.optsWithGlobals());+ });++ batches+ .command("submit")+ .description(t("batches.submit.description"))+ .requiredOption("--jsonl <path>", t("batches.submit.jsonl"))+ .option("--endpoint <e>", t("batches.submit.endpoint"), "/v1/chat/completions")+ .option("--wait", t("batches.submit.wait"))+ .action(async (opts, cmd) => {+ const globalOpts = cmd.optsWithGlobals();+ const upload = await uploadFile(opts.jsonl, "batch");+ const res = await apiFetch("/v1/batches", {+ method: "POST",+ body: { input_file_id: upload.id, endpoint: opts.endpoint, completion_window: "24h" },+ });+ if (!res.ok) {+ process.stderr.write(`Error: ${res.status}\n`);+ process.exit(1);+ }+ const batch = await res.json();+ emit(batch, globalOpts);+ if (opts.wait) await waitBatch(batch.id, globalOpts);+ });++ batches+ .command("cancel <batchId>")+ .option("--yes", t("batches.cancel.yes"))+ .action(async (id, opts, cmd) => {+ if (!opts.yes) {+ const ok = await confirm(`Cancel batch ${id}?`);+ if (!ok) return;+ }+ const res = await apiFetch(`/v1/batches/${id}/cancel`, { method: "POST" });+ if (!res.ok) {+ process.stderr.write(`Error: ${res.status}\n`);+ process.exit(1);+ }+ process.stdout.write("Cancelled\n");+ });++ batches+ .command("wait <batchId>")+ .option("--timeout <ms>", t("batches.wait.timeout"), parseInt, 3600000)+ .action(async (id, opts, cmd) => waitBatch(id, cmd.optsWithGlobals(), opts.timeout));++ batches+ .command("output <batchId>")+ .option("--out <path>", t("batches.output.out"), "batch-output.jsonl")+ .action(async (id, opts, cmd) => {+ const res = await apiFetch(`/v1/batches/${id}`);+ if (!res.ok) {+ process.stderr.write(`Error: ${res.status}\n`);+ process.exit(1);+ }+ const batch = await res.json();+ if (!batch.output_file_id) {+ process.stderr.write("Not yet completed\n");+ process.exit(1);+ }+ const content = await fetchFile(batch.output_file_id, cmd.optsWithGlobals());+ writeFileSync(opts.out, content);+ process.stdout.write(`Saved to ${opts.out}\n`);+ });++ batches+ .command("errors <batchId>")+ .option("--out <path>", t("batches.errors.out"), "batch-errors.jsonl")+ .action(async (id, opts, cmd) => {+ const res = await apiFetch(`/v1/batches/${id}`);+ if (!res.ok) {+ process.stderr.write(`Error: ${res.status}\n`);+ process.exit(1);+ }+ const batch = await res.json();+ if (!batch.error_file_id) {+ process.stdout.write("No errors\n");+ return;+ }+ const content = await fetchFile(batch.error_file_id, cmd.optsWithGlobals());+ writeFileSync(opts.out, content);+ process.stdout.write(`Saved to ${opts.out}\n`);+ });+}diff --git a/bin/cli/commands/files.mjs b/bin/cli/commands/files.mjsnew file mode 100644index 0000000000..ef4559add3--- /dev/null+++ b/bin/cli/commands/files.mjs@@ -0,0 +1,144 @@+import { createReadStream, readFileSync, statSync, writeFileSync } from "node:fs";+import { basename } from "node:path";+import { createInterface } from "node:readline";+import { apiFetch, getBaseUrl } from "../api.mjs";+import { emit } from "../output.mjs";+import { t } from "../i18n.mjs";++function fmtTs(v) {+ if (!v) return "-";+ return new Date(typeof v === "number" ? v * 1000 : v).toLocaleString();+}++function fmtBytes(n) {+ if (n == null) return "-";+ if (n < 1024) return `${n} B`;+ if (n < 1024 ** 2) return `${(n / 1024).toFixed(1)} KB`;+ if (n < 1024 ** 3) return `${(n / 1024 ** 2).toFixed(1)} MB`;+ return `${(n / 1024 ** 3).toFixed(2)} GB`;+}++async function confirm(q) {+ const rl = createInterface({ input: process.stdin, output: process.stdout });+ return new Promise((resolve) => {+ rl.question(`${q} [y/N] `, (a) => {+ rl.close();+ resolve(a.trim().toLowerCase() === "y");+ });+ });+}++function authHeaders(opts) {+ const h = { accept: "application/json" };+ if (opts.apiKey) h["Authorization"] = `Bearer ${opts.apiKey}`;+ return h;+}++const fileSchema = [+ { key: "id", header: "File ID", width: 30 },+ { key: "filename", header: "Filename", width: 35 },+ { key: "purpose", header: "Purpose", width: 14 },+ { key: "bytes", header: "Bytes", formatter: fmtBytes },+ { key: "created_at", header: "Created", formatter: fmtTs },+ { key: "status", header: "Status" },+];++export function registerFiles(program) {+ const files = program.command("files").description(t("files.description"));++ files+ .command("list")+ .option("--purpose <p>", t("files.list.purpose"))+ .option("--limit <n>", t("files.list.limit"), parseInt, 100)+ .action(async (opts, cmd) => {+ const params = new URLSearchParams({ limit: String(opts.limit) });+ if (opts.purpose) params.set("purpose", opts.purpose);+ const res = await apiFetch(`/v1/files?${params}`);+ if (!res.ok) {+ process.stderr.write(`Error: ${res.status}\n`);+ process.exit(1);+ }+ const data = await res.json();+ emit(data.data ?? data.items ?? data, cmd.optsWithGlobals(), fileSchema);+ });++ files+ .command("get <fileId>")+ .description(t("files.get.description"))+ .action(async (id, opts, cmd) => {+ const res = await apiFetch(`/v1/files/${id}`);+ if (!res.ok) {+ process.stderr.write(`Error: ${res.status}\n`);+ process.exit(1);+ }+ emit(await res.json(), cmd.optsWithGlobals());+ });++ files+ .command("upload <path>")+ .description(t("files.upload.description"))+ .requiredOption("--purpose <p>", t("files.upload.purpose"))+ .action(async (filePath, opts, cmd) => {+ const stat = statSync(filePath);+ if (stat.size > 100 * 1024 * 1024) {+ process.stderr.write(+ `Warning: file is ${fmtBytes(stat.size)} (${stat.size > 500e6 ? "very " : ""}large)\n`+ );+ }+ const globalOpts = cmd.optsWithGlobals();+ const form = new FormData();+ form.append("purpose", opts.purpose);+ form.append("file", new Blob([readFileSync(filePath)]), basename(filePath));++ const res = await fetch(`${getBaseUrl(globalOpts)}/v1/files`, {+ method: "POST",+ headers: authHeaders(globalOpts),+ body: form,+ });+ if (!res.ok) {+ process.stderr.write(`Upload failed: ${res.status}\n`);+ process.exit(1);+ }+ emit(await res.json(), globalOpts);+ });++ files+ .command("content <fileId>")+ .description(t("files.content.description"))+ .option("--out <path>", t("files.content.out"))+ .action(async (id, opts, cmd) => {+ const globalOpts = cmd.optsWithGlobals();+ const res = await fetch(`${getBaseUrl(globalOpts)}/v1/files/${id}/content`, {+ headers: authHeaders(globalOpts),+ });+ if (!res.ok) {+ process.stderr.write(`HTTP ${res.status}\n`);+ process.exit(1);+ }+ if (opts.out) {+ const buf = Buffer.from(await res.arrayBuffer());+ writeFileSync(opts.out, buf);+ process.stdout.write(`Saved ${buf.length} bytes to ${opts.out}\n`);+ } else {+ process.stdout.write(await res.text());+ }+ });++ files+ .command("delete <fileId>")+ .option("--yes", t("files.delete.yes"))+ .action(async (id, opts, cmd) => {+ if (!opts.yes) {+ const ok = await confirm(`Delete file ${id}?`);+ if (!ok) return;+ }+ const res = await apiFetch(`/v1/files/${id}`, { method: "DELETE" });+ if (!res.ok) {+ process.stderr.write(`Error: ${res.status}\n`);+ process.exit(1);+ }+ process.stdout.write("Deleted\n");+ });+}++export { fmtBytes };diff --git a/bin/cli/locales/en.json b/bin/cli/locales/en.jsonindex 21452fecab..4bd1236424 100644--- a/bin/cli/locales/en.json+++ b/bin/cli/locales/en.json@@ -201,12 +201,10 @@},"health": {"title": "Health",- "description": "Show server health status","status": "Status: {status}","uptime": "Uptime: {uptime}","requests": "Requests (24h): {count}",- "cost": "Cost (24h): ${cost}",- "noServer": "Server not running. Start with: omniroute serve"+ "cost": "Cost (24h): ${cost}"},"quota": {"description": "Show provider quota usage",@@ -233,13 +231,6 @@"installing": "Installing {latest}...","done": "Updated to {latest}. Restart the server to apply."},- "health": {- "title": "Health",- "status": "Status: {status}",- "uptime": "Uptime: {uptime}",- "requests": "Requests (24h): {count}",- "cost": "Cost (24h): ${cost}"- },"mcp": {"title": "MCP Server","running": "MCP server running ({transport})",@@ -700,5 +691,221 @@"timeout": "HTTP request timeout in milliseconds","api_key": "API key for OmniRoute server","base_url": "OmniRoute server base URL"+ },+ "files": {+ "description": "Manage files (upload, list, get, download, delete)",+ "list": {+ "purpose": "Filter by purpose",+ "limit": "Max results"+ },+ "get": {+ "description": "Get file metadata"+ },+ "upload": {+ "description": "Upload a file",+ "purpose": "File purpose (batch, assistants, fine-tune)"+ },+ "content": {+ "description": "Download file content",+ "out": "Save to path (default: stdout)"+ },+ "delete": {+ "yes": "Skip confirmation"+ }+ },+ "batches": {+ "description": "Manage OpenAI-compatible batch jobs",+ "list": {+ "status": "Filter by status",+ "limit": "Max results"+ },+ "create": {+ "description": "Create a batch job",+ "inputFile": "Input file ID",+ "endpoint": "Target endpoint",+ "window": "Completion window",+ "metadata": "Add metadata key=value"+ },+ "submit": {+ "description": "Upload JSONL file and create batch",+ "jsonl": "Path to JSONL file",+ "endpoint": "Target endpoint",+ "wait": "Wait for completion"+ },+ "cancel": {+ "yes": "Skip confirmation"+ },+ "wait": {+ "timeout": "Timeout in ms"+ },+ "output": {+ "out": "Save output to path"+ },+ "errors": {+ "out": "Save errors to path"+ }+ },+ "translator": {+ "description": "Translate request bodies between LLM formats",+ "detect": {+ "description": "Detect body format"+ },+ "translate": {+ "description": "Convert body from one format to another"+ },+ "send": {+ "description": "Translate and dispatch upstream"+ },+ "stream": {+ "description": "Stream-translate a request body"+ },+ "from": "Source format (openai|anthropic|gemini|cohere)",+ "to": "Target format (openai|anthropic|gemini|cohere)",+ "file": "Path to request body JSON file",+ "out": "Save output to file",+ "model": "Override model",+ "history": {+ "limit": "Max results"+ }+ },+ "pricing": {+ "description": "Manage pricing data for models",+ "sync": {+ "description": "Sync prices from upstream sources",+ "provider": "Filter by provider",+ "force": "Force re-sync"+ },+ "list": {+ "provider": "Filter by provider",+ "model": "Filter by model",+ "limit": "Max results"+ },+ "defaults": {+ "description": "Manage default pricing",+ "input": "Input cost per 1M tokens (USD)",+ "output": "Output cost per 1M tokens (USD)",+ "cacheRead": "Cache read cost per 1M tokens (USD)",+ "cacheWrite": "Cache write cost per 1M tokens (USD)"+ },+ "diff": {+ "description": "Show divergence from upstream prices",+ "model": "Filter by model"+ }+ },+ "resilience": {+ "description": "Inspect and manage resilience mechanisms",+ "status": {+ "provider": "Filter by provider"+ },+ "breakers": {+ "provider": "Filter by provider"+ },+ "cooldowns": {+ "provider": "Filter by provider",+ "connectionId": "Filter by connection ID"+ },+ "lockouts": {+ "provider": "Filter by provider",+ "model": "Filter by model"+ },+ "reset": {+ "description": "Reset breaker/cooldown state",+ "provider": "Provider to reset",+ "connectionId": "Connection ID to reset",+ "model": "Model to reset lockout",+ "allCooldowns": "Reset all cooldowns for provider",+ "yes": "Skip confirmation"+ },+ "profile": {+ "description": "Manage resilience profile",+ "name": "Profile name"+ },+ "config": {+ "description": "Manage resilience config",+ "threshold": "Failure threshold",+ "resetTimeout": "Reset timeout in ms",+ "baseCooldown": "Base cooldown in ms"+ }+ },+ "nodes": {+ "description": "Manage provider nodes (endpoints)",+ "list": {+ "provider": "Filter by provider",+ "enabled": "Only show enabled nodes"+ },+ "add": {+ "provider": "Provider name",+ "baseUrl": "Base URL for the node",+ "name": "Node name",+ "weight": "Load balancing weight",+ "region": "Region tag",+ "authHeader": "Custom auth header (key=value)"+ },+ "update": {+ "baseUrl": "New base URL",+ "name": "New name",+ "weight": "New weight",+ "region": "New region",+ "enabled": "Enable or disable (true|false)"+ },+ "remove": {+ "yes": "Skip confirmation"+ },+ "validate": {+ "baseUrl": "URL to validate",+ "provider": "Provider to validate against"+ },+ "test": {+ "description": "Send test request to node"+ },+ "metrics": {+ "description": "Show node metrics",+ "period": "Time period (e.g. 24h, 7d)"+ }+ },+ "sync": {+ "description": "Sync configuration between OmniRoute instances",+ "push": {+ "description": "Push config to cloud or remote instance",+ "target": "Target (cloud or context:name)",+ "bundle": "Bundle parts to sync",+ "dryRun": "Preview without applying"+ },+ "pull": {+ "description": "Pull config from cloud or remote",+ "source": "Source (cloud or context:name)",+ "merge": "Merge with existing config",+ "replace": "Replace existing config",+ "dryRun": "Preview without applying"+ },+ "diff": {+ "source": "Source context",+ "target": "Target context"+ },+ "bundle": {+ "description": "Export config as a bundle file",+ "include": "Parts to include (comma-separated)"+ },+ "import": {+ "description": "Import a bundle file",+ "dryRun": "Validate without applying"+ },+ "initialize": {+ "fromCloud": "Initialize from cloud backup"+ },+ "tokens": {+ "description": "Manage sync tokens",+ "create": {+ "name": "Token name",+ "scope": "Token scope",+ "ttl": "Token TTL (e.g. 30d)"+ },+ "revoke": {+ "yes": "Skip confirmation"+ }+ },+ "resolve": {+ "description": "Resolve sync conflicts interactively"+ }}}diff --git a/bin/cli/locales/pt-BR.json b/bin/cli/locales/pt-BR.jsonindex 4396839a1a..a0a397c348 100644--- a/bin/cli/locales/pt-BR.json+++ b/bin/cli/locales/pt-BR.json@@ -201,12 +201,10 @@},"health": {"title": "Saúde",- "description": "Exibir status de saúde do servidor","status": "Status: {status}","uptime": "Uptime: {uptime}","requests": "Requisições (24h): {count}",- "cost": "Custo (24h): ${cost}",- "noServer": "Servidor não está em execução. Inicie com: omniroute serve"+ "cost": "Custo (24h): ${cost}"},"quota": {"description": "Exibir uso de cota dos provedores",@@ -233,13 +231,6 @@"installing": "Instalando {latest}...","done": "Atualizado para {latest}. Reinicie o servidor para aplicar."},- "health": {- "title": "Saúde",- "status": "Status: {status}",- "uptime": "Uptime: {uptime}",- "requests": "Requisições (24h): {count}",- "cost": "Custo (24h): ${cost}"- },"mcp": {"title": "Servidor MCP","call": {@@ -700,5 +691,221 @@"timeout": "Timeout de requisições HTTP em milissegundos","api_key": "Chave de API para o servidor OmniRoute","base_url": "URL base do servidor OmniRoute"+ },+ "files": {+ "description": "Gerenciar arquivos (upload, listar, obter, baixar, deletar)",+ "list": {+ "purpose": "Filtrar por propósito",+ "limit": "Máximo de resultados"+ },+ "get": {+ "description": "Obter metadados do arquivo"+ },+ "upload": {+ "description": "Fazer upload de um arquivo",+ "purpose": "Propósito do arquivo (batch, assistants, fine-tune)"+ },+ "content": {+ "description": "Baixar conteúdo do arquivo",+ "out": "Salvar no caminho (padrão: stdout)"+ },+ "delete": {+ "yes": "Pular confirmação"+ }+ },+ "batches": {+ "description": "Gerenciar jobs em batch (compatível com OpenAI)",+ "list": {+ "status": "Filtrar por status",+ "limit": "Máximo de resultados"+ },+ "create": {+ "description": "Criar um job em batch",+ "inputFile": "ID do arquivo de entrada",+ "endpoint": "Endpoint destino",+ "window": "Janela de conclusão",+ "metadata": "Adicionar metadado key=value"+ },+ "submit": {+ "description": "Fazer upload do JSONL e criar batch",+ "jsonl": "Caminho para o arquivo JSONL",+ "endpoint": "Endpoint destino",+ "wait": "Aguardar conclusão"+ },+ "cancel": {+ "yes": "Pular confirmação"+ },+ "wait": {+ "timeout": "Timeout em ms"+ },+ "output": {+ "out": "Salvar output no caminho"+ },+ "errors": {+ "out": "Salvar erros no caminho"+ }+ },+ "translator": {+ "description": "Traduzir payloads entre formatos LLM",+ "detect": {+ "description": "Detectar formato do body"+ },+ "translate": {+ "description": "Converter body de um formato para outro"+ },+ "send": {+ "description": "Traduzir e despachar para upstream"+ },+ "stream": {+ "description": "Tradução de request em stream"+ },+ "from": "Formato de origem (openai|anthropic|gemini|cohere)",+ "to": "Formato de destino (openai|anthropic|gemini|cohere)",+ "file": "Caminho para o arquivo JSON do request",+ "out": "Salvar output em arquivo",+ "model": "Sobrescrever model",+ "history": {+ "limit": "Máximo de resultados"+ }+ },+ "pricing": {+ "description": "Gerenciar dados de precificação dos modelos",+ "sync": {+ "description": "Sincronizar preços com fontes upstream",+ "provider": "Filtrar por provider",+ "force": "Forçar re-sincronização"+ },+ "list": {+ "provider": "Filtrar por provider",+ "model": "Filtrar por model",+ "limit": "Máximo de resultados"+ },+ "defaults": {+ "description": "Gerenciar preços padrão",+ "input": "Custo de entrada por 1M tokens (USD)",+ "output": "Custo de saída por 1M tokens (USD)",+ "cacheRead": "Custo de leitura de cache por 1M tokens (USD)",+ "cacheWrite": "Custo de escrita de cache por 1M tokens (USD)"+ },+ "diff": {+ "description": "Mostrar divergências em relação ao upstream",+ "model": "Filtrar por model"+ }+ },+ "resilience": {+ "description": "Inspecionar e gerenciar mecanismos de resiliência",+ "status": {+ "provider": "Filtrar por provider"+ },+ "breakers": {+ "provider": "Filtrar por provider"+ },+ "cooldowns": {+ "provider": "Filtrar por provider",+ "connectionId": "Filtrar por ID de conexão"+ },+ "lockouts": {+ "provider": "Filtrar por provider",+ "model": "Filtrar por model"+ },+ "reset": {+ "description": "Resetar estado de breaker/cooldown",+ "provider": "Provider para resetar",+ "connectionId": "ID de conexão para resetar",+ "model": "Model para liberar lockout",+ "allCooldowns": "Resetar todos os cooldowns do provider",+ "yes": "Pular confirmação"+ },+ "profile": {+ "description": "Gerenciar perfil de resiliência",+ "name": "Nome do perfil"+ },+ "config": {+ "description": "Gerenciar configuração de resiliência",+ "threshold": "Limiar de falhas",+ "resetTimeout": "Timeout de reset em ms",+ "baseCooldown": "Cooldown base em ms"+ }+ },+ "nodes": {+ "description": "Gerenciar nodes de provider (endpoints)",+ "list": {+ "provider": "Filtrar por provider",+ "enabled": "Exibir apenas nodes ativos"+ },+ "add": {+ "provider": "Nome do provider",+ "baseUrl": "URL base do node",+ "name": "Nome do node",+ "weight": "Peso para balanceamento de carga",+ "region": "Tag de região",+ "authHeader": "Header de autenticação customizado (key=value)"+ },+ "update": {+ "baseUrl": "Nova URL base",+ "name": "Novo nome",+ "weight": "Novo peso",+ "region": "Nova região",+ "enabled": "Habilitar ou desabilitar (true|false)"+ },+ "remove": {+ "yes": "Pular confirmação"+ },+ "validate": {+ "baseUrl": "URL para validar",+ "provider": "Provider para validar"+ },+ "test": {+ "description": "Enviar requisição de teste ao node"+ },+ "metrics": {+ "description": "Exibir métricas do node",+ "period": "Período de tempo (ex: 24h, 7d)"+ }+ },+ "sync": {+ "description": "Sincronizar configuração entre instâncias OmniRoute",+ "push": {+ "description": "Enviar config para cloud ou instância remota",+ "target": "Destino (cloud ou context:nome)",+ "bundle": "Partes do bundle para sincronizar",+ "dryRun": "Visualizar sem aplicar"+ },+ "pull": {+ "description": "Baixar config da cloud ou remoto",+ "source": "Origem (cloud ou context:nome)",+ "merge": "Mesclar com config existente",+ "replace": "Substituir config existente",+ "dryRun": "Visualizar sem aplicar"+ },+ "diff": {+ "source": "Contexto de origem",+ "target": "Contexto de destino"+ },+ "bundle": {+ "description": "Exportar config como arquivo bundle",+ "include": "Partes a incluir (separadas por vírgula)"+ },+ "import": {+ "description": "Importar arquivo bundle",+ "dryRun": "Validar sem aplicar"+ },+ "initialize": {+ "fromCloud": "Inicializar a partir de backup na cloud"+ },+ "tokens": {+ "description": "Gerenciar tokens de sincronização",+ "create": {+ "name": "Nome do token",+ "scope": "Escopo do token",+ "ttl": "TTL do token (ex: 30d)"+ },+ "revoke": {+ "yes": "Pular confirmação"+ }+ },+ "resolve": {+ "description": "Resolver conflitos de sincronização interativamente"+ }}}diff --git a/tests/unit/cli-batches-commands.test.ts b/tests/unit/cli-batches-commands.test.tsnew file mode 100644index 0000000000..57bb73393c--- /dev/null+++ b/tests/unit/cli-batches-commands.test.ts@@ -0,0 +1,147 @@+import test from "node:test";+import assert from "node:assert/strict";++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("batches list busca /v1/batches", async () => {+ let capturedUrl = "";+ const origFetch = globalThis.fetch;+ globalThis.fetch = ((url: string) => {+ capturedUrl = url;+ return Promise.resolve(makeResp({ data: [] }));+ }) as any;++ await (globalThis.fetch as any)("/v1/batches?limit=50");++ globalThis.fetch = origFetch;+ assert.ok(capturedUrl.includes("/v1/batches"));+});++test("batches list com --status filtra na query", async () => {+ let capturedUrl = "";+ const origFetch = globalThis.fetch;+ globalThis.fetch = ((url: string) => {+ capturedUrl = url;+ return Promise.resolve(makeResp({ data: [] }));+ }) as any;++ const params = new URLSearchParams({ limit: "50", status: "completed" });+ await (globalThis.fetch as any)(`/v1/batches?${params}`);++ globalThis.fetch = origFetch;+ assert.ok(capturedUrl.includes("status=completed"));+});++test("batches create envia input_file_id e endpoint no body", async () => {+ let capturedBody: any = null;+ const origFetch = globalThis.fetch;+ globalThis.fetch = ((_url: string, opts: any) => {+ if (opts?.body) capturedBody = JSON.parse(opts.body);+ return Promise.resolve(makeResp({ id: "batch-1", status: "validating" }));+ }) as any;++ await (globalThis.fetch as any)("/v1/batches", {+ method: "POST",+ body: JSON.stringify({+ input_file_id: "file-1",+ endpoint: "/v1/chat/completions",+ completion_window: "24h",+ }),+ });++ globalThis.fetch = origFetch;+ assert.equal(capturedBody.input_file_id, "file-1");+ assert.equal(capturedBody.endpoint, "/v1/chat/completions");+});++test("batches cancel envia POST para /cancel", async () => {+ let capturedUrl = "";+ let capturedMethod = "";+ const origFetch = globalThis.fetch;+ globalThis.fetch = ((url: string, opts: any) => {+ capturedUrl = url;+ capturedMethod = opts?.method ?? "GET";+ return Promise.resolve(makeResp({ id: "batch-1", status: "cancelling" }));+ }) as any;++ await (globalThis.fetch as any)("/v1/batches/batch-1/cancel", { method: "POST" });++ globalThis.fetch = origFetch;+ assert.ok(capturedUrl.includes("/cancel"));+ assert.equal(capturedMethod, "POST");+});++test("batches get busca por batchId", async () => {+ let capturedUrl = "";+ const origFetch = globalThis.fetch;+ globalThis.fetch = ((url: string) => {+ capturedUrl = url;+ return Promise.resolve(makeResp({ id: "batch-1", status: "completed" }));+ }) as any;++ await (globalThis.fetch as any)("/v1/batches/batch-1");++ globalThis.fetch = origFetch;+ assert.ok(capturedUrl.includes("/v1/batches/batch-1"));+});++test("batches output verifica output_file_id antes de baixar", async () => {+ let callCount = 0;+ const origFetch = globalThis.fetch;+ globalThis.fetch = ((url: string) => {+ callCount++;+ if (url.includes("/v1/batches/batch-1") && !url.includes("/content")) {+ return Promise.resolve(+ makeResp({ id: "batch-1", status: "completed", output_file_id: "file-out-1" })+ );+ }+ return Promise.resolve({+ ok: true,+ status: 200,+ text: () => Promise.resolve('{"custom_id":"r1","response":{}}'),+ } as any);+ }) as any;++ // Simula o fluxo: buscar batch, pegar output_file_id, baixar conteúdo+ const batchRes = await (globalThis.fetch as any)("/v1/batches/batch-1");+ const batch = await batchRes.json();+ assert.equal(batch.output_file_id, "file-out-1");++ globalThis.fetch = origFetch;+});++test("batches.mjs pode ser importado sem erro", async () => {+ const mod = await import("../../bin/cli/commands/batches.mjs");+ assert.equal(typeof mod.registerBatches, "function");+});diff --git a/tests/unit/cli-files-commands.test.ts b/tests/unit/cli-files-commands.test.tsnew file mode 100644index 0000000000..7a72b9a3d3--- /dev/null+++ b/tests/unit/cli-files-commands.test.ts@@ -0,0 +1,128 @@+import test from "node:test";+import assert from "node:assert/strict";++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("files list busca /v1/files", async () => {+ let capturedUrl = "";+ const origFetch = globalThis.fetch;+ globalThis.fetch = ((url: string) => {+ capturedUrl = url;+ return Promise.resolve(+ makeResp({ data: [{ id: "file-1", filename: "test.jsonl", purpose: "batch", bytes: 1024 }] })+ );+ }) as any;++ await (globalThis.fetch as any)("/v1/files?limit=100");++ globalThis.fetch = origFetch;+ assert.ok(capturedUrl.includes("/v1/files"));+});++test("files list com --purpose filtra na query", async () => {+ let capturedUrl = "";+ const origFetch = globalThis.fetch;+ globalThis.fetch = ((url: string) => {+ capturedUrl = url;+ return Promise.resolve(makeResp({ data: [] }));+ }) as any;++ const params = new URLSearchParams({ limit: "100", purpose: "batch" });+ await (globalThis.fetch as any)(`/v1/files?${params}`);++ globalThis.fetch = origFetch;+ assert.ok(capturedUrl.includes("purpose=batch"));+});++test("files get busca por id", async () => {+ let capturedUrl = "";+ const origFetch = globalThis.fetch;+ globalThis.fetch = ((url: string) => {+ capturedUrl = url;+ return Promise.resolve(makeResp({ id: "file-1", purpose: "batch" }));+ }) as any;++ await (globalThis.fetch as any)("/v1/files/file-1");++ globalThis.fetch = origFetch;+ assert.ok(capturedUrl.includes("/v1/files/file-1"));+});++test("files content baixa com --out salva em arquivo", async () => {+ let capturedUrl = "";+ const origFetch = globalThis.fetch;+ globalThis.fetch = ((url: string) => {+ capturedUrl = url;+ return Promise.resolve({+ ok: true,+ status: 200,+ arrayBuffer: () => Promise.resolve(new ArrayBuffer(8)),+ text: () => Promise.resolve("data"),+ } as any);+ }) as any;++ await (globalThis.fetch as any)("/v1/files/file-1/content");++ globalThis.fetch = origFetch;+ assert.ok(capturedUrl.includes("/content"));+});++test("files delete com --yes chama DELETE", async () => {+ let capturedUrl = "";+ let capturedMethod = "";+ const origFetch = globalThis.fetch;+ globalThis.fetch = ((url: string, opts: any) => {+ capturedUrl = url;+ capturedMethod = opts?.method ?? "GET";+ return Promise.resolve(makeResp({}, 204));+ }) as any;++ await (globalThis.fetch as any)("/v1/files/file-1", { method: "DELETE" });++ globalThis.fetch = origFetch;+ assert.ok(capturedUrl.includes("/v1/files/file-1"));+ assert.equal(capturedMethod, "DELETE");+});++test("fmtBytes formata bytes corretamente", async () => {+ const { fmtBytes } = await import("../../bin/cli/commands/files.mjs");+ assert.equal(fmtBytes(512), "512 B");+ assert.equal(fmtBytes(1536), "1.5 KB");+ assert.equal(fmtBytes(1.5 * 1024 * 1024), "1.5 MB");+});++test("files.mjs pode ser importado sem erro", async () => {+ const mod = await import("../../bin/cli/commands/files.mjs");+ assert.equal(typeof mod.registerFiles, "function");+});