npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@italosantos-com/cerebro-offline

v0.1.0

Published

Offline-first local copilot with `cerebro` terminal command

Readme

Run and deploy your AI Studio app

This contains everything you need to run your app locally.

View your app in AI Studio: https://ai.studio/apps/81ed5372-9b85-4bfa-91bb-e9353100041e

Run Locally

Prerequisites: Node.js

  1. Install dependencies: npm install
  2. Set the GEMINI_API_KEY in .env.local to your Gemini API key
  3. Run the app: npm run dev

Chat offline no terminal (sem internet) - Python

Este projeto inclui um chat local no terminal em Python, com histórico salvo em JSON.

Pré-requisitos offline

  1. Ter o Ollama instalado localmente
  2. Iniciar o serviço local: ollama serve
  3. Ter pelo menos um modelo baixado (feito uma vez): ollama pull mistral

Se aparecer command not found: ollama no macOS, instale com:

brew install --cask ollama

Depois abra o app Ollama uma vez e rode ollama serve.

Uso

  1. Inicie o chat: python3 chat_cli.py ou npm run chat:offline
  2. (Opcional) Defina um modelo inicial: python3 chat_cli.py llama3.2

O histórico é salvo em conversations.json na raiz do projeto. O aprendizado local é salvo em learning.json na raiz do projeto. Se o Ollama não estiver ativo, o chat inicia em modo offline local usando apenas a base aprendida.

Comandos no chat

  • /help mostra os comandos
  • /new [titulo] cria nova conversa
  • /list lista conversas
  • /use <numero> troca conversa ativa
  • /history exibe histórico da conversa ativa
  • /model <nome> troca o modelo da conversa ativa
  • /learn <pergunta> => <resposta> adiciona aprendizado local
  • /learn-file <arquivo> importa treinamento de arquivo
  • /learn-list lista exemplos aprendidos
  • /learn-clear limpa aprendizados
  • /offline-status mostra status dos recursos locais
  • /perf on|off|status ativa métricas de tempo e contexto usado
  • /try-ollama tenta reconectar no Ollama local
  • /export [arquivo] exporta conversas e aprendizado para JSON
  • /import <arquivo> importa conversas e aprendizado de JSON
  • /exit encerra o chat

Inicialização rápida

No terminal, use:

cerebro central

Arquitetura avançada Python (RAG leve)

Estrutura criada:

  • backend/copilot_terminal.py (copilot técnico local)
  • backend/rag_engine.py (busca vetorial + chamada Ollama)
  • backend/indexer.py (indexador de código útil)
  • backend/settings.py (config otimizada para Mac 2017)
  • backend/watcher.py (aprendizado incremental por monitoramento)
  • data/vector_db/ (índice)
  • knowledge/ (base de conhecimento)
  • projects/ (código para indexação)

Instalação do núcleo IA

python3 -m pip install -r requirements.txt

Recomendado para backend: Python 3.13+ (o launcher cerebro já prioriza python3.13 quando disponível).

Observação: em Python 3.13, sentence-transformers/faiss podem não ter wheel disponível. O backend já inclui fallback leve (embeddings hash + busca vetorial NumPy) para manter funcionamento offline sem travar.

Runtime local compatível (100% offline)

Este projeto agora suporta três runtimes locais:

  • auto (padrão): tenta ollama e depois llama.cpp, senão usa offline.
  • llamacpp: usa modelo .gguf local via llama-cli.
  • offline: sem LLM externo, resposta baseada no RAG local (modo compatível garantido).

Comandos rápidos

  • cerebro central → runtime automático
  • cerebro local → força modo offline compatível
  • cerebro llamacpp → força runtime llama.cpp

Configurar llama.cpp (opcional, recomendado para macOS 12)

  1. Instale llama.cpp (binário llama-cli) de forma compatível com seu sistema.
  2. Coloque um modelo GGUF em models/.
  3. Exemplo de execução:
LLAMACPP_MODEL_PATH=./models/seu-modelo.gguf cerebro llamacpp

Você também pode definir:

  • LLM_RUNTIME=llamacpp|offline|ollama|auto
  • LLAMACPP_BINARY (padrão llama-cli)
  • LLAMACPP_MODEL_PATH

Comandos principais

  • cerebro central inicia o copilot RAG local
  • cerebro local força modo offline local (compatível)
  • cerebro llamacpp força runtime llama.cpp
  • cerebro api inicia API FastAPI local
  • cerebro index reindexa conhecimento/código
  • cerebro watch ativa reindexação incremental

Fluxo recomendado (zero travamento)

  1. Coloque docs em knowledge/
  2. Coloque projetos/código em projects/
  3. Rode cerebro index
  4. Inicie com cerebro central

Método fácil: enviar arquivo de treinamento

Use um dos formatos abaixo e rode:

/learn-file nome-do-arquivo

Formatos aceitos:

  • .json com [{"question":"...","answer":"..."}]
  • .jsonl (1 JSON por linha com question e answer)
  • .csv com colunas question,answer
  • .txt ou .md com linhas pergunta => resposta

Exemplo .json:

[
   {
      "question": "Como criar rota no Express?",
      "answer": "Use app.get('/rota', handler)."
   },
   {
      "question": "Como iniciar Vite?",
      "answer": "Execute npm run dev."
   }
]

MVP: Autocomplete inline offline (VS Code)

1) Iniciar backend local

python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
npm run backend:dev

Para forçar runtime 100% offline compatível:

LLM_RUNTIME=offline npm run backend:dev

O backend sobe em http://127.0.0.1:8000, indexa o projeto ao iniciar e expõe:

  • POST /autocomplete
  • POST /copilot/ask
  • POST /reindex
  • GET /health

O POST /autocomplete retorna também latencyMs (tempo local da inferência em ms).

Também ativa reindexação incremental automática ao detectar mudanças em arquivos de código (.py, .html, .css, .js, .ts, .tsx, .jsx).

Para desativar o watcher:

AUTO_REINDEX_ENABLED=0 npm run backend:dev

2) Rodar Ollama local

ollama serve
ollama pull deepseek-coder:6.7b

3) Carregar extensão local no VS Code

  1. Abra a pasta vscode-extension
  2. Pressione F5 para abrir a janela Extension Development Host
  3. Na janela nova, abra seu projeto web
  4. Comece a digitar em .py, .js, .ts, .html ou .css

As sugestões inline (ghost text) serão buscadas do backend local, usando contexto semântico do projeto (RAG) + Ollama.

Pergunta/resposta local (offline-first)

Você pode consultar o copiloto técnico local com:

curl -X POST "http://127.0.0.1:8000/copilot/ask" \
   -H "Content-Type: application/json" \
   -d '{"question":"Como organizar rotas no Next.js?","topK":3}'

Se o Ollama estiver offline, o endpoint retorna resposta em modo local com base no índice RAG.

O RAG também prioriza exemplos para iniciantes em webapp (Flask, CRUD, forms, templates e estrutura MVC simples).

Fase 3: otimização de latência (Mac 8GB)

O backend agora aplica otimizações para reduzir custo de indexação:

  • Cache persistente de embeddings por hash de conteúdo (data/vector_db/embedding_cache.pkl)
  • Ignora arquivos muito grandes (limite padrão: 400_000 bytes)
  • Limita chunks por arquivo (padrão: 60)

Esses limites ficam em backend/settings.py dentro de INDEXING_CONFIG.

Fase 4: métricas 100% offline

Para ver métricas locais de performance:

curl "http://127.0.0.1:8000/health?debug=true"

O modo debug inclui:

  • requests_total
  • errors_total
  • latency_ms_avg
  • latency_ms_p50
  • latency_ms_p95
  • latency_ms_last

Sem debug, o GET /health continua enxuto para uso normal.

Publicação no npm

Checklist rápido:

npm run release:check

Publicar:

npm run release:publish

Se o npm exigir 2FA/token com bypass, publique com OTP:

NPM_OTP=123456 npm run release:publish:otp