OKAMI OS Documentação Documentation
← Site GitHub
Começar / Visão geral

// começar · 01

O que é o OKAMI OS? What is OKAMI OS?

OKAMI OS é um painel open source para acompanhar agentes de IA em uma interface só. Ele roda local com dados mock, mostra como o estado do agente deve chegar à UI e pode receber dados reais por API, SSE ou uma bridge opcional. OKAMI OS is an open source panel for monitoring AI agents in one interface. It runs locally with mock data, shows how agent state should reach the UI, and can receive real data through API, SSE or an optional bridge.

i
Escolha o caminho certo para o que você quer fazer Choose the right path for what you want to do Quer apenas ver a interface funcionando? Comece pelo quick start. Quer plugar seu agente? Leia o contrato de estado, as rotas HTTP e o stream SSE. Quer adaptar o coletor? Vá para runtime bridge e segurança. Just want to see the interface running? Start with quickstart. Want to plug in your agent? Read the state contract, HTTP routes and SSE stream. Want to adapt the collector? Go to runtime bridge and security.

Rode primeiro em modo mock. Conecte depois. Run mock mode first. Connect later.

O projeto não exige runtime real para abrir a interface. Se nenhuma API estiver configurada, o hook useMissionControl usa src/data/mockMissionControl.js. Isso permite testar layout, navegação, Pixel Office, docs e gráficos antes de plugar dados reais. The project does not require a real runtime to open the UI. If no API is configured, useMissionControl uses src/data/mockMissionControl.js. This lets you test layout, navigation, Pixel Office, docs and charts before plugging in real data.

installnode >= 18
git clone https://github.com/OkamiOps/Okami-Monitor.git okami-os
cd okami-os
npm install
cp .env.example .env.local
npm run dev:all
01 Abrir frontendOpen frontend

Vite sobe em http://localhost:5173.Vite runs at http://localhost:5173.

02 Abrir backendOpen backend

Express escuta em 127.0.0.1:3001.Express listens on 127.0.0.1:3001.

03 Usar mockUse mock

Sem API configurada, a UI usa dados locais.Without an API, the UI uses local data.

04 Conectar runtimeConnect runtime

Depois configure API, SSE ou SSH bridge.Then configure API, SSE or SSH bridge.

Variáveis que mudam o modo de execução. Variables that change runtime behavior.

O arquivo .env.example define o contrato mínimo. Em desenvolvimento, vite.config.js encaminha /api para http://127.0.0.1:3001. Em produção, same-origin assume que existe uma função/proxy atendendo o caminho /api. The .env.example file defines the minimum contract. In development, vite.config.js proxies /api to http://127.0.0.1:3001. In production, same-origin assumes a function/proxy is serving the /api path.

VITE_OKAMI_API_BASE_URLsame-origin ou URL da API. Sem valor em dev, usa mock.same-origin or API URL. Empty in dev falls back to mock.
VITE_OKAMI_API_TOKENBearer opcional enviado pelo cliente.Optional bearer token sent by the client.
VITE_OKAMI_POLL_INTERVAL_MSIntervalo do fallback de polling quando SSE fecha.Polling fallback interval when SSE closes.
OKAMI_API_PORTPorta do backend Express. Padrão: 3001.Express backend port. Default: 3001.
OKAMI_STREAM_INTERVAL_MSIntervalo de coleta do stream SSE. Padrão: 8000.SSE stream collection interval. Default: 8000.
OKAMI_ALLOWED_ORIGINSLista CORS separada por vírgula. Vazio libera origem em dev.Comma-separated CORS allowlist. Empty allows dev origins.
OKAMI_BACKEND_URLBackend real usado pelo proxy de Cloudflare Pages.Real backend used by the Cloudflare Pages proxy.
OKAMI_BACKEND_PROXY_TOKENToken exigido pelo backend quando configurado.Token required by the backend when configured.

Como o repositório está organizado. How the repository is organized.

src/App.jsxSPA principal: navegação, 15 views, modais, tabelas e ações.Main SPA: navigation, 15 views, modals, tables and actions.
src/PixelOfficeCanvas.jsxCanvas Phaser 4 com escritório pixel-art, agentes e mini Kanban.Phaser 4 canvas with pixel-art office, agents and mini Kanban.
src/lib/useMissionControl.jsSSE, fallback polling, mock-first e estado da UI.SSE, polling fallback, mock-first and UI state.
src/lib/apiClient.jsCliente HTTP para state, config, SSH, Kanban, registries e arquivos.HTTP client for state, config, SSH, Kanban, registries and files.
src/data/mockMissionControl.jsDataset local que deixa a UI funcional sem backend.Local dataset that keeps the UI working without a backend.
server/index.jsAPI Express, SSE, rotas Hermes, registries e comandos permitidos.Express API, SSE, Hermes routes, registries and allowed commands.
server/hermesCollector.jsColeta e normaliza sessões, analytics, docs, skills, jobs e Kanban.Collects and normalizes sessions, analytics, docs, skills, jobs and Kanban.
server/sshBridge.jsWrapper ssh2 com key/password, timeout e exec remoto.ssh2 wrapper with key/password, timeout and remote exec.
server/store.jsConfig, secrets e registries em server/.data.Config, secrets and registries in server/.data.
functions/api/[[path]].jsProxy Cloudflare Pages para encaminhar /api ao backend real.Cloudflare Pages proxy that forwards /api to the real backend.

As 15 telas do cockpit. The 15 cockpit screens.

A navegação é definida em navGroups dentro de src/App.jsx. Cada view recebe o mesmo estado base de useMissionControl e decide quais blocos renderizar. Navigation is defined in navGroups inside src/App.jsx. Each view receives the same base state from useMissionControl and decides which blocks to render.

#overviewOverview

Saúde geral, métricas, modelos, atividade recente e estado do runtime.Overall health, metrics, models, recent activity and runtime state.

#usageUsage

Tokens, estimativas de custo, forecast e concentração por modelo/provedor.Tokens, cost estimates, forecast and concentration by model/provider.

#kanbanKanban

Quadro operacional com Backlog, Todo, In Progress, Blocked, Triage, Review e Done.Operational board with Backlog, Todo, In Progress, Blocked, Triage, Review and Done.

#officeOffice

Comando de agentes, cards, inspetor, subagentes e monitor por agente.Agent command view, cards, inspector, subagents and per-agent monitor.

#pixelPixel

Escritório interativo com Phaser, sprites, reuniões, falas e mini Kanban.Interactive office with Phaser, sprites, meetings, dialogue and mini Kanban.

#profilesPerfis

Documentos de identidade, memória e contexto por agente/perfil.Identity, memory and context documents per agent/profile.

#sessionsSessions

Sessões recentes, status, duração, tokens, tool calls e origem.Recent sessions, status, duration, tokens, tool calls and source.

#cronCron

Leitura e edição assistida de crontab e timers systemd permitidos.Assisted reading and editing of allowed crontab and systemd timers.

#configConfig

Arquivos do runtime, campos editáveis e salvamento via bridge.Runtime files, editable fields and bridge-based saving.

#skillsSkills

Uso de skills, docs relacionados e edição de conteúdo quando permitido.Skill usage, related docs and editable content when allowed.

#logsLogs

Linhas normalizadas, níveis, mensagens humanas e leitura rápida de falhas.Normalized lines, levels, human messages and quick failure reading.

#hermesHermes

Configuração do runtime bridge: host, user, key, password, teste SSH e comandos.Runtime bridge configuration: host, user, key, password, SSH test and commands.

#appsApps

Registry editável de apps e endpoints úteis do seu ambiente.Editable registry of apps and useful endpoints in your environment.

#cliCLIs

Verificação de ferramentas locais/remotas como Node, Python, GitHub CLI e Codex.Checks for local/remote tools such as Node, Python, GitHub CLI and Codex.

#docsDocs

Base viva de runbooks, agent briefs, system design e textos editáveis.Living base for runbooks, agent briefs, system design and editable text.

Fluxo de dados no frontend. Frontend data flow.

01App.jsxhash routing + 15 views
02useMissionControlSSE + polling + mock
03apiClientREST wrapper + bearer token
04mockMissionControlfallback state
05ToastProviderasync feedback
06MarkdownLitesafe lightweight render

InicializaçãoInitialization

O app lê window.location.hash para escolher a view inicial. Se o hash não existe ou é inválido, abre overview.The app reads window.location.hash to choose the initial view. If the hash is missing or invalid, it opens overview.

SincronizaçãoSynchronization

Com API configurada, a UI abre EventSource em /api/mission-control/stream. Se fechar, cai para polling em /state.With an API configured, the UI opens EventSource at /api/mission-control/stream. If it closes, it falls back to polling /state.

FallbackFallback

Sem backend, ou com erro de API, o app mantém a interface viva com mockMissionControl e exibe a origem como mock.Without a backend, or after an API error, the app keeps the interface alive with mockMissionControl and marks the source as mock.

Contrato de estado que alimenta a UI. State contract that feeds the UI.

O shape abaixo é o centro do projeto. Você não precisa usar a mesma infraestrutura do autor: qualquer backend pode preencher esse contrato e o painel passa a mostrar seus agentes. The shape below is the center of the project. You do not need to use the author's infrastructure: any backend can fill this contract and the panel will show your agents.

GET /api/mission-control/stateminimum shape
{
  "status": { "label": "Runtime online", "healthy": true, "updatedAt": "..." },
  "metrics": [{ "label": "tokens hoje", "value": "304.3k", "delta": "+18%" }],
  "tokenSeries": { "input": [1200, 1500], "output": [320, 410] },
  "overview": { "serviceHealth": [], "queue": [], "incidents": [] },
  "models": [{ "name": "gpt-5.4", "share": 10 }],
  "activity": [{ "actor": "agent", "message": "...", "status": "OK" }],
  "subscriptions": [],
  "agents": [],
  "liveEvents": [],
  "kanban": { "Backlog": [], "Todo": [], "Done": [] },
  "apiKeys": [],
  "apps": [],
  "docs": [],
  "hermes": {},
  "cliTools": []
}
agentsid, name, role, color, status, currentTask, workspace, tool, logs, workEvents, subagents, tasks
kanbancolumns keyed by status; cards include title, meta, priority, owner, estimate, board
hermesanalytics, sessions, logLines, profileDocs, skillDocs, configFiles, jobs, routes, commands
docsid, title, body, updated, coverage, source, content

Rotas reais do backend Express. Real Express backend routes.

O backend roda em server/index.js. Em desenvolvimento, sem OKAMI_BACKEND_PROXY_TOKEN, a autenticação é liberada. Em produção ou com token configurado, o backend aceita Authorization: Bearer ou x-okami-proxy-token. The backend runs in server/index.js. In development, without OKAMI_BACKEND_PROXY_TOKEN, auth is open. In production or with a token configured, the backend accepts Authorization: Bearer or x-okami-proxy-token.

GET/api/healthHealthcheck simples da API.Simple API healthcheck.
GET/api/mission-control/stateSnapshot completo para a UI.Complete snapshot for the UI.
GET/api/mission-control/streamSSE com eventos state, heartbeat e error.SSE with state, heartbeat and error events.
GET/api/mission-control/appsLista de apps do registry local.List apps from the local registry.
PUT/api/mission-control/apps/:idCria ou atualiza app no registry.Creates or updates an app in the registry.
DELETE/api/mission-control/apps/:idRemove app do registry.Deletes an app from the registry.
GET/api/mission-control/docsLista documentos salvos localmente.Lists locally saved documents.
PUT/api/mission-control/docs/:idCria ou atualiza documento.Creates or updates a document.
DELETE/api/mission-control/docs/:idRemove documento.Deletes a document.
PUT/api/mission-control/apis/:idSalva configuração de provedor/API.Saves provider/API configuration.
POST/api/mission-control/apis/:id/testValida registro de API no painel.Validates an API registry entry.
POST/api/mission-control/apis/:id/rotateSimula/aciona rotação de secret.Simulates/triggers secret rotation.
GET/api/hermes/configLê config do runtime bridge.Reads runtime bridge config.
PUT/api/hermes/configSalva config sem gravar senha crua.Saves config without storing raw password.
POST/api/hermes/ssh/keysRecebe private key e guarda em vault local.Receives a private key and stores it in the local vault.
POST/api/hermes/ssh/passwordGuarda senha SSH como secret local.Stores SSH password as a local secret.
POST/api/hermes/ssh/testTesta conexão SSH com latência.Tests SSH connection with latency.
GET/api/hermes/statusExecuta comandos seguros para status básico.Runs safe commands for basic status.
GET/api/hermes/logsLê tails de logs do runtime.Reads runtime log tails.
GET/api/hermes/kanban/tasksColeta tasks do Kanban real.Collects real Kanban tasks.
POST/api/hermes/kanban/tasksCria task no runtime quando o bridge permite.Creates a runtime task when the bridge allows it.
POST/api/hermes/commandExecuta somente comandos allowlisted.Runs allowlisted commands only.
POST/api/hermes/files/writeEscreve arquivos apenas dentro de escopos Hermes/Codex permitidos.Writes files only within allowed Hermes/Codex scopes.
POST/api/hermes/cron/saveAtualiza crontab remoto com linha validada.Updates remote crontab with a validated line.
POST/api/hermes/systemd-timer/saveAtualiza override de timer systemd.Updates a systemd timer override.

Como o stream ao vivo funciona. How the live stream works.

stream envelopetext/event-stream
event: state
data: {"status":{"healthy":true},"agents":[]}

event: heartbeat
data: {"t":1782130000000}

event: error
data: {"message":"SSH timeout"}
initial

Push inicialInitial push

Ao abrir a conexão, o backend tenta enviar o primeiro snapshot completo.When the connection opens, the backend tries to send the first complete snapshot.

diff

Hash leveLight hash

A API compara tamanho do JSON e lastUpdated para evitar push repetido.The API compares JSON length and lastUpdated to avoid repeated pushes.

alive

Heartbeat

Se nada mudou, envia heartbeat e ping para manter a conexão aberta.If nothing changed, it sends heartbeat and ping to keep the connection open.

fallback

Polling

Se EventSource fechar de vez, o cliente chama /state por intervalo.If EventSource closes, the client calls /state on an interval.

Store local, registries e secrets. Local store, registries and secrets.

O backend usa server/.data para persistir configuração local. Essa pasta deve permanecer fora do Git. Ela permite salvar preferências, apps, docs, APIs e credenciais sem colocar segredos no repositório. The backend uses server/.data to persist local configuration. This folder must stay out of Git. It lets you save preferences, apps, docs, APIs and credentials without putting secrets in the repository.

config.jsonruntime configsshHost, sshUser, hermesHome, routingMode
secrets.jsonvault refsvault://ssh-key/* · vault://ssh-password/*
registry.jsonapps/docs/apiseditable local registries
fingerprintSHA256secret preview without raw value

Conecte qualquer runtime compatível ao painel. Connect any compatible runtime to the panel.

O código inclui uma bridge chamada Hermes porque esse foi o runtime original. Para a comunidade, ela deve ser lida como exemplo de conector: colete dados do seu ambiente, normalize no contrato de estado e mantenha credenciais isoladas no backend. The code includes a bridge named Hermes because that was the original runtime. For the community, treat it as a connector example: collect data from your environment, normalize it into the state contract, and keep credentials isolated in the backend.

AuthKey SSH recomendada; password existe como fallback e fica no vault local.SSH key recommended; password exists as fallback and stays in the local vault.
TimeoutComandos usam timeout para evitar UI presa em operação remota.Commands use timeouts to avoid a remote operation freezing the UI.
RedactionTokens, API keys e env vars são mascarados antes de chegar ao painel.Tokens, API keys and env vars are masked before reaching the panel.
ScopeEscrita de arquivo é bloqueada fora de diretórios permitidos.File writing is blocked outside allowed directories.

O que o collector tenta lerWhat the collector tries to read

state.dbsessions, messages, models, sources, tool calls, token totals
kanban.dbboards, tasks, status, owner, priority, events, logs
profilesSOUL.md, MEMORY.md, USER.md, profile docs, identity files
skills.usage.json, SKILL.md, usage counters, profile ownership
jobscrontab -l, systemctl list-timers, unit names
logstail from runtime log directory with redaction
configsconfig.yaml, .env redacted, settings.json
commandsdoctor, config, status, insights, sessions stats

Pixel Office

O Pixel Office fica em src/PixelOfficeCanvas.jsx. Ele usa Phaser 4 em modo Canvas, carrega sprites de agentes, tiles/objetos do escritório, desenha zonas, mesas, paredes, mini Kanban e movimenta pessoas por rotas ortogonais. Pixel Office lives in src/PixelOfficeCanvas.jsx. It uses Phaser 4 in Canvas mode, loads agent sprites, office tiles/objects, draws zones, desks, walls, mini Kanban and moves people through orthogonal routes.

Pixel Office board view
assetspublic/*office.mp4, rpg characters, modern-office, tmj
sceneOfficeScenepreload, create, update
peoplebuildOfficePeopleagents + tasks into avatars
interactiononSelectAgentclick avatar to open inspector

Tokens visuais e convenções de UI. Visual tokens and UI conventions.

Colors--ok-bg-0..3, --ok-fg*, --ok-orange, --ok-magenta, --ok-cyan, --ok-success.
TypeSpace Grotesk para títulos; JetBrains Mono para labels, comandos e tabelas.Space Grotesk for titles; JetBrains Mono for labels, commands and tables.
ShapeCantos retos por padrão. Pílulas só quando representam status curto.Sharp corners by default. Pills only for short status labels.
Color rhythmCiano, magenta, laranja e verde devem alternar função; evite seção inteira monocromática.Cyan, magenta, orange and green should rotate by function; avoid fully monochrome sections.
MotionTransições curtas com --ok-ease; evite animação que esconda informação.Short transitions with --ok-ease; avoid animation that hides information.
ComponentsBotões, cards, tabs, filter bars, modal, toast, skeleton, markdown lite e terminal cards.Buttons, cards, tabs, filter bars, modal, toast, skeleton, markdown lite and terminal cards.

Build, preview e proxy de produção. Build, preview and production proxy.

production buildvite
npm run build
npm run preview

O repositório inclui functions/api/[[path]].js para Cloudflare Pages. A função copia headers seguros, remove hop-by-hop headers, injeta x-okami-proxy-token e encaminha chamadas para OKAMI_BACKEND_URL. Se o proxy não estiver configurado, retorna 503. The repository includes functions/api/[[path]].js for Cloudflare Pages. The function copies safe headers, removes hop-by-hop headers, injects x-okami-proxy-token and forwards calls to OKAMI_BACKEND_URL. If the proxy is not configured, it returns 503.

headerspublic/_headersX-Frame-Options, nosniff, no-referrer, permissions policy
proxysame-origin /apifrontend can call /api without public backend URL
tokenbackend proxy tokenrequired when production backend is protected

Cuidados de segurança ao conectar dados reais. Security notes for real data integrations.

  • Não versione server/.data, .env.local, private keys, senhas ou dumps de sessão.Do not version server/.data, .env.local, private keys, passwords or session dumps.
  • Prefira usuário SSH com permissões mínimas para leitura e comandos específicos.Prefer an SSH user with minimal permissions for reading and specific commands.
  • Revise o allowlist de /api/hermes/command antes de liberar para outras pessoas.Review the /api/hermes/command allowlist before exposing it to other people.
  • Mantenha o backend atrás de token, VPN, Cloudflare Access ou rede privada quando usar dados reais.Keep the backend behind a token, VPN, Cloudflare Access or private network when using real data.
  • Redija logs e documentos antes de renderizar conteúdo em ambientes compartilhados.Redact logs and documents before rendering content in shared environments.

Problemas comuns. Common issues.

mock

A UI só mostra dados mock.The UI only shows mock data.

Verifique VITE_OKAMI_API_BASE_URL, se o backend está rodando e se /api/mission-control/state responde.Check VITE_OKAMI_API_BASE_URL, whether the backend is running and whether /api/mission-control/state responds.

sse

Stream fecha ou não atualiza.Stream closes or does not update.

Teste /stream, confirme proxy sem buffering e reduza temporariamente OKAMI_STREAM_INTERVAL_MS.Test /stream, confirm proxy without buffering and temporarily reduce OKAMI_STREAM_INTERVAL_MS.

ssh

SSH falha no teste.SSH test fails.

Confirme host, porta, user, private key completa, passphrase e se a chave pública correspondente está autorizada no runtime.Confirm host, port, user, full private key, passphrase and whether the matching public key is authorized in the runtime.

pixel

Pixel Office em branco.Pixel Office is blank.

Verifique assets em public/, console do navegador e se Phaser conseguiu medir o container.Check assets under public/, browser console and whether Phaser could measure the container.

write

Arquivo não salva.File does not save.

A rota bloqueia paths fora de .hermes ou .codex. Ajuste o path ou o escopo conscientemente.The route blocks paths outside .hermes or .codex. Adjust the path or the scope intentionally.

build

Build quebra.Build fails.

Rode npm install, confirme Node >= 18 e execute npm run build antes de abrir PR.Run npm install, confirm Node >= 18 and execute npm run build before opening a PR.

Como contribuir sem quebrar o painel. How to contribute without breaking the panel.

Checklist de PRPR checklist

  • Preserve o modo mock-first: a UI precisa abrir sem backend real.Preserve mock-first mode: the UI must open without a real backend.
  • Não introduza segredos em arquivos versionados.Do not introduce secrets into versioned files.
  • Use tokens --ok-* e mantenha ciano, magenta, laranja e verde em equilíbrio.Use --ok-* tokens and keep cyan, magenta, orange and green balanced.
  • Para nova view, adicione item em navGroups, componente em viewComponents e estado mock correspondente.For a new view, add an item in navGroups, a component in viewComponents and corresponding mock state.
  • Para nova rota, documente método, path, payload, auth e fallback mock.For a new route, document method, path, payload, auth and mock fallback.
  • Rode npm run build e teste hash navigation, troca PT/EN e Pixel Office.Run npm run build and test hash navigation, PT/EN switching and Pixel Office.