@bazilio-san/codex-notify 1.0.6

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/LICENSE ADDED
@@ -0,0 +1,16 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 codex-notify contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
6
+ documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
7
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
8
+ persons to whom the Software is furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
11
+ Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
14
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
15
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,90 @@
1
+ # codex-notify
2
+
3
+ `codex-notify` отправляет сообщение в Telegram, когда Codex завершает очередной ход. Отдельный фоновый процесс не
4
+ используется: Codex сам запускает уведомитель через пользовательский параметр `notify`.
5
+
6
+ Уведомление содержит название проекта, запрос пользователя и последний ответ Codex. Старые сообщения, отправленные
7
+ ботом, по умолчанию удаляются через 24 часа.
8
+
9
+ ## Требования
10
+
11
+ - Node.js 18 или новее.
12
+ - Установленный Codex CLI.
13
+ - Telegram-бот, созданный через [@BotFather](https://t.me/BotFather).
14
+
15
+ ## Установка
16
+
17
+ Сначала отправьте своему новому Telegram-боту любое сообщение. Затем установите пакет и запустите мастер настройки:
18
+
19
+ ```bash
20
+ npm install -g @bazilio-san/codex-notify
21
+ codex-notify install
22
+ ```
23
+
24
+ Установщик сохранит Telegram-настройки в `~/.codex/codex-notify.config.json`, добавит команду в пользовательский
25
+ `~/.codex/config.toml` и отправит пробное сообщение. Если Codex уже открыт, после установки его следует перезапустить.
26
+
27
+ Проверить доставку отдельно можно командой:
28
+
29
+ ```bash
30
+ codex-notify test
31
+ ```
32
+
33
+ ## Настройка
34
+
35
+ Файл `~/.codex/codex-notify.config.json` имеет следующий формат:
36
+
37
+ ```json
38
+ {
39
+ "telegram": {
40
+ "enabled": true,
41
+ "token": "123456789:ABC...",
42
+ "chatId": "123456789",
43
+ "deleteAfterHours": 24,
44
+ "includeLastMessage": true
45
+ },
46
+ "debug": false
47
+ }
48
+ ```
49
+
50
+ Переменные окружения имеют приоритет над файлом настроек:
51
+
52
+ - `CODEX_NOTIFY_TELEGRAM_TOKEN` задаёт токен бота.
53
+ - `CODEX_NOTIFY_TELEGRAM_CHAT_ID` задаёт идентификатор личного чата или группы.
54
+ - `CODEX_NOTIFY_TELEGRAM=0` временно отключает отправку сообщений.
55
+ - `CODEX_NOTIFY_INCLUDE_LAST_MESSAGE=0` скрывает последний ответ Codex.
56
+ - `CODEX_NOTIFY_DEBUG=1` добавляет идентификатор диалога и выводит диагностические сообщения.
57
+
58
+ Значение `deleteAfterHours: 0` отключает автоматическое удаление старых сообщений.
59
+
60
+ ## Удаление
61
+
62
+ ```bash
63
+ codex-notify uninstall
64
+ npm uninstall -g codex-notify
65
+ ```
66
+
67
+ Первая команда удаляет только созданную пакетом строку `notify` из конфигурации Codex. Telegram-настройки сохраняются,
68
+ чтобы повторная установка не требовала вводить их заново.
69
+
70
+ ## Ограничения Codex
71
+
72
+ Внешний параметр `notify` сейчас вызывается для события `agent-turn-complete`, то есть после завершения хода агента.
73
+ Запрос разрешения или ожидание дополнительного ответа обрабатываются встроенными уведомлениями интерфейса Codex и не
74
+ передаются этому уведомителю.
75
+
76
+ ## Лицензия
77
+
78
+ MIT
79
+
80
+ ## Публикация
81
+
82
+ Выпуск выполняется из чистой ветки `master`. Сценарий повышает номер исправления, запускает проверки, создаёт
83
+ коммит и тег, отправляет ветку в GitHub, а затем публикует пакет с открытым доступом:
84
+
85
+ ```bash
86
+ npm run release
87
+ ```
88
+
89
+ Чтобы выпустить уже указанную в `package.json` версию без повышения номера, используется команда
90
+ `npm run release:current`.
package/bin/cli.js ADDED
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { install } from '../src/install.js';
4
+ import { notify } from '../src/notifier.js';
5
+ import { testNotification } from '../src/send-sample.js';
6
+ import { uninstall } from '../src/uninstall.js';
7
+
8
+ const [command, ...args] = process.argv.slice(2);
9
+
10
+ async function main() {
11
+ switch (command) {
12
+ case 'install':
13
+ await install();
14
+ break;
15
+ case 'uninstall':
16
+ await uninstall();
17
+ break;
18
+ case 'test':
19
+ await testNotification();
20
+ break;
21
+ case 'notify':
22
+ await notify(args[0]);
23
+ break;
24
+ case '--help':
25
+ case '-h':
26
+ case undefined:
27
+ printHelp();
28
+ break;
29
+ default:
30
+ if (looksLikeCodexEvent(command)) {
31
+ await notify(command);
32
+ break;
33
+ }
34
+ console.error(`Неизвестная команда: ${command}`);
35
+ printHelp();
36
+ process.exitCode = 1;
37
+ }
38
+ }
39
+
40
+ function looksLikeCodexEvent(value) {
41
+ return typeof value === 'string' && value.trimStart().startsWith('{');
42
+ }
43
+
44
+ function printHelp() {
45
+ console.log(`Использование: codex-notify <команда>
46
+
47
+ Команды:
48
+ install Настроить Telegram и подключить уведомитель к Codex
49
+ test Отправить пробное уведомление
50
+ uninstall Отключить уведомитель от Codex, сохранив его настройки
51
+ --help Показать эту справку`);
52
+ }
53
+
54
+ main().catch((error) => {
55
+ console.error(`codex-notify: ${error.message}`);
56
+ process.exitCode = 1;
57
+ });
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@bazilio-san/codex-notify",
3
+ "version": "1.0.6",
4
+ "description": "Telegram notifications when a Codex turn completes",
5
+ "type": "module",
6
+ "main": "src/notifier.js",
7
+ "bin": {
8
+ "codex-notify": "bin/cli.js"
9
+ },
10
+ "files": [
11
+ "bin",
12
+ "src",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "scripts": {
17
+ "test": "node --test",
18
+ "check": "node --check bin/cli.js && node --check src/config.js && node --check src/notifier.js",
19
+ "release": "node scripts/publish.js",
20
+ "release:current": "node scripts/publish.js -n"
21
+ },
22
+ "engines": {
23
+ "node": ">=18"
24
+ },
25
+ "keywords": [
26
+ "codex",
27
+ "telegram",
28
+ "notifications",
29
+ "openai"
30
+ ],
31
+ "author": {
32
+ "name": "Viacheslav Makarov",
33
+ "email": "npmjs@bazilio.ru"
34
+ },
35
+ "license": "MIT",
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/Bazilio-san/codex-notify.git"
39
+ },
40
+ "homepage": "https://github.com/Bazilio-san/codex-notify#readme",
41
+ "bugs": {
42
+ "url": "https://github.com/Bazilio-san/codex-notify/issues"
43
+ },
44
+ "publishConfig": {
45
+ "access": "public"
46
+ }
47
+ }
@@ -0,0 +1,118 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ import { getCodexConfigPath } from './paths.js';
5
+
6
+ const MANAGED_MARKER = '# Managed by codex-notify';
7
+
8
+ export function createNotifyCommand(cliPath) {
9
+ return [process.execPath, cliPath];
10
+ }
11
+
12
+ export function registerNotify(command, configPath = getCodexConfigPath()) {
13
+ const source = readText(configPath);
14
+ const assignment = `${MANAGED_MARKER}\nnotify = ${formatTomlArray(command)}`;
15
+ const cleaned = removeManagedNotify(source);
16
+ const firstTable = findFirstTableStart(cleaned);
17
+ const before = cleaned.slice(0, firstTable).trimEnd();
18
+ const after = cleaned.slice(firstTable).trimStart();
19
+ const output = [before, assignment, after].filter(Boolean).join('\n\n');
20
+ writeText(configPath, `${output}\n`);
21
+ }
22
+
23
+ export function unregisterNotify(command, configPath = getCodexConfigPath()) {
24
+ const source = readText(configPath);
25
+ const expected = `notify = ${formatTomlArray(command)}`;
26
+ const lines = source.split(/\r?\n/);
27
+ const markerIndex = lines.findIndex((line) => line.trim() === MANAGED_MARKER);
28
+ if (markerIndex < 0 || lines[markerIndex + 1]?.trim() !== expected) {
29
+ return false;
30
+ }
31
+ lines.splice(markerIndex, 2);
32
+ const output = lines.join('\n').replace(/^\n+/, '').replace(/\n{3,}/g, '\n\n').trimEnd();
33
+ writeText(configPath, output ? `${output}\n` : '');
34
+ return true;
35
+ }
36
+
37
+ function removeManagedNotify(source) {
38
+ const lines = source.split(/\r?\n/);
39
+ const output = [];
40
+ let tableSeen = false;
41
+ for (let index = 0; index < lines.length; index += 1) {
42
+ const trimmed = lines[index].trim();
43
+ if (trimmed.startsWith('[')) {
44
+ tableSeen = true;
45
+ }
46
+ if (!tableSeen && trimmed === MANAGED_MARKER && /^notify\s*=/.test(lines[index + 1]?.trim() || '')) {
47
+ index += 1;
48
+ continue;
49
+ }
50
+ if (!tableSeen && /^notify\s*=/.test(trimmed)) {
51
+ index = skipTomlValue(lines, index);
52
+ if (output.at(-1)?.trim() === MANAGED_MARKER) {
53
+ output.pop();
54
+ }
55
+ continue;
56
+ }
57
+ output.push(lines[index]);
58
+ }
59
+ return output.join('\n').trim();
60
+ }
61
+
62
+ function skipTomlValue(lines, start) {
63
+ let balance = 0;
64
+ let quote = '';
65
+ let escaped = false;
66
+ for (let index = start; index < lines.length; index += 1) {
67
+ for (const character of lines[index]) {
68
+ if (escaped) {
69
+ escaped = false;
70
+ } else if (character === '\\' && quote === '"') {
71
+ escaped = true;
72
+ } else if (quote) {
73
+ if (character === quote) {
74
+ quote = '';
75
+ }
76
+ } else if (character === '"' || character === "'") {
77
+ quote = character;
78
+ } else if (character === '[') {
79
+ balance += 1;
80
+ } else if (character === ']') {
81
+ balance -= 1;
82
+ }
83
+ }
84
+ if (balance <= 0) {
85
+ return index;
86
+ }
87
+ }
88
+ return lines.length - 1;
89
+ }
90
+
91
+ function findFirstTableStart(source) {
92
+ const match = /^\s*\[/m.exec(source);
93
+ return match ? match.index : source.length;
94
+ }
95
+
96
+ function formatTomlArray(values) {
97
+ return `[${values.map((value) => `"${escapeTomlString(value)}"`).join(', ')}]`;
98
+ }
99
+
100
+ function escapeTomlString(value) {
101
+ return String(value).replaceAll('\\', '\\\\').replaceAll('"', '\\"');
102
+ }
103
+
104
+ function readText(filePath) {
105
+ try {
106
+ return fs.readFileSync(filePath, 'utf8');
107
+ } catch (error) {
108
+ if (error.code === 'ENOENT') {
109
+ return '';
110
+ }
111
+ throw error;
112
+ }
113
+ }
114
+
115
+ function writeText(filePath, contents) {
116
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
117
+ fs.writeFileSync(filePath, contents);
118
+ }
package/src/config.js ADDED
@@ -0,0 +1,66 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ import { getConfigPath } from './paths.js';
5
+
6
+ export const DEFAULT_CONFIG = Object.freeze({
7
+ telegram: {
8
+ enabled: true,
9
+ token: '',
10
+ chatId: '',
11
+ deleteAfterHours: 24,
12
+ includeLastMessage: true,
13
+ },
14
+ debug: false,
15
+ });
16
+
17
+ export function loadConfig(configPath = getConfigPath()) {
18
+ let stored = {};
19
+ try {
20
+ stored = JSON.parse(fs.readFileSync(configPath, 'utf8'));
21
+ } catch (error) {
22
+ if (error.code !== 'ENOENT') {
23
+ throw new Error(`Не удалось прочитать настройки ${configPath}: ${error.message}`);
24
+ }
25
+ }
26
+
27
+ const config = {
28
+ ...DEFAULT_CONFIG,
29
+ ...stored,
30
+ telegram: {
31
+ ...DEFAULT_CONFIG.telegram,
32
+ ...stored.telegram,
33
+ },
34
+ };
35
+
36
+ applyEnvironment(config);
37
+ return config;
38
+ }
39
+
40
+ export function saveConfig(config, configPath = getConfigPath()) {
41
+ fs.mkdirSync(path.dirname(configPath), { recursive: true });
42
+ fs.writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
43
+ }
44
+
45
+ function applyEnvironment(config) {
46
+ const env = process.env;
47
+ if (env.CODEX_NOTIFY_TELEGRAM_TOKEN !== undefined) {
48
+ config.telegram.token = env.CODEX_NOTIFY_TELEGRAM_TOKEN;
49
+ }
50
+ if (env.CODEX_NOTIFY_TELEGRAM_CHAT_ID !== undefined) {
51
+ config.telegram.chatId = env.CODEX_NOTIFY_TELEGRAM_CHAT_ID;
52
+ }
53
+ if (env.CODEX_NOTIFY_TELEGRAM !== undefined) {
54
+ config.telegram.enabled = parseBoolean(env.CODEX_NOTIFY_TELEGRAM);
55
+ }
56
+ if (env.CODEX_NOTIFY_INCLUDE_LAST_MESSAGE !== undefined) {
57
+ config.telegram.includeLastMessage = parseBoolean(env.CODEX_NOTIFY_INCLUDE_LAST_MESSAGE);
58
+ }
59
+ if (env.CODEX_NOTIFY_DEBUG !== undefined) {
60
+ config.debug = parseBoolean(env.CODEX_NOTIFY_DEBUG);
61
+ }
62
+ }
63
+
64
+ function parseBoolean(value) {
65
+ return value === '1' || value.toLowerCase() === 'true';
66
+ }
package/src/install.js ADDED
@@ -0,0 +1,44 @@
1
+ import { fileURLToPath } from 'node:url';
2
+
3
+ import { createNotifyCommand, registerNotify } from './codex-config.js';
4
+ import { loadConfig, saveConfig } from './config.js';
5
+ import { getCodexConfigPath, getConfigPath } from './paths.js';
6
+ import { askRequired, withPrompts } from './prompt.js';
7
+ import { findChatId, sendTelegramMessage } from './telegram.js';
8
+
9
+ export async function install() {
10
+ const config = loadConfig();
11
+ await withPrompts(async (prompt) => {
12
+ console.log('Настройка уведомлений Codex в Telegram.');
13
+ console.log('Создайте бота через @BotFather и отправьте этому боту любое сообщение до продолжения.\n');
14
+
15
+ config.telegram.token = await askRequired(prompt, 'Введите токен Telegram-бота', config.telegram.token);
16
+ const detectedChatId = await tryFindChatId(config.telegram.token);
17
+ if (detectedChatId) {
18
+ console.log(`Telegram-чат найден автоматически: ${detectedChatId}`);
19
+ }
20
+ config.telegram.chatId = detectedChatId || (await askRequired(
21
+ prompt,
22
+ 'Введите идентификатор Telegram-чата',
23
+ config.telegram.chatId,
24
+ ));
25
+ });
26
+
27
+ saveConfig(config);
28
+ const cliPath = fileURLToPath(new URL('../bin/cli.js', import.meta.url));
29
+ registerNotify(createNotifyCommand(cliPath));
30
+ await sendTelegramMessage(config, '✅ <b>codex-notify настроен</b>\nCodex будет сообщать о завершении работы.');
31
+
32
+ console.log(`\nНастройки Telegram сохранены в ${getConfigPath()}.`);
33
+ console.log(`Команда уведомителя добавлена в ${getCodexConfigPath()}.`);
34
+ console.log('Пробное сообщение успешно отправлено. Перезапустите Codex, если он уже был открыт.');
35
+ }
36
+
37
+ async function tryFindChatId(token) {
38
+ try {
39
+ return await findChatId(token);
40
+ } catch (error) {
41
+ console.warn(`Не удалось определить Telegram-чат автоматически: ${error.message}`);
42
+ return '';
43
+ }
44
+ }
@@ -0,0 +1,81 @@
1
+ import path from 'node:path';
2
+
3
+ import { loadConfig } from './config.js';
4
+ import { loadState, saveState } from './state.js';
5
+ import { deleteTelegramMessage, escapeHtml, sendTelegramMessage, truncateText } from './telegram.js';
6
+
7
+ export async function notify(rawEvent) {
8
+ const config = loadConfig();
9
+ if (!config.telegram.enabled || !config.telegram.token || !config.telegram.chatId) {
10
+ debug(config, 'Уведомление пропущено, потому что Telegram не настроен или отключён.');
11
+ return;
12
+ }
13
+
14
+ const event = parseEvent(rawEvent);
15
+ if (event.type !== 'agent-turn-complete') {
16
+ debug(config, `Событие ${event.type || 'без типа'} не требует уведомления.`);
17
+ return;
18
+ }
19
+
20
+ const state = loadState();
21
+ await deleteExpiredMessages(config, state);
22
+ const sent = await sendTelegramMessage(config, formatNotification(event, config));
23
+ state.sentMessages.push({ id: sent.message_id, timestamp: Date.now() });
24
+ saveState(state);
25
+ }
26
+
27
+ export function parseEvent(rawEvent) {
28
+ if (!rawEvent) {
29
+ throw new Error('Codex не передал данные события.');
30
+ }
31
+ try {
32
+ return JSON.parse(rawEvent);
33
+ } catch (error) {
34
+ throw new Error(`Codex передал некорректный JSON события: ${error.message}`);
35
+ }
36
+ }
37
+
38
+ export function formatNotification(event, config) {
39
+ const cwd = event.cwd || process.cwd();
40
+ const project = path.basename(cwd) || cwd;
41
+ const input = Array.isArray(event['input-messages']) ? event['input-messages'].join('\n') : '';
42
+ const response = config.telegram.includeLastMessage ? event['last-assistant-message'] || '' : '';
43
+ const lines = [`✅ <b>Codex завершил работу</b>`, `<b>Проект:</b> <code>${escapeHtml(project)}</code>`];
44
+
45
+ if (input) {
46
+ lines.push('', '<b>Задача:</b>', escapeHtml(truncateText(input, 900)));
47
+ }
48
+ if (response) {
49
+ lines.push('', '<b>Ответ:</b>', escapeHtml(truncateText(response, 2800)));
50
+ }
51
+ if (config.debug) {
52
+ lines.push('', `<b>Диалог:</b> <code>${escapeHtml(event['thread-id'] || 'неизвестен')}</code>`);
53
+ }
54
+ return lines.join('\n');
55
+ }
56
+
57
+ async function deleteExpiredMessages(config, state) {
58
+ const hours = Number(config.telegram.deleteAfterHours);
59
+ if (!Number.isFinite(hours) || hours <= 0) {
60
+ return;
61
+ }
62
+ const cutoff = Date.now() - hours * 60 * 60 * 1000;
63
+ const current = [];
64
+ for (const message of state.sentMessages) {
65
+ if (message.timestamp >= cutoff) {
66
+ current.push(message);
67
+ continue;
68
+ }
69
+ const deleted = await deleteTelegramMessage(config, message.id);
70
+ if (!deleted) {
71
+ current.push(message);
72
+ }
73
+ }
74
+ state.sentMessages = current;
75
+ }
76
+
77
+ function debug(config, message) {
78
+ if (config.debug) {
79
+ console.error(`[codex-notify] ${message}`);
80
+ }
81
+ }
package/src/paths.js ADDED
@@ -0,0 +1,18 @@
1
+ import os from 'node:os';
2
+ import path from 'node:path';
3
+
4
+ export function getCodexHome() {
5
+ return process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
6
+ }
7
+
8
+ export function getConfigPath() {
9
+ return path.join(getCodexHome(), 'codex-notify.config.json');
10
+ }
11
+
12
+ export function getStatePath() {
13
+ return path.join(getCodexHome(), 'codex-notify.state.json');
14
+ }
15
+
16
+ export function getCodexConfigPath() {
17
+ return path.join(getCodexHome(), 'config.toml');
18
+ }
package/src/prompt.js ADDED
@@ -0,0 +1,27 @@
1
+ import readline from 'node:readline/promises';
2
+
3
+ export async function withPrompts(callback) {
4
+ if (!process.stdin.isTTY) {
5
+ throw new Error('Для первоначальной настройки запустите codex-notify install в интерактивном терминале.');
6
+ }
7
+ const prompt = readline.createInterface({ input: process.stdin, output: process.stdout });
8
+ try {
9
+ return await callback(prompt);
10
+ } finally {
11
+ prompt.close();
12
+ }
13
+ }
14
+
15
+ export async function askRequired(prompt, question, currentValue = '') {
16
+ while (true) {
17
+ const suffix = currentValue ? ' (нажмите Enter, чтобы сохранить текущее значение)' : '';
18
+ const answer = (await prompt.question(`${question}${suffix}: `)).trim();
19
+ if (answer) {
20
+ return answer;
21
+ }
22
+ if (currentValue) {
23
+ return currentValue;
24
+ }
25
+ console.log('Значение не может быть пустым.');
26
+ }
27
+ }
@@ -0,0 +1,11 @@
1
+ import { loadConfig } from './config.js';
2
+ import { sendTelegramMessage } from './telegram.js';
3
+
4
+ export async function testNotification() {
5
+ const config = loadConfig();
6
+ if (!config.telegram.token || !config.telegram.chatId) {
7
+ throw new Error('Telegram ещё не настроен. Сначала выполните codex-notify install.');
8
+ }
9
+ await sendTelegramMessage(config, '✅ <b>Проверка codex-notify</b>\nПробное уведомление успешно доставлено.');
10
+ console.log('Пробное уведомление успешно отправлено в Telegram.');
11
+ }
package/src/state.js ADDED
@@ -0,0 +1,20 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ import { getStatePath } from './paths.js';
5
+
6
+ export function loadState(statePath = getStatePath()) {
7
+ try {
8
+ const state = JSON.parse(fs.readFileSync(statePath, 'utf8'));
9
+ return { sentMessages: Array.isArray(state.sentMessages) ? state.sentMessages : [] };
10
+ } catch {
11
+ return { sentMessages: [] };
12
+ }
13
+ }
14
+
15
+ export function saveState(state, statePath = getStatePath()) {
16
+ fs.mkdirSync(path.dirname(statePath), { recursive: true });
17
+ const temporaryPath = `${statePath}.${process.pid}.tmp`;
18
+ fs.writeFileSync(temporaryPath, JSON.stringify(state));
19
+ fs.renameSync(temporaryPath, statePath);
20
+ }
@@ -0,0 +1,67 @@
1
+ const TELEGRAM_TEXT_LIMIT = 4096;
2
+
3
+ export function escapeHtml(value) {
4
+ return String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
5
+ }
6
+
7
+ export function truncateText(value, maxLength) {
8
+ const text = String(value || '');
9
+ if (text.length <= maxLength) {
10
+ return text;
11
+ }
12
+ return `${text.slice(0, Math.max(0, maxLength - 1)).trimEnd()}…`;
13
+ }
14
+
15
+ export async function sendTelegramMessage(config, html) {
16
+ const { token, chatId } = config.telegram;
17
+ const text = truncateText(html, TELEGRAM_TEXT_LIMIT);
18
+ const response = await fetch(`https://api.telegram.org/bot${token}/sendMessage`, {
19
+ method: 'POST',
20
+ headers: { 'content-type': 'application/json' },
21
+ body: JSON.stringify({
22
+ chat_id: chatId,
23
+ text,
24
+ parse_mode: 'HTML',
25
+ disable_web_page_preview: true,
26
+ }),
27
+ });
28
+ const result = await readTelegramResponse(response);
29
+ if (!response.ok || !result.ok) {
30
+ throw new Error(formatTelegramError(response.status, result));
31
+ }
32
+ return result.result;
33
+ }
34
+
35
+ export async function deleteTelegramMessage(config, messageId) {
36
+ const { token, chatId } = config.telegram;
37
+ const response = await fetch(`https://api.telegram.org/bot${token}/deleteMessage`, {
38
+ method: 'POST',
39
+ headers: { 'content-type': 'application/json' },
40
+ body: JSON.stringify({ chat_id: chatId, message_id: messageId }),
41
+ });
42
+ const result = await readTelegramResponse(response);
43
+ return response.ok && result.ok;
44
+ }
45
+
46
+ export async function findChatId(token) {
47
+ const response = await fetch(`https://api.telegram.org/bot${token}/getUpdates`);
48
+ const result = await readTelegramResponse(response);
49
+ if (!response.ok || !result.ok) {
50
+ throw new Error(formatTelegramError(response.status, result));
51
+ }
52
+ const messages = result.result?.filter((update) => update.message?.chat?.id) || [];
53
+ return messages.length > 0 ? String(messages.at(-1).message.chat.id) : '';
54
+ }
55
+
56
+ async function readTelegramResponse(response) {
57
+ try {
58
+ return await response.json();
59
+ } catch {
60
+ return { ok: false, description: 'Telegram вернул ответ, который не является JSON.' };
61
+ }
62
+ }
63
+
64
+ function formatTelegramError(status, result) {
65
+ const description = result.description || 'Telegram не сообщил подробности ошибки.';
66
+ return `Telegram API вернул код HTTP ${status}: ${description}`;
67
+ }
@@ -0,0 +1,15 @@
1
+ import { fileURLToPath } from 'node:url';
2
+
3
+ import { createNotifyCommand, unregisterNotify } from './codex-config.js';
4
+ import { getCodexConfigPath, getConfigPath } from './paths.js';
5
+
6
+ export async function uninstall() {
7
+ const cliPath = fileURLToPath(new URL('../bin/cli.js', import.meta.url));
8
+ const removed = unregisterNotify(createNotifyCommand(cliPath));
9
+ if (removed) {
10
+ console.log(`Уведомитель отключён в ${getCodexConfigPath()}.`);
11
+ } else {
12
+ console.log('Настройка codex-notify не найдена, поэтому изменять конфигурацию Codex не потребовалось.');
13
+ }
14
+ console.log(`Настройки Telegram сохранены в ${getConfigPath()}, чтобы их можно было использовать повторно.`);
15
+ }