@bazilio-san/codex-notify 1.0.6 → 1.0.10
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/README.md +50 -36
- package/bin/cli.js +12 -7
- package/package.json +2 -2
- package/src/channels.js +15 -0
- package/src/config.js +6 -1
- package/src/icons/complete.png +0 -0
- package/src/icons/question.png +0 -0
- package/src/install.js +35 -11
- package/src/notifier.js +28 -12
- package/src/prompt.js +3 -3
- package/src/question-hook.js +37 -0
- package/src/question.js +21 -0
- package/src/send-sample.js +12 -6
- package/src/session-source.js +44 -0
- package/src/show-toast.ps1 +27 -0
- package/src/telegram.js +3 -3
- package/src/uninstall.js +5 -3
- package/src/windows.js +25 -0
package/README.md
CHANGED
|
@@ -1,41 +1,54 @@
|
|
|
1
1
|
# codex-notify
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
Get a notification when Codex finishes a turn. Choose Telegram, Windows desktop notifications, or both. Codex launches
|
|
4
|
+
the notifier using the `notify` setting in its configuration file.
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
Windows notifications show the project name. Telegram messages also include your prompt and the final Codex response.
|
|
7
|
+
By default, the bot deletes its messages older than 24 hours the next time it sends a notification.
|
|
8
8
|
|
|
9
|
-
##
|
|
9
|
+
## Requirements
|
|
10
10
|
|
|
11
|
-
- Node.js 18
|
|
12
|
-
-
|
|
13
|
-
- Telegram
|
|
11
|
+
- Node.js 18 or later and the Codex command-line interface (CLI).
|
|
12
|
+
- For desktop notifications, run Codex on Windows with Windows PowerShell available.
|
|
13
|
+
- For Telegram, create a bot with [@BotFather](https://t.me/BotFather) and send your bot a message before setup.
|
|
14
14
|
|
|
15
|
-
##
|
|
15
|
+
## Installation
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
Install the package and start the setup wizard.
|
|
18
18
|
|
|
19
19
|
```bash
|
|
20
20
|
npm install -g @bazilio-san/codex-notify
|
|
21
21
|
codex-notify install
|
|
22
22
|
```
|
|
23
23
|
|
|
24
|
-
|
|
25
|
-
`~/.codex/config.toml
|
|
24
|
+
The wizard saves your preferences to `~/.codex/codex-notify.config.json`, registers the notification command in
|
|
25
|
+
`~/.codex/config.toml`, and sends a test notification. Restart Codex if it was already running during setup.
|
|
26
26
|
|
|
27
|
-
|
|
27
|
+
## Enable Windows notifications
|
|
28
|
+
|
|
29
|
+
Run `codex-notify install` to choose your channels, even if you have already set up Telegram. From a local checkout,
|
|
30
|
+
run `node .\bin\cli.js install` in PowerShell from the project root.
|
|
31
|
+
|
|
32
|
+
- Select **1** for Telegram only.
|
|
33
|
+
- Select **2** for Windows desktop notifications only. The built-in Windows PowerShell is sufficient.
|
|
34
|
+
- Select **3** for both channels. Press Enter at the Telegram bot token prompt to keep your saved token.
|
|
35
|
+
|
|
36
|
+
To send another test notification to your selected channels, run the command below. From a local checkout, use
|
|
37
|
+
`node .\bin\cli.js test`.
|
|
28
38
|
|
|
29
39
|
```bash
|
|
30
40
|
codex-notify test
|
|
31
41
|
```
|
|
32
42
|
|
|
33
|
-
##
|
|
43
|
+
## Configuration
|
|
34
44
|
|
|
35
|
-
|
|
45
|
+
The following example shows a Telegram configuration in `~/.codex/codex-notify.config.json`.
|
|
36
46
|
|
|
37
47
|
```json
|
|
38
48
|
{
|
|
49
|
+
"windows": {
|
|
50
|
+
"enabled": false
|
|
51
|
+
},
|
|
39
52
|
"telegram": {
|
|
40
53
|
"enabled": true,
|
|
41
54
|
"token": "123456789:ABC...",
|
|
@@ -47,44 +60,45 @@ codex-notify test
|
|
|
47
60
|
}
|
|
48
61
|
```
|
|
49
62
|
|
|
50
|
-
|
|
63
|
+
Environment variables override the corresponding settings in the configuration file.
|
|
51
64
|
|
|
52
|
-
- `CODEX_NOTIFY_TELEGRAM_TOKEN`
|
|
53
|
-
- `CODEX_NOTIFY_TELEGRAM_CHAT_ID`
|
|
54
|
-
- `CODEX_NOTIFY_TELEGRAM=0`
|
|
55
|
-
- `
|
|
56
|
-
- `
|
|
65
|
+
- `CODEX_NOTIFY_TELEGRAM_TOKEN` sets the bot token.
|
|
66
|
+
- `CODEX_NOTIFY_TELEGRAM_CHAT_ID` sets the ID of the private chat or group.
|
|
67
|
+
- `CODEX_NOTIFY_TELEGRAM=0` disables Telegram messages.
|
|
68
|
+
- `CODEX_NOTIFY_WINDOWS=1` enables Windows desktop notifications. Set it to `0` to disable them.
|
|
69
|
+
- `CODEX_NOTIFY_INCLUDE_LAST_MESSAGE=0` omits the final Codex response from Telegram messages.
|
|
70
|
+
- `CODEX_NOTIFY_DEBUG=1` includes the thread ID in Telegram messages and enables diagnostic output.
|
|
57
71
|
|
|
58
|
-
|
|
72
|
+
Set `deleteAfterHours` to `0` to turn off automatic deletion of older Telegram messages.
|
|
59
73
|
|
|
60
|
-
##
|
|
74
|
+
## Uninstall
|
|
61
75
|
|
|
62
76
|
```bash
|
|
63
77
|
codex-notify uninstall
|
|
64
|
-
npm uninstall -g codex-notify
|
|
78
|
+
npm uninstall -g @bazilio-san/codex-notify
|
|
65
79
|
```
|
|
66
80
|
|
|
67
|
-
|
|
68
|
-
|
|
81
|
+
The first command removes the package's `notify` entry from the Codex configuration and keeps your channel settings
|
|
82
|
+
for future installations.
|
|
69
83
|
|
|
70
|
-
##
|
|
84
|
+
## Supported Codex events
|
|
71
85
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
86
|
+
Windows completion notifications show the project and the first line of your request. When Codex opens a question
|
|
87
|
+
form, a separate Windows notification shows the project and the first 100 characters of the first question.
|
|
88
|
+
Setup registers a `PreToolUse` hook for the question tools. Review and trust this hook using `/hooks` in Codex
|
|
89
|
+
or Settings > Hooks in the desktop app. Existing installations can run setup again to register the hook.
|
|
75
90
|
|
|
76
|
-
##
|
|
91
|
+
## License
|
|
77
92
|
|
|
78
93
|
MIT
|
|
79
94
|
|
|
80
|
-
##
|
|
95
|
+
## Publishing
|
|
81
96
|
|
|
82
|
-
|
|
83
|
-
|
|
97
|
+
Run the release script from a clean `master` branch. It increments the patch version, runs the checks, creates a
|
|
98
|
+
commit and tag, pushes them to GitHub, and publishes the package to npm with public access.
|
|
84
99
|
|
|
85
100
|
```bash
|
|
86
101
|
npm run release
|
|
87
102
|
```
|
|
88
103
|
|
|
89
|
-
|
|
90
|
-
`npm run release:current`.
|
|
104
|
+
To publish the version already specified in `package.json`, run `npm run release:current`.
|
package/bin/cli.js
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
import { install } from '../src/install.js';
|
|
4
4
|
import { notify } from '../src/notifier.js';
|
|
5
|
+
import { notifyQuestion } from '../src/question.js';
|
|
6
|
+
import { readFileSync } from 'node:fs';
|
|
5
7
|
import { testNotification } from '../src/send-sample.js';
|
|
6
8
|
import { uninstall } from '../src/uninstall.js';
|
|
7
9
|
|
|
@@ -9,6 +11,9 @@ const [command, ...args] = process.argv.slice(2);
|
|
|
9
11
|
|
|
10
12
|
async function main() {
|
|
11
13
|
switch (command) {
|
|
14
|
+
case 'question-hook':
|
|
15
|
+
await notifyQuestion(JSON.parse(readFileSync(0, 'utf8')));
|
|
16
|
+
break;
|
|
12
17
|
case 'install':
|
|
13
18
|
await install();
|
|
14
19
|
break;
|
|
@@ -31,7 +36,7 @@ async function main() {
|
|
|
31
36
|
await notify(command);
|
|
32
37
|
break;
|
|
33
38
|
}
|
|
34
|
-
console.error(
|
|
39
|
+
console.error(`Unknown command: ${command}`);
|
|
35
40
|
printHelp();
|
|
36
41
|
process.exitCode = 1;
|
|
37
42
|
}
|
|
@@ -42,13 +47,13 @@ function looksLikeCodexEvent(value) {
|
|
|
42
47
|
}
|
|
43
48
|
|
|
44
49
|
function printHelp() {
|
|
45
|
-
console.log(
|
|
50
|
+
console.log(`Usage: codex-notify <command>
|
|
46
51
|
|
|
47
|
-
|
|
48
|
-
install
|
|
49
|
-
test
|
|
50
|
-
uninstall
|
|
51
|
-
--help
|
|
52
|
+
Commands:
|
|
53
|
+
install Choose notification channels and connect them to Codex
|
|
54
|
+
test Send a test notification
|
|
55
|
+
uninstall Disconnect from Codex and keep your notification settings
|
|
56
|
+
--help Show this help message`);
|
|
52
57
|
}
|
|
53
58
|
|
|
54
59
|
main().catch((error) => {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bazilio-san/codex-notify",
|
|
3
|
-
"version": "1.0.
|
|
4
|
-
"description": "Telegram notifications when a Codex turn completes",
|
|
3
|
+
"version": "1.0.10",
|
|
4
|
+
"description": "Windows and Telegram notifications when a Codex turn completes",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "src/notifier.js",
|
|
7
7
|
"bin": {
|
package/src/channels.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export async function deliver(config, telegram, windows) {
|
|
2
|
+
const deliveries = [];
|
|
3
|
+
if (config.telegram.enabled && config.telegram.token && config.telegram.chatId) {
|
|
4
|
+
deliveries.push(telegram());
|
|
5
|
+
}
|
|
6
|
+
if (config.windows.enabled) {
|
|
7
|
+
deliveries.push(windows());
|
|
8
|
+
}
|
|
9
|
+
const results = await Promise.allSettled(deliveries);
|
|
10
|
+
const failures = results.filter((result) => result.status === 'rejected');
|
|
11
|
+
if (failures.length) {
|
|
12
|
+
throw new Error(failures.map((result) => result.reason.message).join('\n'));
|
|
13
|
+
}
|
|
14
|
+
return results.length;
|
|
15
|
+
}
|
package/src/config.js
CHANGED
|
@@ -4,6 +4,7 @@ import path from 'node:path';
|
|
|
4
4
|
import { getConfigPath } from './paths.js';
|
|
5
5
|
|
|
6
6
|
export const DEFAULT_CONFIG = Object.freeze({
|
|
7
|
+
windows: { enabled: false },
|
|
7
8
|
telegram: {
|
|
8
9
|
enabled: true,
|
|
9
10
|
token: '',
|
|
@@ -20,13 +21,14 @@ export function loadConfig(configPath = getConfigPath()) {
|
|
|
20
21
|
stored = JSON.parse(fs.readFileSync(configPath, 'utf8'));
|
|
21
22
|
} catch (error) {
|
|
22
23
|
if (error.code !== 'ENOENT') {
|
|
23
|
-
throw new Error(
|
|
24
|
+
throw new Error(`Could not read settings from ${configPath}: ${error.message}`);
|
|
24
25
|
}
|
|
25
26
|
}
|
|
26
27
|
|
|
27
28
|
const config = {
|
|
28
29
|
...DEFAULT_CONFIG,
|
|
29
30
|
...stored,
|
|
31
|
+
windows: { ...DEFAULT_CONFIG.windows, ...stored.windows },
|
|
30
32
|
telegram: {
|
|
31
33
|
...DEFAULT_CONFIG.telegram,
|
|
32
34
|
...stored.telegram,
|
|
@@ -44,6 +46,9 @@ export function saveConfig(config, configPath = getConfigPath()) {
|
|
|
44
46
|
|
|
45
47
|
function applyEnvironment(config) {
|
|
46
48
|
const env = process.env;
|
|
49
|
+
if (env.CODEX_NOTIFY_WINDOWS !== undefined) {
|
|
50
|
+
config.windows.enabled = parseBoolean(env.CODEX_NOTIFY_WINDOWS);
|
|
51
|
+
}
|
|
47
52
|
if (env.CODEX_NOTIFY_TELEGRAM_TOKEN !== undefined) {
|
|
48
53
|
config.telegram.token = env.CODEX_NOTIFY_TELEGRAM_TOKEN;
|
|
49
54
|
}
|
|
Binary file
|
|
Binary file
|
package/src/install.js
CHANGED
|
@@ -4,22 +4,30 @@ import { createNotifyCommand, registerNotify } from './codex-config.js';
|
|
|
4
4
|
import { loadConfig, saveConfig } from './config.js';
|
|
5
5
|
import { getCodexConfigPath, getConfigPath } from './paths.js';
|
|
6
6
|
import { askRequired, withPrompts } from './prompt.js';
|
|
7
|
-
import {
|
|
7
|
+
import { testNotification } from './send-sample.js';
|
|
8
|
+
import { configureQuestionHook } from './question-hook.js';
|
|
9
|
+
import { findChatId } from './telegram.js';
|
|
8
10
|
|
|
9
11
|
export async function install() {
|
|
10
12
|
const config = loadConfig();
|
|
11
13
|
await withPrompts(async (prompt) => {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
+
if (process.platform === 'win32') {
|
|
15
|
+
await chooseChannels(prompt, config);
|
|
16
|
+
} else {
|
|
17
|
+
config.windows.enabled = false;
|
|
18
|
+
config.telegram.enabled = true;
|
|
19
|
+
}
|
|
20
|
+
if (!config.telegram.enabled) return;
|
|
21
|
+
console.log('Create a bot with @BotFather and send it a message before continuing.\n');
|
|
14
22
|
|
|
15
|
-
config.telegram.token = await askRequired(prompt, '
|
|
23
|
+
config.telegram.token = await askRequired(prompt, 'Enter your Telegram bot token', config.telegram.token);
|
|
16
24
|
const detectedChatId = await tryFindChatId(config.telegram.token);
|
|
17
25
|
if (detectedChatId) {
|
|
18
|
-
console.log(`Telegram
|
|
26
|
+
console.log(`Found Telegram chat: ${detectedChatId}`);
|
|
19
27
|
}
|
|
20
28
|
config.telegram.chatId = detectedChatId || (await askRequired(
|
|
21
29
|
prompt,
|
|
22
|
-
'
|
|
30
|
+
'Enter your Telegram chat ID',
|
|
23
31
|
config.telegram.chatId,
|
|
24
32
|
));
|
|
25
33
|
});
|
|
@@ -27,18 +35,34 @@ export async function install() {
|
|
|
27
35
|
saveConfig(config);
|
|
28
36
|
const cliPath = fileURLToPath(new URL('../bin/cli.js', import.meta.url));
|
|
29
37
|
registerNotify(createNotifyCommand(cliPath));
|
|
30
|
-
|
|
38
|
+
configureQuestionHook(cliPath, config.windows.enabled);
|
|
39
|
+
if (config.windows.enabled) console.log('Open /hooks in Codex and trust the question notification hook.');
|
|
40
|
+
console.log(`\nSaved notification settings to ${getConfigPath()}.`);
|
|
41
|
+
console.log(`Registered the notification command in ${getCodexConfigPath()}.`);
|
|
42
|
+
await testNotification(config);
|
|
43
|
+
console.log('Restart Codex if it is already running.');
|
|
44
|
+
}
|
|
31
45
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
console.log('
|
|
46
|
+
async function chooseChannels(prompt, config) {
|
|
47
|
+
const current = config.windows.enabled ? (config.telegram.enabled ? '3' : '2') : '1';
|
|
48
|
+
console.log('Where should Codex send notifications?');
|
|
49
|
+
console.log('1. Telegram\n2. Windows Notification Center\n3. Telegram and Windows');
|
|
50
|
+
while (true) {
|
|
51
|
+
const choice = (await prompt.question(`Enter a number or press Enter to select ${current}: `)).trim() || current;
|
|
52
|
+
if (['1', '2', '3'].includes(choice)) {
|
|
53
|
+
config.telegram.enabled = choice !== '2';
|
|
54
|
+
config.windows.enabled = choice !== '1';
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
console.log('Enter a number from 1 to 3.');
|
|
58
|
+
}
|
|
35
59
|
}
|
|
36
60
|
|
|
37
61
|
async function tryFindChatId(token) {
|
|
38
62
|
try {
|
|
39
63
|
return await findChatId(token);
|
|
40
64
|
} catch (error) {
|
|
41
|
-
console.warn(
|
|
65
|
+
console.warn(`Could not detect the Telegram chat: ${error.message}`);
|
|
42
66
|
return '';
|
|
43
67
|
}
|
|
44
68
|
}
|
package/src/notifier.js
CHANGED
|
@@ -1,22 +1,38 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
2
|
|
|
3
|
+
import { deliver } from './channels.js';
|
|
3
4
|
import { loadConfig } from './config.js';
|
|
4
5
|
import { loadState, saveState } from './state.js';
|
|
6
|
+
import { isSubagentThread } from './session-source.js';
|
|
5
7
|
import { deleteTelegramMessage, escapeHtml, sendTelegramMessage, truncateText } from './telegram.js';
|
|
8
|
+
import { showWindowsNotification } from './windows.js';
|
|
6
9
|
|
|
7
10
|
export async function notify(rawEvent) {
|
|
8
11
|
const config = loadConfig();
|
|
9
|
-
if (!config.telegram.enabled || !config.telegram.token || !config.telegram.chatId) {
|
|
10
|
-
debug(config, 'Уведомление пропущено, потому что Telegram не настроен или отключён.');
|
|
11
|
-
return;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
12
|
const event = parseEvent(rawEvent);
|
|
15
13
|
if (event.type !== 'agent-turn-complete') {
|
|
16
|
-
debug(config,
|
|
14
|
+
debug(config, `Skipping event with type ${event.type || '(unspecified)'}.`);
|
|
17
15
|
return;
|
|
18
16
|
}
|
|
19
17
|
|
|
18
|
+
try {
|
|
19
|
+
if (await isSubagentThread(event['thread-id'])) return;
|
|
20
|
+
} catch (error) {
|
|
21
|
+
debug(config, `Could not identify the thread source: ${error.message}`);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
await deliver(config, () => notifyTelegram(config, event), () => {
|
|
25
|
+
const cwd = event.cwd || process.cwd();
|
|
26
|
+
const messages = event['input-messages'];
|
|
27
|
+
const request = Array.isArray(messages)
|
|
28
|
+
? messages.findLast((message) => typeof message === 'string' && message.trim())
|
|
29
|
+
: '';
|
|
30
|
+
const task = request?.trim().split(/\r?\n/, 1)[0].trim();
|
|
31
|
+
return showWindowsNotification(path.basename(cwd) || cwd, truncateText(task || 'Ответ готов', 160));
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function notifyTelegram(config, event) {
|
|
20
36
|
const state = loadState();
|
|
21
37
|
await deleteExpiredMessages(config, state);
|
|
22
38
|
const sent = await sendTelegramMessage(config, formatNotification(event, config));
|
|
@@ -26,12 +42,12 @@ export async function notify(rawEvent) {
|
|
|
26
42
|
|
|
27
43
|
export function parseEvent(rawEvent) {
|
|
28
44
|
if (!rawEvent) {
|
|
29
|
-
throw new Error('Codex
|
|
45
|
+
throw new Error('Codex did not provide event data.');
|
|
30
46
|
}
|
|
31
47
|
try {
|
|
32
48
|
return JSON.parse(rawEvent);
|
|
33
49
|
} catch (error) {
|
|
34
|
-
throw new Error(`Codex
|
|
50
|
+
throw new Error(`Codex provided invalid JSON for the event: ${error.message}`);
|
|
35
51
|
}
|
|
36
52
|
}
|
|
37
53
|
|
|
@@ -40,16 +56,16 @@ export function formatNotification(event, config) {
|
|
|
40
56
|
const project = path.basename(cwd) || cwd;
|
|
41
57
|
const input = Array.isArray(event['input-messages']) ? event['input-messages'].join('\n') : '';
|
|
42
58
|
const response = config.telegram.includeLastMessage ? event['last-assistant-message'] || '' : '';
|
|
43
|
-
const lines = [`✅ <b>Codex
|
|
59
|
+
const lines = [`✅ <b>Codex finished its turn</b>`, `<b>Project:</b> <code>${escapeHtml(project)}</code>`];
|
|
44
60
|
|
|
45
61
|
if (input) {
|
|
46
|
-
lines.push('', '<b
|
|
62
|
+
lines.push('', '<b>Task:</b>', escapeHtml(truncateText(input, 900)));
|
|
47
63
|
}
|
|
48
64
|
if (response) {
|
|
49
|
-
lines.push('', '<b
|
|
65
|
+
lines.push('', '<b>Response:</b>', escapeHtml(truncateText(response, 2800)));
|
|
50
66
|
}
|
|
51
67
|
if (config.debug) {
|
|
52
|
-
lines.push('', `<b
|
|
68
|
+
lines.push('', `<b>Thread:</b> <code>${escapeHtml(event['thread-id'] || 'unknown')}</code>`);
|
|
53
69
|
}
|
|
54
70
|
return lines.join('\n');
|
|
55
71
|
}
|
package/src/prompt.js
CHANGED
|
@@ -2,7 +2,7 @@ import readline from 'node:readline/promises';
|
|
|
2
2
|
|
|
3
3
|
export async function withPrompts(callback) {
|
|
4
4
|
if (!process.stdin.isTTY) {
|
|
5
|
-
throw new Error('
|
|
5
|
+
throw new Error('Run codex-notify install in an interactive terminal to set up notifications.');
|
|
6
6
|
}
|
|
7
7
|
const prompt = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
8
8
|
try {
|
|
@@ -14,7 +14,7 @@ export async function withPrompts(callback) {
|
|
|
14
14
|
|
|
15
15
|
export async function askRequired(prompt, question, currentValue = '') {
|
|
16
16
|
while (true) {
|
|
17
|
-
const suffix = currentValue ? ' (
|
|
17
|
+
const suffix = currentValue ? ' (press Enter to keep the current value)' : '';
|
|
18
18
|
const answer = (await prompt.question(`${question}${suffix}: `)).trim();
|
|
19
19
|
if (answer) {
|
|
20
20
|
return answer;
|
|
@@ -22,6 +22,6 @@ export async function askRequired(prompt, question, currentValue = '') {
|
|
|
22
22
|
if (currentValue) {
|
|
23
23
|
return currentValue;
|
|
24
24
|
}
|
|
25
|
-
console.log('
|
|
25
|
+
console.log('Enter a value to continue.');
|
|
26
26
|
}
|
|
27
27
|
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
|
|
5
|
+
import { getCodexHome } from './paths.js';
|
|
6
|
+
import { questionMatcher } from './question.js';
|
|
7
|
+
|
|
8
|
+
export function configureQuestionHook(cliPath, enabled, configPath = path.join(getCodexHome(), 'hooks.json')) {
|
|
9
|
+
let config = {};
|
|
10
|
+
try {
|
|
11
|
+
config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
|
|
12
|
+
} catch (error) {
|
|
13
|
+
if (error.code !== 'ENOENT') throw error;
|
|
14
|
+
}
|
|
15
|
+
const command = `node "${cliPath.replaceAll('\\', '/')}" question-hook`;
|
|
16
|
+
const groups = config.hooks?.PreToolUse ?? [];
|
|
17
|
+
const index = groups.findIndex((group) => group.matcher === questionMatcher &&
|
|
18
|
+
group.hooks.some((handler) => handler.type === 'command' && handler.command === command));
|
|
19
|
+
if (enabled === (index >= 0)) return;
|
|
20
|
+
if (enabled) {
|
|
21
|
+
groups.push({ matcher: questionMatcher, hooks: [{ type: 'command', command }] });
|
|
22
|
+
} else {
|
|
23
|
+
const group = groups[index];
|
|
24
|
+
group.hooks = group.hooks.filter((handler) => handler.type !== 'command' || handler.command !== command);
|
|
25
|
+
if (!group.hooks.length) groups.splice(index, 1);
|
|
26
|
+
}
|
|
27
|
+
config.hooks ??= {};
|
|
28
|
+
config.hooks.PreToolUse = groups;
|
|
29
|
+
fs.mkdirSync(path.dirname(configPath), { recursive: true });
|
|
30
|
+
const temp = `${configPath}.${randomUUID()}.tmp`;
|
|
31
|
+
try {
|
|
32
|
+
fs.writeFileSync(temp, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
|
|
33
|
+
fs.renameSync(temp, configPath);
|
|
34
|
+
} finally {
|
|
35
|
+
fs.rmSync(temp, { force: true });
|
|
36
|
+
}
|
|
37
|
+
}
|
package/src/question.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
|
|
3
|
+
import { loadConfig } from './config.js';
|
|
4
|
+
import { showWindowsNotification } from './windows.js';
|
|
5
|
+
|
|
6
|
+
export const questionMatcher = '^(functions\\.)?request_user_input(_async)?$';
|
|
7
|
+
const questionTool = new RegExp(questionMatcher);
|
|
8
|
+
|
|
9
|
+
export async function notifyQuestion(event, config = loadConfig(), show = showWindowsNotification) {
|
|
10
|
+
if (!config.windows.enabled || event.hook_event_name !== 'PreToolUse' || !questionTool.test(event.tool_name)) return;
|
|
11
|
+
const questions = event.tool_input?.questions;
|
|
12
|
+
if (!Array.isArray(questions)) return;
|
|
13
|
+
const asyncForm = event.tool_name.endsWith('_async');
|
|
14
|
+
const text = questions.map((item) => asyncForm ? item?.title : item?.question)
|
|
15
|
+
.find((value) => typeof value === 'string' && value.trim());
|
|
16
|
+
if (!text) return;
|
|
17
|
+
|
|
18
|
+
const cwd = event.cwd || process.cwd();
|
|
19
|
+
const preview = Array.from(text.trim()).slice(0, 100).join('');
|
|
20
|
+
await show(path.basename(cwd) || cwd, preview, 'question');
|
|
21
|
+
}
|
package/src/send-sample.js
CHANGED
|
@@ -1,11 +1,17 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
|
|
3
|
+
import { deliver } from './channels.js';
|
|
1
4
|
import { loadConfig } from './config.js';
|
|
2
5
|
import { sendTelegramMessage } from './telegram.js';
|
|
6
|
+
import { showWindowsNotification } from './windows.js';
|
|
3
7
|
|
|
4
|
-
export async function testNotification() {
|
|
5
|
-
const
|
|
6
|
-
|
|
7
|
-
|
|
8
|
+
export async function testNotification(config = loadConfig()) {
|
|
9
|
+
const sent = await deliver(config,
|
|
10
|
+
() => sendTelegramMessage(config, '✅ <b>codex-notify test</b>\nThis is a test notification.'),
|
|
11
|
+
() => showWindowsNotification(path.basename(process.cwd()) || process.cwd(), 'Проверка уведомлений завершена.'),
|
|
12
|
+
);
|
|
13
|
+
if (!sent) {
|
|
14
|
+
throw new Error('Run codex-notify install to enable notifications first.');
|
|
8
15
|
}
|
|
9
|
-
|
|
10
|
-
console.log('Пробное уведомление успешно отправлено в Telegram.');
|
|
16
|
+
console.log('Sent a test notification to the selected channels.');
|
|
11
17
|
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { createReadStream } from 'node:fs';
|
|
2
|
+
import { readdir } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { createInterface } from 'node:readline';
|
|
5
|
+
|
|
6
|
+
import { getCodexHome } from './paths.js';
|
|
7
|
+
|
|
8
|
+
async function findRollout(directory, suffix) {
|
|
9
|
+
let entries;
|
|
10
|
+
try {
|
|
11
|
+
entries = await readdir(directory, { withFileTypes: true });
|
|
12
|
+
} catch (error) {
|
|
13
|
+
if (error.code === 'ENOENT') return;
|
|
14
|
+
throw error;
|
|
15
|
+
}
|
|
16
|
+
const file = entries.find((entry) => entry.isFile() && entry.name.startsWith('rollout-') && entry.name.endsWith(suffix));
|
|
17
|
+
if (file) return path.join(directory, file.name);
|
|
18
|
+
|
|
19
|
+
// Active rollouts are usually in the newest year/month/day directory.
|
|
20
|
+
const dates = entries.filter((entry) => entry.isDirectory() && /^\d{2,4}$/.test(entry.name));
|
|
21
|
+
for (const date of dates.sort((a, b) => b.name.localeCompare(a.name))) {
|
|
22
|
+
const found = await findRollout(path.join(directory, date.name), suffix);
|
|
23
|
+
if (found) return found;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function isSubagentThread(threadId, home = getCodexHome()) {
|
|
28
|
+
if (typeof threadId !== 'string' || !/^[\da-f-]{36}$/i.test(threadId)) return false;
|
|
29
|
+
const suffix = `-${threadId}.jsonl`;
|
|
30
|
+
const file = await findRollout(path.join(home, 'sessions'), suffix)
|
|
31
|
+
?? await findRollout(path.join(home, 'archived_sessions'), suffix);
|
|
32
|
+
if (!file) return false;
|
|
33
|
+
|
|
34
|
+
const input = createReadStream(file, { encoding: 'utf8' });
|
|
35
|
+
try {
|
|
36
|
+
for await (const line of createInterface({ input, crlfDelay: Infinity })) {
|
|
37
|
+
const { type, payload } = JSON.parse(line);
|
|
38
|
+
return type === 'session_meta' && payload?.id === threadId && payload.source?.subagent != null;
|
|
39
|
+
}
|
|
40
|
+
return false;
|
|
41
|
+
} finally {
|
|
42
|
+
input.destroy();
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
$ErrorActionPreference = 'Stop'
|
|
2
|
+
$null = [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]
|
|
3
|
+
$null = [Windows.UI.Notifications.ToastNotification, Windows.UI.Notifications, ContentType = WindowsRuntime]
|
|
4
|
+
$document = [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime]::new()
|
|
5
|
+
$document.LoadXml(@'
|
|
6
|
+
<toast>
|
|
7
|
+
<visual>
|
|
8
|
+
<binding template="ToastGeneric">
|
|
9
|
+
<text></text>
|
|
10
|
+
<text></text>
|
|
11
|
+
<image placement="appLogoOverride" />
|
|
12
|
+
<group>
|
|
13
|
+
<subgroup>
|
|
14
|
+
<text hint-style="base">Codex</text>
|
|
15
|
+
</subgroup>
|
|
16
|
+
</group>
|
|
17
|
+
</binding>
|
|
18
|
+
</visual>
|
|
19
|
+
</toast>
|
|
20
|
+
'@)
|
|
21
|
+
$fields = $document.GetElementsByTagName('text')
|
|
22
|
+
$document.GetElementsByTagName('image').Item(0).SetAttribute('src', $env:CODEX_TOAST_ICON)
|
|
23
|
+
$null = $fields.Item(0).AppendChild($document.CreateTextNode($env:CODEX_TOAST_TITLE))
|
|
24
|
+
$null = $fields.Item(1).AppendChild($document.CreateTextNode($env:CODEX_TOAST_MESSAGE))
|
|
25
|
+
$appId = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\WindowsPowerShell\v1.0\powershell.exe'
|
|
26
|
+
$notifier = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($appId)
|
|
27
|
+
$notifier.Show([Windows.UI.Notifications.ToastNotification]::new($document))
|
package/src/telegram.js
CHANGED
|
@@ -57,11 +57,11 @@ async function readTelegramResponse(response) {
|
|
|
57
57
|
try {
|
|
58
58
|
return await response.json();
|
|
59
59
|
} catch {
|
|
60
|
-
return { ok: false, description: 'Telegram
|
|
60
|
+
return { ok: false, description: 'Telegram returned a response that could not be parsed as JSON.' };
|
|
61
61
|
}
|
|
62
62
|
}
|
|
63
63
|
|
|
64
64
|
function formatTelegramError(status, result) {
|
|
65
|
-
const description = result.description || 'Telegram
|
|
66
|
-
return `Telegram API
|
|
65
|
+
const description = result.description || 'Telegram did not provide error details.';
|
|
66
|
+
return `The Telegram API returned HTTP ${status}: ${description}`;
|
|
67
67
|
}
|
package/src/uninstall.js
CHANGED
|
@@ -2,14 +2,16 @@ import { fileURLToPath } from 'node:url';
|
|
|
2
2
|
|
|
3
3
|
import { createNotifyCommand, unregisterNotify } from './codex-config.js';
|
|
4
4
|
import { getCodexConfigPath, getConfigPath } from './paths.js';
|
|
5
|
+
import { configureQuestionHook } from './question-hook.js';
|
|
5
6
|
|
|
6
7
|
export async function uninstall() {
|
|
7
8
|
const cliPath = fileURLToPath(new URL('../bin/cli.js', import.meta.url));
|
|
8
9
|
const removed = unregisterNotify(createNotifyCommand(cliPath));
|
|
10
|
+
configureQuestionHook(cliPath, false);
|
|
9
11
|
if (removed) {
|
|
10
|
-
console.log(
|
|
12
|
+
console.log(`Removed the notification command from ${getCodexConfigPath()}.`);
|
|
11
13
|
} else {
|
|
12
|
-
console.log('
|
|
14
|
+
console.log('Codex has no registered codex-notify command.');
|
|
13
15
|
}
|
|
14
|
-
console.log(
|
|
16
|
+
console.log(`Your notification settings are available in ${getConfigPath()} for future use.`);
|
|
15
17
|
}
|
package/src/windows.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { promisify } from 'node:util';
|
|
4
|
+
|
|
5
|
+
const execute = promisify(execFile);
|
|
6
|
+
const script = fileURLToPath(new URL('./show-toast.ps1', import.meta.url));
|
|
7
|
+
|
|
8
|
+
export async function showWindowsNotification(title, message, icon = 'complete') {
|
|
9
|
+
if (process.platform !== 'win32') {
|
|
10
|
+
throw new Error('Run codex-notify on Windows to receive desktop notifications.');
|
|
11
|
+
}
|
|
12
|
+
try {
|
|
13
|
+
await execute('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', script], {
|
|
14
|
+
windowsHide: true,
|
|
15
|
+
env: {
|
|
16
|
+
...process.env,
|
|
17
|
+
CODEX_TOAST_TITLE: title,
|
|
18
|
+
CODEX_TOAST_MESSAGE: message,
|
|
19
|
+
CODEX_TOAST_ICON: new URL(`./icons/${icon}.png`, import.meta.url).href,
|
|
20
|
+
},
|
|
21
|
+
});
|
|
22
|
+
} catch (error) {
|
|
23
|
+
throw new Error(`Could not send the Windows notification. ${error.stderr?.trim() || error.message}`);
|
|
24
|
+
}
|
|
25
|
+
}
|