mirror of
https://github.com/domfelipe/mika-agent-assist.git
synced 2026-08-07 10:16:43 +00:00
fix: wire mika runtime cron and skill actions
This commit is contained in:
parent
6c0ccff305
commit
e9f22e6ceb
16 changed files with 1562 additions and 1310 deletions
67
README.md
67
README.md
|
|
@ -24,8 +24,10 @@ Já configuradas via `.env` (gerado automaticamente pelo Lovable Cloud):
|
|||
- `PADDLE_API_KEY` / `PADDLE_WEBHOOK_SECRET`
|
||||
- `SUPABASE_SERVICE_ROLE_KEY`
|
||||
- `RAILWAY_API_TOKEN` — token da Railway Public API, usado por `provision-agent`/`suspend-agent`/`resume-agent` para criar e gerenciar containers Hermes.
|
||||
- `OLLAMA_API_KEY` — chave do Ollama Cloud, injetada como env var no container Hermes (imagem custom `ghcr.io/domfelipe/hermes-agent-custom:latest`).
|
||||
- `HERMES_API_SERVER_KEY` — token usado pelo API server interno do Hermes (`API_SERVER_KEY`). Valor atual: `HermesRailwayKey2026SecureToken123456`.
|
||||
- `OLLAMA_API_KEY` — chave do Ollama Cloud, injetada como env var no container Hermes.
|
||||
- `HERMES_RUNTIME_IMAGE` — opcional; imagem Docker usada no Railway. Default: `ghcr.io/domfelipe/hermes-agent-custom:latest`.
|
||||
- `HERMES_API_SERVER_KEY` — token usado pelo API server interno do Hermes (`API_SERVER_KEY`). Gere um valor forte por ambiente e nunca versionado no repo.
|
||||
- `INTERNAL_FUNCTION_SECRET` — segredo server-to-server usado pelo runtime Hermes para chamar Edge Functions internas, como `create-cronjob-from-agent`.
|
||||
- `TELEGRAM_MANAGER_BOT_TOKEN` — token do bot manager (`@mika_managerbot`) usado para criar bots dos clientes em 1 toque via Bot Management Mode do BotFather.
|
||||
- `TELEGRAM_MANAGER_BOT_USERNAME` — username do bot manager, padrão `mika_managerbot` (sem `@`).
|
||||
|
||||
|
|
@ -42,17 +44,21 @@ Já configuradas via `.env` (gerado automaticamente pelo Lovable Cloud):
|
|||
```
|
||||
Resposta esperada: `{ "webhook_set": "...", "telegram_response": { "ok": true } }`.
|
||||
|
||||
> **Imagem Docker custom**: o container roda `ghcr.io/domfelipe/hermes-agent-custom:latest`, que já contém o `SOUL.md` embutido. Por isso não passamos mais `HERMES_SOUL_OVERRIDE` via env var, e o Dockerfile define o `CMD` (sem `startCommand` no Railway). Secrets removidos do projeto: `OPENROUTER_API_KEY`, `OPENAI_API_KEY`, `OPENAI_BASE_URL`, `HERMES_SOUL_OVERRIDE`.
|
||||
> **Imagem Docker custom**: por padrão o container roda `ghcr.io/domfelipe/hermes-agent-custom:latest`, mas `HERMES_RUNTIME_IMAGE` pode apontar para uma tag de branch/sha durante smoke. A imagem já contém o `SOUL.md` embutido. Por isso não passamos mais `HERMES_SOUL_OVERRIDE` via env var, e o Dockerfile define o `CMD` (sem `startCommand` no Railway). Secrets removidos do projeto: `OPENROUTER_API_KEY`, `OPENAI_API_KEY`, `OPENAI_BASE_URL`, `HERMES_SOUL_OVERRIDE`.
|
||||
|
||||
> **Suspend/Resume via flag, não via stop.** Railway não permite parar containers sem redeploy. As Edge Functions `suspend-agent`/`resume-agent` usam a env var `HERMES_SUSPENDED` + `serviceInstanceRedeploy`:
|
||||
>
|
||||
> - `suspend` → upsert `HERMES_SUSPENDED=true` e redeploy → container entra em `sleep infinity`.
|
||||
> - `resume` → upsert `HERMES_SUSPENDED=""` e redeploy → container sobe normal.
|
||||
>
|
||||
> Isso depende do start command verificar a flag. Novos serviços já são provisionados com o comando correto (`HERMES_START_COMMAND` em `_shared/railway.ts`):
|
||||
>
|
||||
> ```bash
|
||||
> /bin/bash -c 'if [ "$HERMES_SUSPENDED" = "true" ]; then echo "Agent suspended" && sleep infinity; fi && if [ -n "$HERMES_SOUL_OVERRIDE" ]; then echo "$HERMES_SOUL_OVERRIDE" > /opt/data/SOUL.md; fi && /opt/hermes/docker/entrypoint.sh gateway run'
|
||||
> ```
|
||||
>
|
||||
> **Para serviços Railway existentes (provisionados antes desta mudança):** atualize manualmente o Start Command via Railway UI/Agent para o comando acima — caso contrário `suspend-agent` apenas marcará `status='suspended'` no banco mas o container continuará rodando.
|
||||
|
||||
> **Suspend/Resume via flag, não via stop.** Railway não permite parar containers sem redeploy. As Edge Functions `suspend-agent`/`resume-agent` usam a env var `HERMES_SUSPENDED` + `serviceInstanceRedeploy`:
|
||||
> - `suspend` → upsert `HERMES_SUSPENDED=true` e redeploy → container entra em `sleep infinity`.
|
||||
> - `resume` → upsert `HERMES_SUSPENDED=""` e redeploy → container sobe normal.
|
||||
>
|
||||
> Isso depende do start command verificar a flag. Novos serviços já são provisionados com o comando correto (`HERMES_START_COMMAND` em `_shared/railway.ts`):
|
||||
> ```bash
|
||||
> /bin/bash -c 'if [ "$HERMES_SUSPENDED" = "true" ]; then echo "Agent suspended" && sleep infinity; fi && if [ -n "$HERMES_SOUL_OVERRIDE" ]; then echo "$HERMES_SOUL_OVERRIDE" > /opt/data/SOUL.md; fi && /opt/hermes/docker/entrypoint.sh gateway run'
|
||||
> ```
|
||||
> **Para serviços Railway existentes (provisionados antes desta mudança):** atualize manualmente o Start Command via Railway UI/Agent para o comando acima — caso contrário `suspend-agent` apenas marcará `status='suspended'` no banco mas o container continuará rodando.
|
||||
- `OPENROUTER_API_KEY` — **obrigatório**. Injetado em cada container Hermes provisionado para que o agente possa chamar os modelos `openrouter/google/gemma-4-*-it`. Sem isso o `provision-agent` retorna 500.
|
||||
- `ADMIN_TELEGRAM_BOT_TOKEN` — token do bot de admin (ex: `@mika_test2_bot`) usado pelo `payments-webhook` para enviar notificações de novos clientes, falhas de pagamento e cancelamentos.
|
||||
- `ADMIN_TELEGRAM_CHAT_ID` — chat ID do admin que recebe as notificações (ex: `179720882`).
|
||||
|
|
@ -155,29 +161,29 @@ Para cada provider abaixo, crie um OAuth app e configure a **Redirect URI**:
|
|||
https://smsarmgoirlcedmqvdgc.supabase.co/functions/v1/oauth-callback
|
||||
```
|
||||
|
||||
| Provider | Console | Scopes mínimos |
|
||||
|----------|---------|----------------|
|
||||
| Provider | Console | Scopes mínimos |
|
||||
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
|
||||
| **Google Workspace** | [console.cloud.google.com](https://console.cloud.google.com) → APIs & Services → Credentials → OAuth 2.0 Client ID (Web app) | `openid email profile https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/calendar` |
|
||||
| **Microsoft 365** | [Azure Portal](https://portal.azure.com) → App registrations → New registration → Web | `openid email profile offline_access Mail.Read Calendars.ReadWrite` |
|
||||
| **Notion** | [notion.so/my-integrations](https://www.notion.so/my-integrations) → New integration (Public) | (definidos na integração) |
|
||||
| **Todoist** | [developer.todoist.com](https://developer.todoist.com/appconsole.html) → App management → Create app | `data:read_write` |
|
||||
| **Cal.com** | [app.cal.com/settings/developer](https://app.cal.com/settings/developer/oauth-clients) → New OAuth Client | `READ_BOOKING WRITE_BOOKING READ_PROFILE` |
|
||||
| **Microsoft 365** | [Azure Portal](https://portal.azure.com) → App registrations → New registration → Web | `openid email profile offline_access Mail.Read Calendars.ReadWrite` |
|
||||
| **Notion** | [notion.so/my-integrations](https://www.notion.so/my-integrations) → New integration (Public) | (definidos na integração) |
|
||||
| **Todoist** | [developer.todoist.com](https://developer.todoist.com/appconsole.html) → App management → Create app | `data:read_write` |
|
||||
| **Cal.com** | [app.cal.com/settings/developer](https://app.cal.com/settings/developer/oauth-clients) → New OAuth Client | `READ_BOOKING WRITE_BOOKING READ_PROFILE` |
|
||||
|
||||
#### 2. Adicionar os 10 secrets no Lovable Cloud
|
||||
|
||||
Pelo menu **Connectors → Lovable Cloud → Secrets**, adicione:
|
||||
|
||||
```
|
||||
GOOGLE_OAUTH_CLIENT_ID
|
||||
GOOGLE_OAUTH_CLIENT_SECRET
|
||||
MICROSOFT_OAUTH_CLIENT_ID
|
||||
MICROSOFT_OAUTH_CLIENT_SECRET
|
||||
NOTION_OAUTH_CLIENT_ID
|
||||
NOTION_OAUTH_CLIENT_SECRET
|
||||
TODOIST_OAUTH_CLIENT_ID
|
||||
TODOIST_OAUTH_CLIENT_SECRET
|
||||
CALCOM_OAUTH_CLIENT_ID
|
||||
CALCOM_OAUTH_CLIENT_SECRET
|
||||
GOOGLE_CLIENT_ID
|
||||
GOOGLE_CLIENT_SECRET
|
||||
MICROSOFT_CLIENT_ID
|
||||
MICROSOFT_CLIENT_SECRET
|
||||
NOTION_CLIENT_ID
|
||||
NOTION_CLIENT_SECRET
|
||||
TODOIST_CLIENT_ID
|
||||
TODOIST_CLIENT_SECRET
|
||||
CALCOM_CLIENT_ID
|
||||
CALCOM_CLIENT_SECRET
|
||||
```
|
||||
|
||||
#### 3. Verificar publicação Realtime
|
||||
|
|
@ -215,8 +221,10 @@ A view `user_integration_limits` e `user_jobs_limits` usam dados de `user_integr
|
|||
- `user_roles` + enum `app_role` + função `has_role()` (substitui `is_admin` em profiles, mais seguro)
|
||||
- Trigger `on_agent_instance_provisioning` usando `pg_net` chama `provision-agent` quando uma agent_instance entra em status `provisioning`
|
||||
- **Edge Functions**:
|
||||
- `provision-agent` (verify_jwt=false): cria serviço Docker no Railway via GraphQL API, configura variáveis (TELEGRAM_BOT_TOKEN do Vault, OPENCODE_ZEN_API_KEY, etc.) e dispara deploy. Apaga webhook do Telegram antes (Hermes opera em polling). Retry com backoff exponencial até 5 tentativas.
|
||||
- `provision-agent` (verify_jwt=false): cria serviço Docker no Railway via GraphQL API, configura Telegram/modelo/soul e o contrato runtime→plataforma (`MIKA_CREATE_CRONJOB_URL`, `MIKA_CREATE_SKILL_URL`, `MIKA_AGENT_INSTANCE_ID`, `MIKA_INTERNAL_FUNCTION_SECRET`), e dispara deploy. Apaga webhook do Telegram antes (Hermes opera em polling). Retry com backoff exponencial até 5 tentativas.
|
||||
- `railway-webhook` (verify_jwt=false): recebe eventos do Railway. SUCCESS → marca agent como `active`; FAILED/CRASHED → marca como `error`.
|
||||
- `create-cronjob-from-agent` / `create-skill-from-agent` (verify_jwt=false): endpoints server-to-server chamados pelo runtime Hermes com `X-Internal-Secret`.
|
||||
- `railway-webhook` garante um pacote padrao de skills antes de sincronizar `/api/skills/sync` no runtime.
|
||||
- **Helper compartilhado**: `supabase/functions/_shared/railway.ts`
|
||||
|
||||
### Etapas pós-deploy (uma única vez) — **OBRIGATÓRIAS**
|
||||
|
|
@ -292,4 +300,3 @@ bun dev # dev server (porta 8080)
|
|||
bun run build # build de produção
|
||||
bun run typecheck
|
||||
```
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue