@bazilio-san/codex-notify 1.0.9 → 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 CHANGED
@@ -83,8 +83,10 @@ for future installations.
83
83
 
84
84
  ## Supported Codex events
85
85
 
86
- The notifier handles `agent-turn-complete`, which Codex emits at the end of a turn. The Codex interface handles
87
- approval requests and prompts for additional input through its own notifications.
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.
88
90
 
89
91
  ## License
90
92
 
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;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bazilio-san/codex-notify",
3
- "version": "1.0.9",
3
+ "version": "1.0.10",
4
4
  "description": "Windows and Telegram notifications when a Codex turn completes",
5
5
  "type": "module",
6
6
  "main": "src/notifier.js",
Binary file
Binary file
package/src/install.js CHANGED
@@ -5,6 +5,7 @@ import { loadConfig, saveConfig } from './config.js';
5
5
  import { getCodexConfigPath, getConfigPath } from './paths.js';
6
6
  import { askRequired, withPrompts } from './prompt.js';
7
7
  import { testNotification } from './send-sample.js';
8
+ import { configureQuestionHook } from './question-hook.js';
8
9
  import { findChatId } from './telegram.js';
9
10
 
10
11
  export async function install() {
@@ -34,6 +35,8 @@ export async function install() {
34
35
  saveConfig(config);
35
36
  const cliPath = fileURLToPath(new URL('../bin/cli.js', import.meta.url));
36
37
  registerNotify(createNotifyCommand(cliPath));
38
+ configureQuestionHook(cliPath, config.windows.enabled);
39
+ if (config.windows.enabled) console.log('Open /hooks in Codex and trust the question notification hook.');
37
40
  console.log(`\nSaved notification settings to ${getConfigPath()}.`);
38
41
  console.log(`Registered the notification command in ${getCodexConfigPath()}.`);
39
42
  await testNotification(config);
package/src/notifier.js CHANGED
@@ -3,6 +3,7 @@ import path from 'node:path';
3
3
  import { deliver } from './channels.js';
4
4
  import { loadConfig } from './config.js';
5
5
  import { loadState, saveState } from './state.js';
6
+ import { isSubagentThread } from './session-source.js';
6
7
  import { deleteTelegramMessage, escapeHtml, sendTelegramMessage, truncateText } from './telegram.js';
7
8
  import { showWindowsNotification } from './windows.js';
8
9
 
@@ -14,9 +15,20 @@ export async function notify(rawEvent) {
14
15
  return;
15
16
  }
16
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
+
17
24
  await deliver(config, () => notifyTelegram(config, event), () => {
18
25
  const cwd = event.cwd || process.cwd();
19
- return showWindowsNotification('Codex finished its turn', `Project: ${path.basename(cwd) || 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));
20
32
  });
21
33
  }
22
34
 
@@ -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
+ }
@@ -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
+ }
@@ -1,3 +1,5 @@
1
+ import path from 'node:path';
2
+
1
3
  import { deliver } from './channels.js';
2
4
  import { loadConfig } from './config.js';
3
5
  import { sendTelegramMessage } from './telegram.js';
@@ -6,7 +8,7 @@ import { showWindowsNotification } from './windows.js';
6
8
  export async function testNotification(config = loadConfig()) {
7
9
  const sent = await deliver(config,
8
10
  () => sendTelegramMessage(config, '✅ <b>codex-notify test</b>\nThis is a test notification.'),
9
- () => showWindowsNotification('codex-notify test', 'Codex will notify you when it finishes a turn.'),
11
+ () => showWindowsNotification(path.basename(process.cwd()) || process.cwd(), 'Проверка уведомлений завершена.'),
10
12
  );
11
13
  if (!sent) {
12
14
  throw new Error('Run codex-notify install to enable notifications first.');
@@ -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
+ }
@@ -1,9 +1,25 @@
1
1
  $ErrorActionPreference = 'Stop'
2
2
  $null = [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]
3
3
  $null = [Windows.UI.Notifications.ToastNotification, Windows.UI.Notifications, ContentType = WindowsRuntime]
4
- $template = [Windows.UI.Notifications.ToastTemplateType]::ToastText02
5
- $document = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent($template)
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
+ '@)
6
21
  $fields = $document.GetElementsByTagName('text')
22
+ $document.GetElementsByTagName('image').Item(0).SetAttribute('src', $env:CODEX_TOAST_ICON)
7
23
  $null = $fields.Item(0).AppendChild($document.CreateTextNode($env:CODEX_TOAST_TITLE))
8
24
  $null = $fields.Item(1).AppendChild($document.CreateTextNode($env:CODEX_TOAST_MESSAGE))
9
25
  $appId = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\WindowsPowerShell\v1.0\powershell.exe'
package/src/uninstall.js CHANGED
@@ -2,10 +2,12 @@ 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
12
  console.log(`Removed the notification command from ${getCodexConfigPath()}.`);
11
13
  } else {
package/src/windows.js CHANGED
@@ -5,14 +5,19 @@ import { promisify } from 'node:util';
5
5
  const execute = promisify(execFile);
6
6
  const script = fileURLToPath(new URL('./show-toast.ps1', import.meta.url));
7
7
 
8
- export async function showWindowsNotification(title, message) {
8
+ export async function showWindowsNotification(title, message, icon = 'complete') {
9
9
  if (process.platform !== 'win32') {
10
10
  throw new Error('Run codex-notify on Windows to receive desktop notifications.');
11
11
  }
12
12
  try {
13
13
  await execute('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', script], {
14
14
  windowsHide: true,
15
- env: { ...process.env, CODEX_TOAST_TITLE: title, CODEX_TOAST_MESSAGE: message },
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
+ },
16
21
  });
17
22
  } catch (error) {
18
23
  throw new Error(`Could not send the Windows notification. ${error.stderr?.trim() || error.message}`);