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
+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*