@grinev/opencode-telegram-bot 0.1.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +34 -0
- package/LICENSE +21 -0
- package/README.md +72 -0
- package/dist/agent/manager.js +92 -0
- package/dist/agent/types.js +26 -0
- package/dist/app/start-bot-app.js +26 -0
- package/dist/bot/commands/agent.js +16 -0
- package/dist/bot/commands/definitions.js +20 -0
- package/dist/bot/commands/help.js +7 -0
- package/dist/bot/commands/model.js +16 -0
- package/dist/bot/commands/models.js +37 -0
- package/dist/bot/commands/new.js +58 -0
- package/dist/bot/commands/opencode-start.js +87 -0
- package/dist/bot/commands/opencode-stop.js +46 -0
- package/dist/bot/commands/projects.js +104 -0
- package/dist/bot/commands/server-restart.js +23 -0
- package/dist/bot/commands/server-start.js +23 -0
- package/dist/bot/commands/sessions.js +240 -0
- package/dist/bot/commands/start.js +40 -0
- package/dist/bot/commands/status.js +63 -0
- package/dist/bot/commands/stop.js +92 -0
- package/dist/bot/handlers/agent.js +96 -0
- package/dist/bot/handlers/context.js +112 -0
- package/dist/bot/handlers/model.js +115 -0
- package/dist/bot/handlers/permission.js +158 -0
- package/dist/bot/handlers/question.js +294 -0
- package/dist/bot/handlers/variant.js +126 -0
- package/dist/bot/index.js +573 -0
- package/dist/bot/middleware/auth.js +30 -0
- package/dist/bot/utils/keyboard.js +66 -0
- package/dist/cli/args.js +97 -0
- package/dist/cli.js +90 -0
- package/dist/config.js +46 -0
- package/dist/index.js +26 -0
- package/dist/keyboard/manager.js +171 -0
- package/dist/keyboard/types.js +1 -0
- package/dist/model/manager.js +123 -0
- package/dist/model/types.js +26 -0
- package/dist/opencode/client.js +13 -0
- package/dist/opencode/events.js +79 -0
- package/dist/opencode/server.js +104 -0
- package/dist/permission/manager.js +78 -0
- package/dist/permission/types.js +1 -0
- package/dist/pinned/manager.js +610 -0
- package/dist/pinned/types.js +1 -0
- package/dist/pinned-message/service.js +54 -0
- package/dist/process/manager.js +273 -0
- package/dist/process/types.js +1 -0
- package/dist/project/manager.js +28 -0
- package/dist/question/manager.js +143 -0
- package/dist/question/types.js +1 -0
- package/dist/runtime/bootstrap.js +278 -0
- package/dist/runtime/mode.js +74 -0
- package/dist/runtime/paths.js +37 -0
- package/dist/session/manager.js +10 -0
- package/dist/session/state.js +24 -0
- package/dist/settings/manager.js +99 -0
- package/dist/status/formatter.js +44 -0
- package/dist/summary/aggregator.js +427 -0
- package/dist/summary/formatter.js +226 -0
- package/dist/utils/formatting.js +237 -0
- package/dist/utils/logger.js +59 -0
- package/dist/utils/safe-background-task.js +33 -0
- package/dist/variant/manager.js +103 -0
- package/dist/variant/types.js +1 -0
- package/package.json +63 -0
package/.env.example
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# Telegram Bot Token (from @BotFather)
|
|
2
|
+
TELEGRAM_BOT_TOKEN=
|
|
3
|
+
|
|
4
|
+
# Allowed Telegram User ID (fron @userinfobot)
|
|
5
|
+
TELEGRAM_ALLOWED_USER_ID=
|
|
6
|
+
|
|
7
|
+
# OpenCode API URL (optional, default: http://localhost:4096)
|
|
8
|
+
# OPENCODE_API_URL=http://localhost:4096
|
|
9
|
+
|
|
10
|
+
# OpenCode Server Authentication (optional)
|
|
11
|
+
# OPENCODE_SERVER_USERNAME=opencode
|
|
12
|
+
# OPENCODE_SERVER_PASSWORD=
|
|
13
|
+
|
|
14
|
+
# OpenCode Model Configuration (REQUIRED)
|
|
15
|
+
# You must specify a default model provider and model ID
|
|
16
|
+
# Examples:
|
|
17
|
+
# Anthropic Claude 3.5 Sonnet: OPENCODE_MODEL_PROVIDER=anthropic, OPENCODE_MODEL_ID=claude-3-5-sonnet-20241022
|
|
18
|
+
# OpenAI GPT-4 Turbo: OPENCODE_MODEL_PROVIDER=openai, OPENCODE_MODEL_ID=gpt-4-turbo
|
|
19
|
+
# Groq Mixtral: OPENCODE_MODEL_PROVIDER=groq, OPENCODE_MODEL_ID=mixtral-8x7b-32768
|
|
20
|
+
OPENCODE_MODEL_PROVIDER=opencode
|
|
21
|
+
OPENCODE_MODEL_ID=big-pickle
|
|
22
|
+
|
|
23
|
+
# Server Configuration (optional)
|
|
24
|
+
# Logging level: debug, info, warn, error (default: info)
|
|
25
|
+
# Use "debug" to see detailed diagnostic logs including all bot events
|
|
26
|
+
# LOG_LEVEL=info
|
|
27
|
+
|
|
28
|
+
# Bot Configuration (optional)
|
|
29
|
+
# Maximum number of sessions shown in /sessions (default: 10)
|
|
30
|
+
# SESSIONS_LIST_LIMIT=10
|
|
31
|
+
|
|
32
|
+
# Code File Settings (optional)
|
|
33
|
+
# Maximum file size in KB to send as document (default: 100)
|
|
34
|
+
# CODE_FILE_MAX_SIZE_KB=100
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ruslan Grinev
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# OpenCode Telegram Client
|
|
2
|
+
|
|
3
|
+
Мобильный клиент для OpenCode в Telegram, позволяющий управлять задачами разработки на локальном компьютере.
|
|
4
|
+
|
|
5
|
+
## Требования
|
|
6
|
+
|
|
7
|
+
- Node.js 20+
|
|
8
|
+
- Установленный OpenCode CLI (`opencode`)
|
|
9
|
+
|
|
10
|
+
## Установка
|
|
11
|
+
|
|
12
|
+
1. Клонируйте репозиторий.
|
|
13
|
+
2. Установите зависимости:
|
|
14
|
+
```bash
|
|
15
|
+
npm install
|
|
16
|
+
```
|
|
17
|
+
3. Скопируйте файл с переменными окружения:
|
|
18
|
+
```bash
|
|
19
|
+
cp .env.example .env
|
|
20
|
+
```
|
|
21
|
+
4. Заполните `.env` файл (токен бота, ваш ID и путь к проекту).
|
|
22
|
+
5. Настройте избранные модели в OpenCode (Desktop/TUI). Бот автоматически читает их из локального state файла OpenCode (`model.json`).
|
|
23
|
+
6. Если избранные модели недоступны или файл не читается, бот использует fallback из `.env`:
|
|
24
|
+
- `OPENCODE_MODEL_PROVIDER`
|
|
25
|
+
- `OPENCODE_MODEL_ID`
|
|
26
|
+
|
|
27
|
+
## Переменные окружения
|
|
28
|
+
|
|
29
|
+
Основные переменные в `.env`:
|
|
30
|
+
|
|
31
|
+
- `TELEGRAM_BOT_TOKEN` — токен бота (обязательно).
|
|
32
|
+
- `TELEGRAM_ALLOWED_USER_ID` — ваш Telegram user ID (обязательно).
|
|
33
|
+
- `OPENCODE_MODEL_PROVIDER` — провайдер модели по умолчанию (обязательно).
|
|
34
|
+
- `OPENCODE_MODEL_ID` — ID модели по умолчанию (обязательно).
|
|
35
|
+
- `SESSIONS_LIST_LIMIT` — сколько последних сессий показывать в `/sessions` (опционально, по умолчанию `10`).
|
|
36
|
+
|
|
37
|
+
## Сборка и запуск
|
|
38
|
+
|
|
39
|
+
### Режим разработки
|
|
40
|
+
|
|
41
|
+
Запуск без автоматической перезагрузки процесса:
|
|
42
|
+
|
|
43
|
+
> В этом проекте auto-restart (watch/restart) намеренно не используется для runtime-бота,
|
|
44
|
+
> чтобы не ломать активные SSE/polling соединения.
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
npm run dev
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### Продакшн
|
|
51
|
+
|
|
52
|
+
1. Соберите проект:
|
|
53
|
+
```bash
|
|
54
|
+
npm run build
|
|
55
|
+
```
|
|
56
|
+
2. Запустите собранный код:
|
|
57
|
+
```bash
|
|
58
|
+
npm start
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Команды
|
|
62
|
+
|
|
63
|
+
- `npm run lint` — проверка кода линтером.
|
|
64
|
+
- `npm run format` — форматирование кода через Prettier.
|
|
65
|
+
- `npm run test` — запуск тестов через Vitest.
|
|
66
|
+
- `npm run test:coverage` — запуск тестов с coverage-отчётом.
|
|
67
|
+
|
|
68
|
+
## Функционал
|
|
69
|
+
|
|
70
|
+
Подробное описание функционала и плана разработки находится в [PRODUCT.md](./PRODUCT.md).
|
|
71
|
+
План технических улучшений (архитектура + тесты) — в [TECHNICAL_IMPROVEMENTS.md](./TECHNICAL_IMPROVEMENTS.md).
|
|
72
|
+
Инструкции для разработчиков и описание архитектуры — в [AGENTS.md](./AGENTS.md).
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { opencodeClient } from "../opencode/client.js";
|
|
2
|
+
import { getCurrentProject } from "../settings/manager.js";
|
|
3
|
+
import { getCurrentSession } from "../session/manager.js";
|
|
4
|
+
import { getCurrentAgent, setCurrentAgent } from "../settings/manager.js";
|
|
5
|
+
import { logger } from "../utils/logger.js";
|
|
6
|
+
/**
|
|
7
|
+
* Get list of available agents from OpenCode API
|
|
8
|
+
* @returns Array of available agents (filtered by mode and hidden flag)
|
|
9
|
+
*/
|
|
10
|
+
export async function getAvailableAgents() {
|
|
11
|
+
const project = getCurrentProject();
|
|
12
|
+
if (!project) {
|
|
13
|
+
logger.warn("[AgentManager] Cannot get agents: no project selected");
|
|
14
|
+
return [];
|
|
15
|
+
}
|
|
16
|
+
try {
|
|
17
|
+
const { data: agents, error } = await opencodeClient.app.agents({
|
|
18
|
+
directory: project.worktree,
|
|
19
|
+
});
|
|
20
|
+
if (error) {
|
|
21
|
+
logger.error("[AgentManager] Failed to fetch agents:", error);
|
|
22
|
+
return [];
|
|
23
|
+
}
|
|
24
|
+
if (!agents) {
|
|
25
|
+
return [];
|
|
26
|
+
}
|
|
27
|
+
// Filter out hidden agents and subagents (only show primary and all)
|
|
28
|
+
const filtered = agents.filter((agent) => !agent.hidden && (agent.mode === "primary" || agent.mode === "all"));
|
|
29
|
+
logger.debug(`[AgentManager] Fetched ${filtered.length} available agents`);
|
|
30
|
+
return filtered;
|
|
31
|
+
}
|
|
32
|
+
catch (err) {
|
|
33
|
+
logger.error("[AgentManager] Error fetching agents:", err);
|
|
34
|
+
return [];
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Get current agent from last session message or settings
|
|
39
|
+
* @returns Current agent name or undefined
|
|
40
|
+
*/
|
|
41
|
+
export async function fetchCurrentAgent() {
|
|
42
|
+
const storedAgent = getCurrentAgent();
|
|
43
|
+
const session = getCurrentSession();
|
|
44
|
+
const project = getCurrentProject();
|
|
45
|
+
if (!session || !project) {
|
|
46
|
+
// No active session, return stored agent from settings
|
|
47
|
+
return storedAgent;
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
const { data: messages, error } = await opencodeClient.session.messages({
|
|
51
|
+
sessionID: session.id,
|
|
52
|
+
directory: project.worktree,
|
|
53
|
+
limit: 1,
|
|
54
|
+
});
|
|
55
|
+
if (error || !messages || messages.length === 0) {
|
|
56
|
+
logger.debug("[AgentManager] No messages found, using stored agent");
|
|
57
|
+
return storedAgent;
|
|
58
|
+
}
|
|
59
|
+
const lastAgent = messages[0].info.agent;
|
|
60
|
+
logger.debug(`[AgentManager] Current agent from session: ${lastAgent}`);
|
|
61
|
+
// If user explicitly selected an agent in bot settings, prefer it.
|
|
62
|
+
// Session messages may contain stale agent until next prompt is sent.
|
|
63
|
+
if (storedAgent && lastAgent !== storedAgent) {
|
|
64
|
+
logger.debug(`[AgentManager] Using stored agent "${storedAgent}" instead of session agent "${lastAgent}"`);
|
|
65
|
+
return storedAgent;
|
|
66
|
+
}
|
|
67
|
+
// No stored agent yet: sync from session history
|
|
68
|
+
if (lastAgent && lastAgent !== storedAgent) {
|
|
69
|
+
setCurrentAgent(lastAgent);
|
|
70
|
+
}
|
|
71
|
+
return lastAgent || storedAgent;
|
|
72
|
+
}
|
|
73
|
+
catch (err) {
|
|
74
|
+
logger.error("[AgentManager] Error fetching current agent:", err);
|
|
75
|
+
return storedAgent;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Select agent and persist to settings
|
|
80
|
+
* @param agentName Name of the agent to select
|
|
81
|
+
*/
|
|
82
|
+
export function selectAgent(agentName) {
|
|
83
|
+
logger.info(`[AgentManager] Selected agent: ${agentName}`);
|
|
84
|
+
setCurrentAgent(agentName);
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Get stored agent from settings (synchronous)
|
|
88
|
+
* @returns Current agent name or default "build"
|
|
89
|
+
*/
|
|
90
|
+
export function getStoredAgent() {
|
|
91
|
+
return getCurrentAgent() ?? "build";
|
|
92
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent emoji mapping for visual distinction
|
|
3
|
+
*/
|
|
4
|
+
export const AGENT_EMOJI = {
|
|
5
|
+
plan: "📋",
|
|
6
|
+
build: "🛠️",
|
|
7
|
+
general: "💬",
|
|
8
|
+
explore: "🔍",
|
|
9
|
+
title: "📝",
|
|
10
|
+
summary: "📄",
|
|
11
|
+
compaction: "📦",
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Get emoji for agent (fallback to 🤖 if not found)
|
|
15
|
+
*/
|
|
16
|
+
export function getAgentEmoji(agentName) {
|
|
17
|
+
return AGENT_EMOJI[agentName] ?? "🤖";
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Get display name for agent (with emoji)
|
|
21
|
+
*/
|
|
22
|
+
export function getAgentDisplayName(agentName) {
|
|
23
|
+
const emoji = getAgentEmoji(agentName);
|
|
24
|
+
const capitalizedName = agentName.charAt(0).toUpperCase() + agentName.slice(1);
|
|
25
|
+
return `${emoji} ${capitalizedName} Mode`;
|
|
26
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { createBot } from "../bot/index.js";
|
|
2
|
+
import { config } from "../config.js";
|
|
3
|
+
import { loadSettings } from "../settings/manager.js";
|
|
4
|
+
import { processManager } from "../process/manager.js";
|
|
5
|
+
import { getRuntimeMode } from "../runtime/mode.js";
|
|
6
|
+
import { logger } from "../utils/logger.js";
|
|
7
|
+
export async function startBotApp() {
|
|
8
|
+
const mode = getRuntimeMode();
|
|
9
|
+
logger.info("Starting OpenCode Telegram Client...");
|
|
10
|
+
logger.info(`Allowed User ID: ${config.telegram.allowedUserId}`);
|
|
11
|
+
logger.debug(`[Runtime] Application start mode: ${mode}`);
|
|
12
|
+
await loadSettings();
|
|
13
|
+
await processManager.initialize();
|
|
14
|
+
const bot = createBot();
|
|
15
|
+
const webhookInfo = await bot.api.getWebhookInfo();
|
|
16
|
+
if (webhookInfo.url) {
|
|
17
|
+
logger.info(`[Bot] Webhook detected: ${webhookInfo.url}, removing...`);
|
|
18
|
+
await bot.api.deleteWebhook();
|
|
19
|
+
logger.info("[Bot] Webhook removed, switching to long polling");
|
|
20
|
+
}
|
|
21
|
+
await bot.start({
|
|
22
|
+
onStart: (botInfo) => {
|
|
23
|
+
logger.info(`Bot @${botInfo.username} started!`);
|
|
24
|
+
},
|
|
25
|
+
});
|
|
26
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { showAgentSelectionMenu } from "../handlers/agent.js";
|
|
2
|
+
import { logger } from "../../utils/logger.js";
|
|
3
|
+
/**
|
|
4
|
+
* Handler for /agent command
|
|
5
|
+
* Shows inline menu to select agent mode
|
|
6
|
+
*/
|
|
7
|
+
export async function handleAgentCommand(ctx) {
|
|
8
|
+
logger.debug("[AgentCommand] /agent command received");
|
|
9
|
+
try {
|
|
10
|
+
await showAgentSelectionMenu(ctx);
|
|
11
|
+
}
|
|
12
|
+
catch (err) {
|
|
13
|
+
logger.error("[AgentCommand] Error showing agent menu:", err);
|
|
14
|
+
await ctx.reply("❌ Ошибка при загрузке списка агентов");
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Centralized bot commands definitions
|
|
3
|
+
* Used for both Telegram API setMyCommands and command handler registration
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* List of all bot commands
|
|
7
|
+
* Update this array when adding new commands
|
|
8
|
+
*/
|
|
9
|
+
export const BOT_COMMANDS = [
|
|
10
|
+
{ command: "status", description: "Статус сервера и сессии" },
|
|
11
|
+
{ command: "new", description: "Создать новую сессию" },
|
|
12
|
+
{ command: "stop", description: "Прервать текущее действие" },
|
|
13
|
+
{ command: "sessions", description: "Список сессий" },
|
|
14
|
+
{ command: "projects", description: "Список проектов" },
|
|
15
|
+
{ command: "model", description: "Выбрать модель" },
|
|
16
|
+
{ command: "agent", description: "Выбрать режим работы" },
|
|
17
|
+
{ command: "opencode_start", description: "Запустить OpenCode сервер" },
|
|
18
|
+
{ command: "opencode_stop", description: "Остановить OpenCode сервер" },
|
|
19
|
+
{ command: "help", description: "Справка" },
|
|
20
|
+
];
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { showModelSelectionMenu } from "../handlers/model.js";
|
|
2
|
+
import { logger } from "../../utils/logger.js";
|
|
3
|
+
/**
|
|
4
|
+
* Handler for /model command
|
|
5
|
+
* Shows inline menu to select model from favorites
|
|
6
|
+
*/
|
|
7
|
+
export async function handleModelCommand(ctx) {
|
|
8
|
+
logger.debug("[ModelCommand] /model command received");
|
|
9
|
+
try {
|
|
10
|
+
await showModelSelectionMenu(ctx);
|
|
11
|
+
}
|
|
12
|
+
catch (err) {
|
|
13
|
+
logger.error("[ModelCommand] Error showing model menu:", err);
|
|
14
|
+
await ctx.reply("❌ Ошибка при загрузке списка моделей");
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { opencodeClient } from "../../opencode/client.js";
|
|
2
|
+
import { logger } from "../../utils/logger.js";
|
|
3
|
+
export async function modelsCommand(ctx) {
|
|
4
|
+
try {
|
|
5
|
+
const { data: providersData, error } = await opencodeClient.config.providers();
|
|
6
|
+
if (error || !providersData) {
|
|
7
|
+
await ctx.reply("🔴 Не удалось получить список моделей. Проверьте статус сервера /status.");
|
|
8
|
+
return;
|
|
9
|
+
}
|
|
10
|
+
const providers = providersData.providers;
|
|
11
|
+
if (!providers || providers.length === 0) {
|
|
12
|
+
await ctx.reply("📋 Нет доступных моделей. Настройте провайдеры через OpenCode.");
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
let message = "📋 **Доступные модели:**\n\n";
|
|
16
|
+
for (const provider of providers) {
|
|
17
|
+
message += `🔹 **\`${provider.id}\`**\n`;
|
|
18
|
+
const models = Object.values(provider.models);
|
|
19
|
+
if (models.length === 0) {
|
|
20
|
+
message += " ⚠️ Нет доступных моделей\n";
|
|
21
|
+
}
|
|
22
|
+
else {
|
|
23
|
+
for (const model of models) {
|
|
24
|
+
message += ` • \`${model.id}\`\n`;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
message += "\n";
|
|
28
|
+
}
|
|
29
|
+
message += "💡 Для использования модели в .env:\n";
|
|
30
|
+
message += "```\nOPENCODE_MODEL_PROVIDER=<provider.id>\nOPENCODE_MODEL_ID=<model.id>\n```";
|
|
31
|
+
await ctx.reply(message, { parse_mode: "Markdown" });
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
logger.error("[ModelsCommand] Error listing models:", error);
|
|
35
|
+
await ctx.reply("🔴 Произошла ошибка при получении списка моделей.");
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { opencodeClient } from "../../opencode/client.js";
|
|
2
|
+
import { setCurrentSession } from "../../session/manager.js";
|
|
3
|
+
import { getCurrentProject } from "../../settings/manager.js";
|
|
4
|
+
import { pinnedMessageManager } from "../../pinned/manager.js";
|
|
5
|
+
import { keyboardManager } from "../../keyboard/manager.js";
|
|
6
|
+
import { getStoredAgent } from "../../agent/manager.js";
|
|
7
|
+
import { getStoredModel } from "../../model/manager.js";
|
|
8
|
+
import { formatVariantForButton } from "../../variant/manager.js";
|
|
9
|
+
import { createMainKeyboard } from "../utils/keyboard.js";
|
|
10
|
+
import { logger } from "../../utils/logger.js";
|
|
11
|
+
export async function newCommand(ctx) {
|
|
12
|
+
try {
|
|
13
|
+
const currentProject = getCurrentProject();
|
|
14
|
+
if (!currentProject) {
|
|
15
|
+
await ctx.reply("🏗 Проект не выбран.\n\nСначала выберите проект командой /projects.");
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
logger.debug("[Bot] Creating new session for directory:", currentProject.worktree);
|
|
19
|
+
const { data: session, error } = await opencodeClient.session.create({
|
|
20
|
+
directory: currentProject.worktree,
|
|
21
|
+
});
|
|
22
|
+
if (error || !session) {
|
|
23
|
+
throw error || new Error("No data received from server");
|
|
24
|
+
}
|
|
25
|
+
logger.info(`[Bot] Created new session via /new command: id=${session.id}, title="${session.title}", project=${currentProject.worktree}`);
|
|
26
|
+
const sessionInfo = {
|
|
27
|
+
id: session.id,
|
|
28
|
+
title: session.title,
|
|
29
|
+
directory: currentProject.worktree,
|
|
30
|
+
};
|
|
31
|
+
setCurrentSession(sessionInfo);
|
|
32
|
+
// Initialize pinned message manager and create pinned message
|
|
33
|
+
if (!pinnedMessageManager.isInitialized()) {
|
|
34
|
+
pinnedMessageManager.initialize(ctx.api, ctx.chat.id);
|
|
35
|
+
}
|
|
36
|
+
// Initialize keyboard manager if not already
|
|
37
|
+
keyboardManager.initialize(ctx.api, ctx.chat.id);
|
|
38
|
+
try {
|
|
39
|
+
await pinnedMessageManager.onSessionChange(session.id, session.title);
|
|
40
|
+
}
|
|
41
|
+
catch (err) {
|
|
42
|
+
logger.error("[Bot] Error creating pinned message:", err);
|
|
43
|
+
}
|
|
44
|
+
// Get current state for keyboard
|
|
45
|
+
const currentAgent = getStoredAgent();
|
|
46
|
+
const currentModel = getStoredModel();
|
|
47
|
+
const contextInfo = pinnedMessageManager.getContextInfo();
|
|
48
|
+
const variantName = formatVariantForButton(currentModel.variant || "default");
|
|
49
|
+
const keyboard = createMainKeyboard(currentAgent, currentModel, contextInfo ?? undefined, variantName);
|
|
50
|
+
await ctx.reply(`✅ Создана новая сессия: ${session.title}`, {
|
|
51
|
+
reply_markup: keyboard,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
logger.error("[Bot] Error creating session:", error);
|
|
56
|
+
await ctx.reply("🔴 OpenCode Server недоступен или произошла ошибка при создании сессии.");
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { opencodeClient } from "../../opencode/client.js";
|
|
2
|
+
import { processManager } from "../../process/manager.js";
|
|
3
|
+
import { logger } from "../../utils/logger.js";
|
|
4
|
+
/**
|
|
5
|
+
* Wait for OpenCode server to become ready by polling health endpoint
|
|
6
|
+
* @param maxWaitMs Maximum time to wait in milliseconds
|
|
7
|
+
* @returns true if server became ready, false if timeout
|
|
8
|
+
*/
|
|
9
|
+
async function waitForServerReady(maxWaitMs = 10000) {
|
|
10
|
+
const startTime = Date.now();
|
|
11
|
+
const pollInterval = 500;
|
|
12
|
+
while (Date.now() - startTime < maxWaitMs) {
|
|
13
|
+
try {
|
|
14
|
+
const { data, error } = await opencodeClient.global.health();
|
|
15
|
+
if (!error && data?.healthy) {
|
|
16
|
+
return true;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
// Server not ready yet
|
|
21
|
+
}
|
|
22
|
+
await new Promise((resolve) => setTimeout(resolve, pollInterval));
|
|
23
|
+
}
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Command handler for /opencode-start
|
|
28
|
+
* Starts the OpenCode server process
|
|
29
|
+
*/
|
|
30
|
+
export async function opencodeStartCommand(ctx) {
|
|
31
|
+
try {
|
|
32
|
+
// 1. Check if process is already running under our management
|
|
33
|
+
if (processManager.isRunning()) {
|
|
34
|
+
const uptime = processManager.getUptime();
|
|
35
|
+
const uptimeStr = uptime ? Math.floor(uptime / 1000) : 0;
|
|
36
|
+
await ctx.reply(`⚠️ OpenCode Server уже запущен\n\n` +
|
|
37
|
+
`PID: ${processManager.getPID()}\n` +
|
|
38
|
+
`Uptime: ${uptimeStr} секунд`);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
// 2. Check if server is accessible (external process)
|
|
42
|
+
try {
|
|
43
|
+
const { data, error } = await opencodeClient.global.health();
|
|
44
|
+
if (!error && data?.healthy) {
|
|
45
|
+
await ctx.reply(`✅ OpenCode Server уже запущен внешним процессом\n\n` +
|
|
46
|
+
`Версия: ${data.version || "неизвестна"}\n\n` +
|
|
47
|
+
`Этот сервер не был запущен через бота, поэтому команда /opencode-stop не сможет его остановить.`);
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
// Server not accessible, continue with start
|
|
53
|
+
}
|
|
54
|
+
// 3. Notify user that we're starting the server
|
|
55
|
+
const statusMessage = await ctx.reply("🔄 Запускаю OpenCode Server...");
|
|
56
|
+
// 4. Start the process
|
|
57
|
+
const { success, error } = await processManager.start();
|
|
58
|
+
if (!success) {
|
|
59
|
+
await ctx.api.editMessageText(ctx.chat.id, statusMessage.message_id, `🔴 Не удалось запустить OpenCode Server\n\n` +
|
|
60
|
+
`Ошибка: ${error || "неизвестная ошибка"}\n\n` +
|
|
61
|
+
`Проверьте, что OpenCode CLI установлен и доступен в PATH:\n` +
|
|
62
|
+
`\`opencode --version\`\n` +
|
|
63
|
+
`\`npm install -g @opencode-ai/cli\``, { parse_mode: "Markdown" });
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
// 5. Wait for server to become ready
|
|
67
|
+
logger.info("[Bot] Waiting for OpenCode server to become ready...");
|
|
68
|
+
const ready = await waitForServerReady(10000);
|
|
69
|
+
if (!ready) {
|
|
70
|
+
await ctx.api.editMessageText(ctx.chat.id, statusMessage.message_id, `⚠️ OpenCode Server запущен, но не отвечает\n\n` +
|
|
71
|
+
`PID: ${processManager.getPID()}\n\n` +
|
|
72
|
+
`Сервер может запускаться. Попробуйте /status через несколько секунд.`);
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
// 6. Get server version and send success message
|
|
76
|
+
const { data: health } = await opencodeClient.global.health();
|
|
77
|
+
await ctx.api.editMessageText(ctx.chat.id, statusMessage.message_id, `✅ OpenCode Server успешно запущен\n\n` +
|
|
78
|
+
`PID: ${processManager.getPID()}\n` +
|
|
79
|
+
`Версия: ${health?.version || "неизвестна"}`);
|
|
80
|
+
logger.info(`[Bot] OpenCode server started successfully, PID=${processManager.getPID()}`);
|
|
81
|
+
}
|
|
82
|
+
catch (err) {
|
|
83
|
+
logger.error("[Bot] Error in /opencode-start command:", err);
|
|
84
|
+
await ctx.reply("🔴 Произошла ошибка при запуске сервера.\n\n" +
|
|
85
|
+
"Проверьте логи приложения для подробностей.");
|
|
86
|
+
}
|
|
87
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { opencodeClient } from "../../opencode/client.js";
|
|
2
|
+
import { processManager } from "../../process/manager.js";
|
|
3
|
+
import { logger } from "../../utils/logger.js";
|
|
4
|
+
/**
|
|
5
|
+
* Command handler for /opencode-stop
|
|
6
|
+
* Stops the OpenCode server process
|
|
7
|
+
*/
|
|
8
|
+
export async function opencodeStopCommand(ctx) {
|
|
9
|
+
try {
|
|
10
|
+
// 1. Check if process is running under our management
|
|
11
|
+
if (!processManager.isRunning()) {
|
|
12
|
+
// Check if there's an external server running
|
|
13
|
+
try {
|
|
14
|
+
const { data, error } = await opencodeClient.global.health();
|
|
15
|
+
if (!error && data?.healthy) {
|
|
16
|
+
await ctx.reply(`⚠️ OpenCode Server запущен внешним процессом\n\n` +
|
|
17
|
+
`Этот сервер не был запущен через /opencode-start.\n` +
|
|
18
|
+
`Остановите его вручную или используйте /status для проверки состояния.`);
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
// Server not accessible
|
|
24
|
+
}
|
|
25
|
+
await ctx.reply("⚠️ OpenCode Server не запущен");
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
// 2. Notify user that we're stopping the server
|
|
29
|
+
const pid = processManager.getPID();
|
|
30
|
+
const statusMessage = await ctx.reply(`🛑 Останавливаю OpenCode Server...\n\nPID: ${pid}`);
|
|
31
|
+
// 3. Stop the process
|
|
32
|
+
const { success, error } = await processManager.stop(5000);
|
|
33
|
+
if (!success) {
|
|
34
|
+
await ctx.api.editMessageText(ctx.chat.id, statusMessage.message_id, `🔴 Не удалось остановить OpenCode Server\n\n` + `Ошибка: ${error || "неизвестная ошибка"}`);
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
// 4. Success - process has been stopped
|
|
38
|
+
await ctx.api.editMessageText(ctx.chat.id, statusMessage.message_id, `✅ OpenCode Server успешно остановлен`);
|
|
39
|
+
logger.info("[Bot] OpenCode server stopped successfully");
|
|
40
|
+
}
|
|
41
|
+
catch (err) {
|
|
42
|
+
logger.error("[Bot] Error in /opencode-stop command:", err);
|
|
43
|
+
await ctx.reply("🔴 Произошла ошибка при остановке сервера.\n\n" +
|
|
44
|
+
"Проверьте логи приложения для подробностей.");
|
|
45
|
+
}
|
|
46
|
+
}
|