refactor(i18n): translate codebase and documentation to English

- Rewrite README.md, DEPLOY.md and RULES.md in English
- Translate module docstring, license string and inline comments
- Rename Portuguese state variables (is_agendamento, is_useragenda,
  is_configia) to English equivalents (is_schedule, is_dailyroutine,
  is_configai)
- Replace Portuguese web-search and file-creation trigger phrases
  with English keywords
This commit is contained in:
2026-10-26 13:50:10 -03:00
parent 4cd968a74e
commit 6b11f05dab
5 changed files with 1368 additions and 1402 deletions
+74 -74
View File
@@ -1,17 +1,17 @@
# PsAgentAI - Deploy em Servidor # PsAgentAI - Server Deployment
Deploy como serviço systemd em Debian/Ubuntu para funcionar 24/7 em VPS. Deploy as a systemd service on Debian/Ubuntu to run 24/7 on a VPS.
--- ---
## Pré-requisitos no servidor ## Prerequisites on the server
```bash ```bash
sudo apt update sudo apt update
sudo apt install -y python3 python3-venv python3-pip git ffmpeg sudo apt install -y python3 python3-venv python3-pip git ffmpeg
``` ```
Habilite o journal se quiser logs persistentes (opcional): Enable journal if you want persistent logs (optional):
```bash ```bash
sudo apt install -y systemd-journal-remote sudo apt install -y systemd-journal-remote
@@ -19,58 +19,58 @@ sudo apt install -y systemd-journal-remote
--- ---
## 1) Copie o projeto para o servidor ## 1) Copy the project to the server
Use git ou scp/rsync. Exemplo com git: Use git or scp/rsync. Example with git:
```bash ```bash
cd /opt cd /opt
sudo git clone <URL_DO_REPOSITORIO> psagentai sudo git clone <REPOSITORY_URL> psagentai
sudo chown -R $USER:$USER /opt/psagentai sudo chown -R $USER:$USER /opt/psagentai
cd /opt/psagentai/app cd /opt/psagentai/app
``` ```
Ajuste o caminho no serviço systemd para o diretório real: Adjust the path in the systemd service to the real directory:
```bash ```bash
nano psagentai.service nano psagentai.service
# altere /home/marco/PsAgentAI/app para /opt/psagentai/app # change /home/marco/PsAgentAI/app to /opt/psagentai/app
``` ```
> O serviço usa `User=marco` por padrão. Crie o usuário se não existir: > The service uses `User=marco` by default. Create the user if it doesn't exist:
> ```bash > ```bash
> sudo useradd -m -s /bin/bash marco || true > sudo useradd -m -s /bin/bash marco || true
> sudo usermod -aG sudo marco > sudo usermod -aG sudo marco
> ``` > ```
> Ou edite `User=` no `.service` para o usuário existente do seu VPS. > Or edit `User=` in the `.service` to an existing user on your VPS.
--- ---
## 2) Configure o `.env` ## 2) Configure `.env`
```bash ```bash
cp .env.example .env # se existir exemplo cp .env.example .env # if example exists
nano .env nano .env
``` ```
Preencha obrigatoriamente: Fill in the required fields:
- `TELEGRAM_BOT_TOKEN` - `TELEGRAM_BOT_TOKEN`
- `TELEGRAM_CHAT_ID` - `TELEGRAM_CHAT_ID`
- `AI_PROVIDER` (`openrouter`, `stepfun`, `qwencloud` ou `llamacpp`) - `AI_PROVIDER` (`openrouter`, `stepfun`, `qwencloud` or `llamacpp`)
- `DEFAULT_MODEL` - `DEFAULT_MODEL`
- pelo menos a chave de IA correspondente ao provider escolhido - at least the AI key corresponding to the chosen provider
Ajuste opcionalmente: Optionally adjust:
- `MIN_INTERVAL_MINUTES` / `MAX_INTERVAL_MINUTES` - `MIN_INTERVAL_MINUTES` / `MAX_INTERVAL_MINUTES`
- `MIN_MESSAGE_LINES` - `MIN_MESSAGE_LINES`
> Importante: no Telegram, envie `/start` uma vez para o bot antes de ligar o serviço, caso contrário ele não conseguirá enviar mensagens iniciantes. > Important: on Telegram, send `/start` once to the bot before turning on the service, otherwise it won't be able to send starting messages.
--- ---
## 3) Instale as dependências ## 3) Install dependencies
```bash ```bash
sudo apt install -y ffmpeg sudo apt install -y ffmpeg
@@ -80,26 +80,26 @@ chmod +x iniciar.sh
./iniciar.sh ./iniciar.sh
``` ```
Esse script cria o `venv`, instala dependências e valida as variáveis do `.env`. This script creates the `venv`, installs dependencies and validates the `.env` variables.
Se o comando acima não instalar `ffmpeg` na versão esperada, use também: If the above command doesn't install the expected `ffmpeg` version, also use:
```bash ```bash
sudo apt install -y ffmpeg sudo apt install -y ffmpeg
``` ```
> O reconhecimento de voz usa `SpeechRecognition` + `pydub` + `ffmpeg`. > Voice recognition uses `SpeechRecognition` + `pydub` + `ffmpeg`.
--- ---
## 4) Instale o serviço systemd ## 4) Install the systemd service
```bash ```bash
# caminho absoluto no seu servidor # absolute path on your server
sudo nano /etc/systemd/system/psagentai.service sudo nano /etc/systemd/system/psagentai.service
``` ```
Conteúdo mínimo: Minimum content:
```ini ```ini
[Unit] [Unit]
@@ -121,7 +121,7 @@ StandardError=journal
WantedBy=multi-user.target WantedBy=multi-user.target
``` ```
Ative e inicie: Enable and start:
```bash ```bash
sudo systemctl daemon-reload sudo systemctl daemon-reload
@@ -131,25 +131,25 @@ sudo systemctl start psagentai
--- ---
## 5) Comandos úteis ## 5) Useful commands
```bash ```bash
# status # status
sudo systemctl status psagentai sudo systemctl status psagentai
# logs em tempo real # real-time logs
sudo journalctl -u psagentai -f sudo journalctl -u psagentai -f
# reiniciar após atualização # restart after update
sudo systemctl restart psagentai sudo systemctl restart psagentai
# parar # stop
sudo systemctl stop psagentai sudo systemctl stop psagentai
``` ```
--- ---
## 6) Atualizações futuras ## 6) Future updates
```bash ```bash
cd /opt/psagentai/app cd /opt/psagentai/app
@@ -160,70 +160,70 @@ sudo systemctl restart psagentai
--- ---
## 7) Múltiplos usuários / VPSs ## 7) Multiple users / VPSs
Cada instância do sistema é independente por chat ID do Telegram. Each system instance is independent by Telegram chat ID.
Para cada novo usuário/VPS: For each new user/VPS:
1. Crie o bot via @BotFather (`/newbot`) e pegue o token. 1. Create the bot via @BotFather (`/newbot`) and get the token.
2. Copie o projeto em um diretório separado, por exemplo `/opt/psagentai-user2`. 2. Copy the project to a separate directory, for example `/opt/psagentai-user2`.
3. Crie um `.env` próprio com `TELEGRAM_BOT_TOKEN`, `TELEGRAM_CHAT_ID` e suas chaves de IA. 3. Create your own `.env` with `TELEGRAM_BOT_TOKEN`, `TELEGRAM_CHAT_ID` and your AI keys.
4. Instale dependências com `./iniciar.sh`. 4. Install dependencies with `./iniciar.sh`.
5. Crie um serviço systemd separado, ex: `psagentai-user2.service`, apontando para esse diretório. 5. Create a separate systemd service, ex: `psagentai-user2.service`, pointing to that directory.
6. Habilite e inicie. 6. Enable and start.
Nomes recomendados para evitar conflito: Recommended names to avoid conflicts:
- `/opt/psagentai-user1/`, `/opt/psagentai-user2/` - `/opt/psagentai-user1/`, `/opt/psagentai-user2/`
- `psagentai-user1.service`, `psagentai-user2.service` - `psagentai-user1.service`, `psagentai-user2.service`
--- ---
## 8) Variáveis do `.env` ## 8) `.env` variables
| Variável | Obrigatória | Descrição | | Variable | Required | Description |
|---|---|---| |---|---|---|
| `AI_PROVIDER` | não | Provider preferencial: `openrouter`, `stepfun`, `qwencloud` ou `llamacpp` | | `AI_PROVIDER` | no | Preferred provider: `openrouter`, `stepfun`, `qwencloud` or `llamacpp` |
| `TELEGRAM_BOT_TOKEN` | sim | Token do bot do Telegram | | `TELEGRAM_BOT_TOKEN` | yes | Telegram bot token |
| `TELEGRAM_CHAT_ID` | sim | Chat ID do usuário | | `TELEGRAM_CHAT_ID` | yes | User chat ID |
| `DEFAULT_MODEL` | sim | Modelo de IA padrão | | `DEFAULT_MODEL` | yes | Default AI model |
| `OPENROUTER_API_KEY` | 1 das chaves | Chave OpenRouter | | `OPENROUTER_API_KEY` | 1 of the keys | OpenRouter key |
| `STEPFUN_API_KEY` | 1 das chaves | Chave StepFun | | `STEPFUN_API_KEY` | 1 of the keys | StepFun key |
| `QWENCLOUD_API_KEY` | 1 das chaves | Chave QwenCloud | | `QWENCLOUD_API_KEY` | 1 of the keys | QwenCloud key |
| `MIN_INTERVAL_MINUTES` | não | Intervalo mínimo para mensagens proativas | | `MIN_INTERVAL_MINUTES` | no | Minimum interval for proactive messages |
| `MAX_INTERVAL_MINUTES` | não | Intervalo máximo para mensagens proativas | | `MAX_INTERVAL_MINUTES` | no | Maximum interval for proactive messages |
| `MIN_MESSAGE_LINES` | não | Mínimo de linhas por mensagem do agente | | `MIN_MESSAGE_LINES` | no | Minimum lines per agent message |
| `AUTO_ENRICH_EVERY` | não | Enriquece perfil a cada N mensagens | | `AUTO_ENRICH_EVERY` | no | Enriches profile every N messages |
| `AUTO_IMPROVE_EVERY` | não | Melhoria automática a cada N mensagens | | `AUTO_IMPROVE_EVERY` | no | Auto improvement every N messages |
| `UPLOAD_CONTEXT_MAX_CHARS` | não | Limite de caracteres do upload enviado para a IA (`0` = sem limite) | | `UPLOAD_CONTEXT_MAX_CHARS` | no | Character limit of upload sent to AI (`0` = no limit) |
| `VISION_MODEL` | não | Modelo de IA para análise de imagens | | `VISION_MODEL` | no | AI model for image analysis |
| `VISION_PROVIDER` | não | Provider do modelo de visão (`openrouter`, `stepfun`, `qwencloud`) | | `VISION_PROVIDER` | no | Vision model provider (`openrouter`, `stepfun`, `qwencloud`) |
--- ---
## Comandos úteis via Telegram ## Useful commands via Telegram
- `/veria` — mostra o provider e o modelo de IA atuais - `/viewai` — shows current AI provider and model
- `/configia` — configura interativamente o provider e o modelo de IA - `/configai` — interactively configures AI provider and model
- `/veriavision` — mostra o provider e o modelo de visão atuais - `/viewvision` — shows current vision provider and model
- `/configiavision` — configura interativamente o modelo de visão - `/configvision` — interactively configures vision model
- `/about` — exibe informações do sistema, versão, autor e licença - `/about` — displays system information, version, author and license
--- ---
## 9) Backups importantes ## 9) Important backups
Faça backup regular dos arquivos de dados dentro de `/app`: Regularly backup the data files inside `/app`:
- `user_profile.json` - `user_profile.json`
- `agent_profile.json` - `agent_profile.json`
- `system_improvements.json` - `system_improvements.json`
- `uploads_metadata.json` - `uploads_metadata.json`
- pasta `contexts/` - `contexts/` folder
- pasta `workspace/` - `workspace/` folder
Exemplo simples de backup diário: Simple daily backup example:
```bash ```bash
tar czf /root/backups/psagentai-$(date +%F).tar.gz -C /opt/psagentai/app user_profile.json agent_profile.json system_improvements.json uploads_metadata.json contexts workspace tar czf /root/backups/psagentai-$(date +%F).tar.gz -C /opt/psagentai/app user_profile.json agent_profile.json system_improvements.json uploads_metadata.json contexts workspace
@@ -231,9 +231,9 @@ tar czf /root/backups/psagentai-$(date +%F).tar.gz -C /opt/psagentai/app user_pr
--- ---
## 10) Segurança ## 10) Security
- Nunca comite o `.env` no repositório. - Never commit `.env` to the repository.
- Restrinja permissões: `chmod 600 .env`. - Restrict permissions: `chmod 600 .env`.
- Use um usuário exclusivo para cada instância do serviço. - Use an exclusive user for each service instance.
- Para maior isolamento, execute cada instância em um container Docker separado ou em VMs distintas. - For greater isolation, run each instance in a separate Docker container or on distinct VMs.
+70 -70
View File
@@ -1,43 +1,43 @@
# PsAgentAI - Personal Agent AI Conversacional # PsAgentAI - Personal Conversational AI Agent
Sistema de Personal Agent AI Conversacional via Telegram que se comporta como uma companheira pessoal, conversando, cooperando e mantendo contexto contínuo com o usuário. Personal Conversational AI Agent system via Telegram that behaves as a personal companion, chatting, cooperating and maintaining continuous context with the user.
## Estrutura ## Structure
``` ```
app/ app/
├── psagentai_agent.py # Código principal do agente ├── psagentai_agent.py # Main agent code
├── iniciar.sh # Script de instalação e execução ├── iniciar.sh # Installation and execution script
├── requirements.txt # Dependências Python ├── requirements.txt # Python dependencies
├── .env # Configurações locais (não comitar) ├── .env # Local settings (do not commit)
├── .env.example # Exemplo de configuração ├── .env.example # Configuration example
├── user_profile.json # Perfil do usuário ├── user_profile.json # User profile
├── agent_profile.json # Perfil do agente (personalidade, traços, notas) ├── agent_profile.json # Agent profile (personality, traits, notes)
├── contexts/ # Históricos de conversa por data ├── contexts/ # Conversation history by date
│ └── YYYY-MM-DD.json │ └── YYYY-MM-DD.json
├── README.md ├── README.md
└── LICENSE └── LICENSE
``` ```
## Pré-requisitos ## Prerequisites
- Python 3.9+ - Python 3.9+
- Conta no Telegram com bot criado via @BotFather - Telegram account with bot created via @BotFather
- Pelo menos uma chave de API de IA suportada - At least one supported AI API key
## Configuração ## Configuration
1. Copie `.env.example` para `.env` e preencha: 1. Copy `.env.example` to `.env` and fill in:
- `TELEGRAM_BOT_TOKEN` — token do bot do Telegram - `TELEGRAM_BOT_TOKEN` — Telegram bot token
- `TELEGRAM_CHAT_ID` — seu chat ID no Telegram - `TELEGRAM_CHAT_ID` — your Telegram chat ID
- `OPENROUTER_API_KEY` ou outra chave de API compatível - `OPENROUTER_API_KEY` or other compatible API key
2. Ajuste intervalos se desejar: 2. Adjust intervals if desired:
- `MIN_INTERVAL_MINUTES` - `MIN_INTERVAL_MINUTES`
- `MAX_INTERVAL_MINUTES` - `MAX_INTERVAL_MINUTES`
- `MIN_MESSAGE_LINES` — define o número mínimo de linhas por mensagem do agente (padrão: `15`) - `MIN_MESSAGE_LINES` — defines the minimum number of lines per agent message (default: `15`)
## Instalação e execução ## Installation and execution
```bash ```bash
cd app cd app
@@ -45,71 +45,71 @@ chmod +x iniciar.sh
./iniciar.sh ./iniciar.sh
``` ```
O script cria o ambiente virtual, instala dependências e inicia o agente. The script creates the virtual environment, installs dependencies and starts the agent.
## Funcionalidades ## Features
- Onboarding inicial com perguntas para construir o perfil - Initial onboarding with questions to build the profile
- Histórico de conversa por dia em `contexts/` - Conversation history by day in `contexts/`
- Perfil do usuário persistido em `user_profile.json` - User profile persisted in `user_profile.json`
- Perfil do agente persistido em `agent_profile.json` (nome, personalidade, traços e notas) - Agent profile persisted in `agent_profile.json` (name, personality, traits and notes)
- Mensagens proativas em intervalos aleatórios configuráveis - Proactive messages at configurable random intervals
- Mínimo de linhas por mensagem do agente configurável via `.env` - Minimum lines per agent message configurable via `.env`
- Suporte a múltiplos provedores de IA: - Support for multiple AI providers:
- OpenRouter - OpenRouter
- StepFun - StepFun
- QwenCloud - QwenCloud
- llama.cpp (local) - llama.cpp (local)
- Atualização dinâmica do perfil via comandos naturais no chat - Dynamic profile update via natural commands in chat
## Comandos disponíveis ## Available commands
- `/start` — inicia ou reinicia a conversa - `/start` — starts or restarts the conversation
- `/ajuda` ou `/help` — exibe ajuda - `/help` — displays help
- `/perfil` — mostra perfil do usuário e do agente - `/profile` — shows user and agent profile summary
- `/agentprofile` — mostra apenas o perfil do agente - `/agentprofile` — shows only the agent profile
- `/reset` — reseta perfis do usuário e do agente - `/reset` — resets user and agent profiles
- `/limpar` — deleta todos os dados (perfis, contextos, chat_id) - `/clear` — deletes all data (profiles, contexts, chat_id)
- `/onboarding` — reinicia o onboarding - `/onboarding` — restarts onboarding
- `/newconfig` — reconfigura tudo do zero - `/newconfig` — reconfigures everything from scratch
- `/cancelar` — cancela operação em andamento - `/cancel` — cancels ongoing operation
- `/veria` — mostra o provider e o modelo de IA atuais - `/viewai` — shows current AI provider and model
- `/configia` — configura interativamente o provider e o modelo de IA com seleção por botões - `/configai` — interactively configures AI provider and model with button selection
- `/about` — exibe informações do sistema, versão, autor e licença - `/about` — displays system information, version, author and license
- `/veriavision` — mostra o provider e o modelo de visão atuais - `/viewvision` — shows current vision provider and model
- `/configiavision` — configura interativamente o modelo de visão com seleção por botões - `/configvision` — interactively configures vision model with button selection
- `/baixar <nome>` — baixa um arquivo do workspace pelo nome - `/download <name>` — downloads a workspace file by name
## Editando arquivos do workspace ## Editing workspace files
Você pode pedir para editar arquivos existentes no `workspace/` usando comandos como: You can ask to edit existing files in `workspace/` using commands like:
- `edite o arquivo teste.txt e adicione uma linha 4` - `edit the file test.txt and add line 4`
- `modifique o arquivo hello.py para imprimir hello world` - `modify the file hello.py to print hello world`
- `no arquivo teste.txt troque Linha 2 por Linha 2 editada` - `in the file test.txt replace Line 2 with Line 2 edited`
O Agent irá localizar o arquivo, aplicar a alteração solicitada e salvar o resultado. The Agent will locate the file, apply the requested change and save the result.
- `/incluirnomeuperfil <nome>` — atualiza seu nome no perfil - `/addtouserprofile <text>` — updates information in your profile
- `/incluirnoperfildoagent <texto>` — adiciona características ao perfil do agente - `/addtoagentprofile <text>` — adds characteristics to the agent profile
## Atualizando o perfil durante a conversa ## Updating profile during conversation
### Perfil do usuário ### User profile
Você pode atualizar seu perfil a qualquer momento usando frases como: You can update your profile at any time using phrases like:
- `Inclui isso no meu perfil: ...` - `Include this in my profile: ...`
- `Anote no meu perfil: ...` - `Note in my profile: ...`
- `Adicione no meu perfil: ...` - `Add to my profile: ...`
- `Salve no meu perfil: ...` - `Save in my profile: ...`
### Perfil do agente ### Agent profile
Use `/incluirnoperfildoagent <texto>` para adicionar características ao perfil do agente. Use `/addtoagentprofile <text>` to add characteristics to the agent profile.
Ou use frases como: Or use phrases like:
- `Inclui isso no perfil do agente: ...` - `Include this in the agent profile: ...`
- `Anote no perfil do agente: ...` - `Note in the agent profile: ...`
## Licença ## License
Uso proprietário. Veja o arquivo `LICENSE`. Proprietary use. See the `LICENSE` file.
+180 -180
View File
@@ -1,289 +1,289 @@
# PsAgentAI - Regras de Desenvolvimento # PsAgentAI - Development Rules
Regras oficiais para IAs e desenvolvedores codarem o sistema PsAgentAI de forma correta, padronizada e segura. Official rules for AIs and developers to code the PsAgentAI system correctly, standardized and securely.
--- ---
## 1. Visão Geral do Projeto ## 1. Project Overview
- **Nome:** PsAgentAI - **Name:** PsAgentAI
- **Tipo:** Bot Telegram de agente de IA conversacional - **Type:** Telegram bot for conversational AI agent
- **Linguagem:** Python 3.9+ - **Language:** Python 3.9+
- **Framework:** python-telegram-bot (v20+) - **Framework:** python-telegram-bot (v20+)
- **Arquivo principal:** `psagentai_agent.py` - **Main file:** `psagentai_agent.py`
- **Propósito:** Companheiro pessoal conversacional com memória, perfis, workspace de arquivos, análise de imagens, pesquisa web e automações. - **Purpose:** Personal conversational companion with memory, profiles, file workspace, image analysis, web search and automations.
### Regra básica ### Basic rule
Toda alteração deve preservar o comportamento existente a menos que o usuário solicite explicitamente uma mudança. Alterações estruturais devem ser validadas com `python3 -m py_compile psagentai_agent.py`. Every change must preserve existing behavior unless the user explicitly requests a change. Structural changes must be validated with `python3 -m py_compile psagentai_agent.py`.
--- ---
## 2. Padrões de Código ## 2. Code Standards
### 2.1 Estilo ### 2.1 Style
- Siga o estilo já estabelecido no `psagentai_agent.py`. - Follow the style already established in `psagentai_agent.py`.
- Use aspas duplas para strings curtas e mensagens; aspas simples apenas quando houver aspas duplas dentro. - Use double quotes for short strings and messages; single quotes only when there are double quotes inside.
- Indentação: 4 espaços. - Indentation: 4 spaces.
- Nomes de funções/arquivos: `snake_case`. - Function/file names: `snake_case`.
- Constantes globais em `UPPER_CASE`. - Global constants in `UPPER_CASE`.
- Comentários em português do Brasil quando necessário; evite comentários óbvios. - Comments in Brazilian Portuguese when necessary; avoid obvious comments.
- Mantenha logs `print("[LABEL] ...")` apenas onde já existirem; não adicione novos logs sem necessidade. - Keep `print("[LABEL] ...")` logs only where they already exist; do not add new logs without need.
### 2.2 Estrutura do arquivo principal ### 2.2 Main file structure
Mantenha a ordem lógica: Maintain the logical order:
1. Imports 1. Imports
2. Variáveis globais e constantes 2. Global variables and constants
3. Funções utilitárias 3. Utility functions
4. Funções de profile/context/workspace 4. Profile/context/workspace functions
5. Handlers de comandos 5. Command handlers
6. Handlers de mensagens/voz/foto/documento 6. Message/voice/photo/document handlers
7. `process_text_message` 7. `process_text_message`
8. Funções de criação/edição de arquivos 8. File creation/editing functions
9. Registro de handlers e `main()` 9. Handler registration and `main()`
Novos handlers devem ser adicionados próximos a funcionalidades similares já existentes. New handlers should be added close to similar existing functionalities.
### 2.3 Imports ### 2.3 Imports
- Agrupe imports padrão, de terceiros e locais. - Group standard, third-party and local imports.
- Não adicione dependências sem verificar se já existem no `requirements.txt`. - Do not add dependencies without checking if they already exist in `requirements.txt`.
- Se precisar de uma nova dependência, atualize `requirements.txt` e comunique. - If you need a new dependency, update `requirements.txt` and communicate.
--- ---
## 3. Convenções de Comandos e Handlers ## 3. Command and Handler Conventions
### 3.1 Nomenclatura ### 3.1 Naming
- Funções de comando: `<nome>_command` (ex: `help_command`, `manualdeuso_command`). - Command functions: `<name>_command` (ex: `help_command`, `manual_command`).
- Handler registration: `CommandHandler("nome", nome_command)`. - Handler registration: `CommandHandler("name", name_command)`.
- Nomes de comando em minúsculas, sem espaços, em português quando for comando voltado ao usuário final. - Command names in lowercase, without spaces, in Portuguese when it's a command for the end user.
### 3.2 Registro de handlers ### 3.2 Handler registration
- Sempre adicione o `CommandHandler` na seção apropriada de `setup_handlers()`. - Always add the `CommandHandler` in the appropriate section of `setup_handlers()`.
- Mantenha a ordem existente: primeiro comandos, depois callbacks, depois mensagens de mídia, depois `MessageHandler(filters.TEXT & ~filters.COMMAND, message_handler)`. - Maintain the existing order: first commands, then callbacks, then media messages, then `MessageHandler(filters.TEXT & ~filters.COMMAND, message_handler)`.
- Nunca registre handlers duplicados para o mesmo comando. - Never register duplicate handlers for the same command.
### 3.3 Comportamento de comandos ### 3.3 Command behavior
- Todos os handlers de comando devem chamar `await auto_detect_chat_id(update)` no início, exceto onde já houver tratamento explícito. - All command handlers must call `await auto_detect_chat_id(update)` at the beginning, except where there is already explicit handling.
- Respostas devem usar `await update.message.reply_text(...)` ou `await context.bot.send_message(...)` quando necessário. - Responses should use `await update.message.reply_text(...)` or `await context.bot.send_message(...)` when necessary.
- Use `ParseMode.HTML` apenas quando realmente precisar de formatação. - Use `ParseMode.HTML` only when formatting is really needed.
--- ---
## 4. Gerenciamento de Perfis ## 4. Profile Management
### 4.1 Arquivos ### 4.1 Files
- `user_profile.json` — perfil do usuário. - `user_profile.json` — user profile.
- `agent_profile.json` — perfil do agente. - `agent_profile.json` — agent profile.
- Nunca crie novos arquivos de perfil sem necessidade. - Never create new profile files without need.
### 4.2 Atualização de perfis ### 4.2 Profile updates
- Use as funções existentes: `load_user_profile()`, `save_user_profile()`, `load_agent_profile()`, `save_agent_profile()`. - Use the existing functions: `load_user_profile()`, `save_user_profile()`, `load_agent_profile()`, `save_agent_profile()`.
- Atualizações parciais devem mesclar com o conteúdo existente, não sobrescrever campos inteiros sem leitura prévia. - Partial updates must merge with existing content, not overwrite entire fields without prior reading.
- Triggers de atualização natural devem usar `handle_profile_update_if_triggered()` sempre que possível. - Natural update triggers must use `handle_profile_update_if_triggered()` whenever possible.
### 4.3 Onboarding ### 4.3 Onboarding
- Mantenha o fluxo de onboarding existente. - Maintain the existing onboarding flow.
- Novas perguntas de onboarding devem ser adicionadas ao dicionário `ONBOARDING_QUESTIONS` ou à lógica existente, não criando fluxos paralelos. - New onboarding questions must be added to the `ONBOARDING_QUESTIONS` dictionary or to the existing logic, not creating parallel flows.
--- ---
## 5. Contexto de Conversa ## 5. Conversation Context
### 5.1 Diretório ### 5.1 Directory
- Contextos são salvos em `contexts/YYYY-MM-DD.json`. - Contexts are saved in `contexts/YYYY-MM-DD.json`.
- Use `load_context()` e `add_to_context()` para manipular contexto. - Use `load_context()` and `add_to_context()` to manipulate context.
- Nunca acesse diretamente o arquivo de contexto sem usar as funções auxiliares. - Never access the context file directly without using the helper functions.
### 5.2 Limites ### 5.2 Limits
- Respeite os limites de tokens configurados no `.env`. - Respect the token limits configured in `.env`.
- Funções de limpeza de contexto devem usar `remove_old_messages()` ou equivalente, não reescrever o arquivo manualmente. - Context cleanup functions must use `remove_old_messages()` or equivalent, not manually rewrite the file.
--- ---
## 6. Workspace e Arquivos ## 6. Workspace and Files
### 6.1 Diretórios ### 6.1 Directories
- `workspace/` — armazena uploads, imagens e arquivos criados/editados. - `workspace/` — stores uploads, images and created/edited files.
- `workspace/projects/` — projetos criados pelo usuário. - `workspace/projects/` — projects created by the user.
- Nunca crie pastas adicionais dentro de `workspace/` sem necessidade explícita. - Never create additional folders inside `workspace/` without explicit need.
### 6.2 Funções obrigatórias ### 6.2 Mandatory functions
Use sempre as funções auxiliares existentes: Always use the existing helper functions:
- `ensure_workspace_dirs()` — cria diretórios necessários. - `ensure_workspace_dirs()` — creates necessary directories.
- `save_workspace_file(filename, content)` — salva arquivo no workspace. - `save_workspace_file(filename, content)` — saves file in workspace.
- `build_workspace_tree()` — gera árvore visual do workspace. - `build_workspace_tree()` — generates visual workspace tree.
- `_find_workspace_file(target)` — localiza arquivo por nome parcial. - `_find_workspace_file(target)` — locates file by partial name.
- `_looks_like_create_request()` / `_handle_create_request()` — cria arquivos via IA. - `_looks_like_create_request()` / `_handle_create_request()` — creates files via AI.
- `_looks_like_edit_request()` / `_handle_edit_request()` — edita arquivos via IA. - `_looks_like_edit_request()` / `_handle_edit_request()` — edits files via AI.
### 6.3 Metadados ### 6.3 Metadata
- Atualize `uploads_metadata.json` quando necessário. - Update `uploads_metadata.json` when necessary.
- Metadados devem conter: `original_name`, `filepath`, `chat_id`, `summary`, `full_text`, `type`. - Metadata must contain: `original_name`, `filepath`, `chat_id`, `summary`, `full_text`, `type`.
--- ---
## 7. Integração com IA ## 7. AI Integration
### 7.1 Providers suportados ### 7.1 Supported providers
- `openrouter` - `openrouter`
- `stepfun` - `stepfun`
- `qwencloud` - `qwencloud`
- `llamacpp` (local) - `llamacpp` (local)
### 7.2 Uso ### 7.2 Usage
- Sempre use `AIProvider.chat(model, messages, ...)` para chamadas de IA. - Always use `AIProvider.chat(model, messages, ...)` for AI calls.
- Não chame APIs diretamente; use a camada de abstração existente. - Do not call APIs directly; use the existing abstraction layer.
- Modelos padrão vêm do `.env`: `DEFAULT_MODEL`, `VISION_MODEL`, etc. - Default models come from `.env`: `DEFAULT_MODEL`, `VISION_MODEL`, etc.
- Novos modelos devem ser adicionados às listas em `psagentai_agent.py` quando houver suporte explícito. - New models must be added to the lists in `psagentai_agent.py` when there is explicit support.
### 7.3 Prompts ### 7.3 Prompts
- System prompt é gerado por `build_system_prompt()`. - System prompt is generated by `build_system_prompt()`.
- Não altere o system prompt sem necessidade; se alterar, preserve as seções de data/hora, perfil do usuário e perfil do agente. - Do not change the system prompt without need; if changing, preserve the date/time, user profile and agent profile sections.
- Para tarefas específicas (edição de arquivo, criação, análise), crie prompts separados e claros. - For specific tasks (file editing, creation, analysis), create separate and clear prompts.
--- ---
## 8. Pesquisa na Internet ## 8. Web Search
### 8.1 Funções ### 8.1 Functions
- `_web_search()` — executa busca no DuckDuckGo HTML. - `_web_search()` — executes search on DuckDuckGo HTML.
- `_looks_like_search_request()` — detecta intenção de busca. - `_looks_like_search_request()` — detects search intent.
- Triggers estão em `_WEB_SEARCH_TRIGGERS`. - Triggers are in `_WEB_SEARCH_TRIGGERS`.
### 8.2 Regras ### 8.2 Rules
- Não ative pesquisa web automaticamente para todo tipo de pergunta. - Do not activate web search automatically for every type of question.
- Respeite a diretriz `IMPORTANTE SOBRE INFORMAÇÕES ATUALIZADAS` no system prompt. - Respect the `IMPORTANTE SOBRE INFORMAÇÕES ATUALIZADAS` guideline in the system prompt.
- Limite de resultados vem do `.env` (`WEB_SEARCH_MAX_RESULTS`). - Results limit comes from `.env` (`WEB_SEARCH_MAX_RESULTS`).
--- ---
## 9. Análise de Imagens e Visão ## 9. Image Analysis and Vision
- Funções: `encode_image_to_base64()`, `analyze_image()`, `save_image_to_workspace()`. - Functions: `encode_image_to_base64()`, `analyze_image()`, `save_image_to_workspace()`.
- Comandos: `/veriavision`, `/configiavision`. - Commands: `/viewvision`, `/configvision`.
- Configuração via `.env`: `VISION_MODEL`, `VISION_PROVIDER`. - Configuration via `.env`: `VISION_MODEL`, `VISION_PROVIDER`.
- Imagens enviadas como documento preservam o nome original. - Images sent as document preserve the original name.
--- ---
## 10. Agendamento e Rotina ## 10. Scheduling and Routine
### 10.1 Arquivos ### 10.1 Files
- `config.json` — armazena agendamentos. - `config.json` — stores schedules.
- Não adicione campos obsoletos (ex: `timezone` foi removido; use horário do servidor). - Do not add obsolete fields (ex: `timezone` was removed; use server time).
### 10.2 Regras ### 10.2 Rules
- O Agent SEMPRE usa o horário do servidor (`datetime.now().astimezone()`). - The Agent ALWAYS uses server time (`datetime.now().astimezone()`).
- `/fusohorario` é apenas informativo, não permite alteração. - `/timezone` is only informative, does not allow changes.
- `get_timezone()` sempre retorna o timezone do servidor; `set_timezone()` retorna `False`. - `get_timezone()` always returns the server timezone; `set_timezone()` returns `False`.
--- ---
## 11. Segurança ## 11. Security
- Nunca commite `.env`, chaves de API, tokens ou dados sensíveis. - Never commit `.env`, API keys, tokens or sensitive data.
- Use variáveis de ambiente para segredos. - Use environment variables for secrets.
- Preserve emails e telefones em perfis e contextos sem expô-los em logs. - Preserve emails and phones in profiles and contexts without exposing them in logs.
- Valide caminhos de arquivo para evitar path traversal. - Validate file paths to avoid path traversal.
--- ---
## 12. Testes e Validação ## 12. Tests and Validation
### 12.1 Obrigatório ### 12.1 Mandatory
- Após alterações em `psagentai_agent.py`: `python3 -m py_compile psagentai_agent.py`. - After changes in `psagentai_agent.py`: `python3 -m py_compile psagentai_agent.py`.
- Teste cenários básicos com scripts Python inline quando possível. - Test basic scenarios with inline Python scripts when possible.
- Não quebre funcionalidades existentes (ex: criação/edição de arquivos, perfis, comandos). - Do not break existing functionalities (ex: file creation/editing, profiles, commands).
### 12.2 Testes manuais recomendados ### 12.2 Recommended manual tests
- `/start`, `/ajuda`, `/manualdeuso`, `/about` - `/start`, `/help`, `/manual`, `/about`
- Criação de arquivo: "crie um arquivo teste.txt com conteúdo X" - File creation: "create a test.txt file with content X"
- Edição de arquivo: "edite o arquivo teste.txt e adicione Y" - File editing: "edit the file test.txt and add Y"
- Envio de foto e análise - Photo sending and analysis
- Envio de voz e transcrição - Voice sending and transcription
- Pesquisa web: "pesquise sobre X" - Web search: "search about X"
- Configuração de IA: `/veria`, `/configia` - AI configuration: `/viewai`, `/configai`
--- ---
## 13. Documentação ## 13. Documentation
### 13.1 Arquivos obrigatórios ### 13.1 Mandatory files
- `README.md` — documentação principal, comandos, funcionalidades. - `README.md` — main documentation, commands, features.
- `DEPLOY.md` — guia de deploy em servidor. - `DEPLOY.md` — server deployment guide.
- `RULES.md` — este arquivo, regras de desenvolvimento. - `RULES.md` — this file, development rules.
- `LICENSE` — licença proprietária. - `LICENSE` — proprietary license.
### 13.2 Atualização ### 13.2 Update
- Sempre atualize `README.md` quando adicionar comandos ou funcionalidades. - Always update `README.md` when adding commands or features.
- Atualize `DEPLOY.md` se houver mudanças em variáveis de ambiente ou estrutura. - Update `DEPLOY.md` if there are changes in environment variables or structure.
- Este arquivo (`RULES.md`) deve ser atualizado quando novas regras forem definidas. - This file (`RULES.md`) must be updated when new rules are defined.
--- ---
## 14. Git e Workflow ## 14. Git and Workflow
### 14.1 Commits ### 14.1 Commits
- Mensagens curtas e descritivas em português ou inglês técnico. - Short and descriptive messages in Portuguese or technical English.
- Commits devem refletir uma mudança lógica por vez. - Commits must reflect one logical change at a time.
- Não faça commits automáticos sem revisão. - Do not make automatic commits without review.
### 14.2 Branches ### 14.2 Branches
- Trabalhe na branch principal ou crie branches para features específicas. - Work on the main branch or create branches for specific features.
- Não faça force push sem autorização. - Do not force push without authorization.
--- ---
## 15. Idioma e Comunicação ## 15. Language and Communication
- Interface do bot: português do Brasil. - Bot interface: Brazilian Portuguese.
- Respostas do Agent: português do Brasil. - Agent replies: Brazilian Portuguese.
- Logs e código: inglês técnico para nomes de variáveis/funções; português para mensagens ao usuário. - Logs and code: technical English for variable/function names; Portuguese for user-facing messages.
- Documentação: português do Brasil. - Documentation: Brazilian Portuguese.
--- ---
## 16. Regras Específicas do PsAgentAI ## 16. PsAgentAI Specific Rules
### 16.1 Nunca faça ### 16.1 Never do
- Remover funcionalidades existentes sem solicitação explícita. - Remove existing functionalities without explicit request.
- Alterar o `.env` sem aviso. - Change `.env` without notice.
- Modificar estrutura de pastas (`workspace/`, `contexts/`) sem necessidade. - Modify folder structure (`workspace/`, `contexts/`) without need.
- Introduzir dependências pesadas sem justificativa. - Introduce heavy dependencies without justification.
- Usar `input()` ou interações bloqueantes no código do bot. - Use `input()` or blocking interactions in the bot code.
### 16.2 Sempre faça ### 16.2 Always do
- Preserve compatibilidade com versões anteriores de perfis e contextos. - Preserve compatibility with previous versions of profiles and contexts.
- Trate erros de forma graceful (try/except com logs). - Handle errors gracefully (try/except with logs).
- Use `logger` para erros graves; use `print()` apenas para debug existente. - Use `logger` for serious errors; use `print()` only for existing debug.
- Valide entradas do usuário antes de processar. - Validate user inputs before processing.
- Forneça feedback ao usuário em caso de erro ("Erro ao processar. Tente novamente."). - Provide feedback to the user in case of error ("Error processing. Please try again.").
### 16.3 Integração de novas funcionalidades ### 16.3 Integration of new functionalities
1. Entenda o fluxo existente antes de adicionar código. 1. Understand the existing flow before adding code.
2. Crie funções pequenas e específicas. 2. Create small and specific functions.
3. Integre no ponto correto do `process_text_message` ou handlers. 3. Integrate at the correct point of `process_text_message` or handlers.
4. Registre handlers na ordem correta. 4. Register handlers in the correct order.
5. Atualize a documentação. 5. Update documentation.
6. Valide com `py_compile` e testes manuais. 6. Validate with `py_compile` and manual tests.
--- ---
## 17. Versionamento ## 17. Versioning
- Versão atual: `1.0.0` - Current version: `1.0.0`
- Incremente a versão em `__version__` quando houver mudanças relevantes. - Increment version in `__version__` when there are relevant changes.
- Atualize o `CHANGELOG` se existir; senão, documente no commit. - Update `CHANGELOG` if it exists; otherwise, document in the commit.
--- ---
## 18. Contato e Suporte ## 18. Contact and Support
- Sistema desenvolvido por: Syspanel.com.br - System developed by: Syspanel.com.br
- Autor: Marco A. S. Costa - Author: Marco A. S. Costa
- Email: contato@syspanel.com.br - Email: contato@syspanel.com.br
- Licença: Proprietária para syspanel.com.br - License: Proprietary for syspanel.com.br
--- ---
*Última atualização: Outubro 2026* *Last update: October 2026*
Binary file not shown.
+1044 -1078
View File
File diff suppressed because it is too large Load Diff