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