Go-live runtime sync and control plane hardening (#1)

* Implement Mika runtime sync and go-live controls

* Add CI validation workflow

* Align CI with validated runtime checks

* Fix Mika CI install workflow
This commit is contained in:
Felipe Domingues 2026-04-30 20:41:06 -03:00 committed by GitHub
parent cb54fa4666
commit d87ea2657c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
31 changed files with 4019 additions and 95 deletions

View file

@ -1,7 +1,10 @@
// keep-alive-agents
// Mantém todos os containers Railway dos agentes ativos "acordados" fazendo
// uma request GET /getMe ao Telegram para cada agente. Isso força tráfego de
// saída no container, evitando que o Railway hiberne instâncias ociosas.
// Mantém todos os containers Railway dos agentes ativos "acordados" e aproveita
// o ciclo para reconciliar o estado operacional dos cronjobs de volta no banco.
//
// Estratégia:
// 1. Faz GET /getMe no Telegram quando o agente já tem bot configurado
// 2. Puxa /api/cronjobs do runtime Hermes e atualiza scheduled_jobs
//
// Substitui completamente o UptimeRobot — não precisa de configuração externa
// por agente. Roda via pg_cron a cada 4 minutos.
@ -10,14 +13,18 @@
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.45.4";
import { corsHeaders } from "../_shared/cors.ts";
import { pullAgentCronjobsRuntimeState } from "../_shared/runtime-sync.ts";
const SUPABASE_URL = Deno.env.get("SUPABASE_URL")!;
const SUPABASE_SERVICE_ROLE_KEY = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;
const RAILWAY_API_TOKEN = Deno.env.get("RAILWAY_API_TOKEN") ?? "";
const HERMES_API_SERVER_KEY = Deno.env.get("HERMES_API_SERVER_KEY") ?? "";
interface AgentRow {
id: string;
user_id: string;
telegram_bot_token_vault_id: string;
railway_service_id: string | null;
telegram_bot_token_vault_id: string | null;
telegram_bot_username: string | null;
}
@ -28,12 +35,11 @@ Deno.serve(async (req) => {
auth: { persistSession: false, autoRefreshToken: false },
});
// 1) Buscar agentes ativos com token configurado
// 1) Buscar agentes ativos; Telegram e runtime são tratados separadamente
const { data: agents, error: agentsErr } = await supabase
.from("agent_instances")
.select("id, user_id, telegram_bot_token_vault_id, telegram_bot_username")
.eq("status", "active")
.not("telegram_bot_token_vault_id", "is", null);
.select("id, user_id, railway_service_id, telegram_bot_token_vault_id, telegram_bot_username")
.eq("status", "active");
if (agentsErr) {
console.error("keep-alive: failed to load agents:", agentsErr.message);
@ -41,43 +47,78 @@ Deno.serve(async (req) => {
}
const list = (agents ?? []) as AgentRow[];
let success = 0;
let failed = 0;
let telegramSuccess = 0;
let telegramFailed = 0;
let telegramSkipped = 0;
let runtimeSyncSuccess = 0;
let runtimeSyncFailed = 0;
let runtimeSyncSkipped = 0;
const runtimeSyncEnabled = Boolean(RAILWAY_API_TOKEN && HERMES_API_SERVER_KEY);
// 2) Para cada agente, decrypt token + GET /getMe (em paralelo, mas sem quebrar o loop)
// 2) Para cada agente, ping no Telegram + reconciliação de runtime
await Promise.all(
list.map(async (agent) => {
if (agent.telegram_bot_token_vault_id) {
try {
const { data: secret, error: secretErr } = await supabase.rpc("vault_decrypt_secret", {
secret_id: agent.telegram_bot_token_vault_id,
});
if (secretErr || !secret?.[0]?.decrypted_secret) {
console.warn(`keep-alive: missing token for agent ${agent.id} (${agent.telegram_bot_username ?? "?"})`);
telegramFailed++;
} else {
const token = secret[0].decrypted_secret as string;
const res = await fetch(`https://api.telegram.org/bot${token}/getMe`, { method: "GET" });
if (!res.ok) {
const text = await res.text().catch(() => "");
console.warn(`keep-alive: getMe failed for agent ${agent.id} (${agent.telegram_bot_username ?? "?"}): ${res.status} ${text.slice(0, 200)}`);
telegramFailed++;
} else {
telegramSuccess++;
}
}
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
console.warn(`keep-alive: telegram exception for agent ${agent.id}: ${msg}`);
telegramFailed++;
}
} else {
telegramSkipped++;
}
if (!runtimeSyncEnabled || !agent.railway_service_id) {
runtimeSyncSkipped++;
return;
}
try {
const { data: secret, error: secretErr } = await supabase.rpc("vault_decrypt_secret", {
secret_id: agent.telegram_bot_token_vault_id,
await pullAgentCronjobsRuntimeState({
supabase,
agentInstanceId: agent.id,
railwayToken: RAILWAY_API_TOKEN,
apiKey: HERMES_API_SERVER_KEY,
});
if (secretErr || !secret?.[0]?.decrypted_secret) {
console.warn(`keep-alive: missing token for agent ${agent.id} (${agent.telegram_bot_username ?? "?"})`);
failed++;
return;
}
const token = secret[0].decrypted_secret as string;
const res = await fetch(`https://api.telegram.org/bot${token}/getMe`, { method: "GET" });
if (!res.ok) {
const text = await res.text().catch(() => "");
console.warn(`keep-alive: getMe failed for agent ${agent.id} (${agent.telegram_bot_username ?? "?"}): ${res.status} ${text.slice(0, 200)}`);
failed++;
return;
}
success++;
runtimeSyncSuccess++;
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
console.warn(`keep-alive: exception for agent ${agent.id}: ${msg}`);
failed++;
console.warn(`keep-alive: runtime sync exception for agent ${agent.id}: ${msg}`);
runtimeSyncFailed++;
}
}),
);
const summary = { total: list.length, success, failed };
const summary = {
total: list.length,
telegram_success: telegramSuccess,
telegram_failed: telegramFailed,
telegram_skipped: telegramSkipped,
runtime_sync_enabled: runtimeSyncEnabled,
runtime_sync_success: runtimeSyncSuccess,
runtime_sync_failed: runtimeSyncFailed,
runtime_sync_skipped: runtimeSyncSkipped,
};
console.log("keep-alive summary:", JSON.stringify(summary));
return jsonResponse(200, summary);
});