opencode-windows-scheduler 1.2.3 → 1.3.0

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-windows-scheduler",
3
- "version": "1.2.3",
3
+ "version": "1.3.0",
4
4
  "description": "OpenCode v2 plugin for scheduling and orchestrating AI agent jobs: cron, one-shot runs, DAG pipelines, matrix builds, quality gates, SQLite history, metrics and a local web dashboard. Windows, macOS and Linux. Free and open source (MIT).",
5
5
  "license": "MIT",
6
6
  "author": "opencode-windows-scheduler contributors",
@@ -69,7 +69,7 @@
69
69
  "demo": "node scripts/demo-dashboard.mjs",
70
70
  "prepare": "npm run build",
71
71
  "prepublishOnly": "npm run build && npm run build:gui",
72
- "test": "node test-sqlite.mjs && node test-crash-recovery.mjs && node test-workspaces.mjs && node test-role-scoped.mjs && node test-dry-run.mjs && node test-matrix.mjs && node test-matrix-lifecycle.mjs && node test-matrix-sync.mjs && node test-retention.mjs && node test-metrics.mjs && node test-schedule-v2.mjs && node test-notifications-v2.mjs && node test-profiles.mjs && node test-env.mjs && node test-agent-tools.mjs && node test-skill.mjs && node test-integrations.mjs && node test-one-shot.mjs && node test-session-continuity.mjs && node test-task-status.mjs && node test-jobs-view.mjs && node test-dag.mjs && node test-dashboard.mjs && node test-dashboard-dag.mjs && node test-dashboard-json.mjs && node test-docs.mjs",
72
+ "test": "node test-sqlite.mjs && node test-crash-recovery.mjs && node test-workspaces.mjs && node test-role-scoped.mjs && node test-dry-run.mjs && node test-matrix.mjs && node test-matrix-lifecycle.mjs && node test-matrix-sync.mjs && node test-retention.mjs && node test-metrics.mjs && node test-schedule-v2.mjs && node test-notifications-v2.mjs && node test-notifications-v3.mjs && node test-profiles.mjs && node test-env.mjs && node test-agent-tools.mjs && node test-skill.mjs && node test-integrations.mjs && node test-one-shot.mjs && node test-session-continuity.mjs && node test-task-status.mjs && node test-jobs-view.mjs && node test-dag.mjs && node test-dashboard.mjs && node test-dashboard-dag.mjs && node test-dashboard-json.mjs && node test-docs.mjs",
73
73
  "test:sqlite": "node test-sqlite.mjs",
74
74
  "test:crash": "node test-crash-recovery.mjs",
75
75
  "test:workspaces": "node test-workspaces.mjs",
@@ -82,6 +82,7 @@
82
82
  "test:metrics": "node test-metrics.mjs",
83
83
  "test:schedule-v2": "node test-schedule-v2.mjs",
84
84
  "test:notifications-v2": "node test-notifications-v2.mjs",
85
+ "test:notifications-v3": "node test-notifications-v3.mjs",
85
86
  "test:profiles": "node test-profiles.mjs",
86
87
  "test:env": "node test-env.mjs",
87
88
  "test:agent": "node test-agent-tools.mjs",
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Нативные уведомления ОС (Спринт 25).
3
+ *
4
+ * Windows — Toast через PowerShell/WinRT, macOS — Notification Center через
5
+ * osascript, Linux — notify-send (libnotify). Внешних зависимостей нет:
6
+ * node-notifier не требуется. Все ошибки проглатываются намеренно —
7
+ * уведомление не должно ломать задачу.
8
+ */
9
+ import { execFile } from "node:child_process";
10
+ import { promisify } from "node:util";
11
+
12
+ const execFileAsync = promisify(execFile);
13
+
14
+ /** Таймаут запуска процесса уведомления. */
15
+ const DEFAULT_TIMEOUT_MS = 15_000;
16
+
17
+ export interface NativeNotificationMessage {
18
+ /** Заголовок; по умолчанию «OpenCode Scheduler». */
19
+ title?: string;
20
+ /** Текст уведомления. */
21
+ body: string;
22
+ /** Со звуком, если платформа поддерживает. */
23
+ sound?: boolean;
24
+ }
25
+
26
+ /** Готовая команда запуска — удобно проверять в тестах. */
27
+ export interface NativeCommand {
28
+ command: string;
29
+ args: string[];
30
+ env?: Record<string, string>;
31
+ }
32
+
33
+ /** Скрипт Windows Toast: текст передаётся через env, чтобы не экранировать кавычки. */
34
+ const WINDOWS_TOAST_SCRIPT = `
35
+ $ErrorActionPreference = 'Stop'
36
+ $title = [System.Security.SecurityElement]::Escape($env:OCS_NOTIFY_TITLE)
37
+ $body = [System.Security.SecurityElement]::Escape($env:OCS_NOTIFY_BODY)
38
+ $silent = if ($env:OCS_NOTIFY_SOUND -eq '1') { '' } else { '<audio silent="true"/>' }
39
+ $xml = '<toast><visual><binding template="ToastGeneric"><text>' + $title + '</text><text>' + $body + '</text></binding></visual>' + $silent + '</toast>'
40
+ [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType=WindowsRuntime] > $null
41
+ [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType=WindowsRuntime] > $null
42
+ $doc = [Windows.Data.Xml.Dom.XmlDocument]::new()
43
+ $doc.LoadXml($xml)
44
+ $toast = [Windows.UI.Notifications.ToastNotification]::new($doc)
45
+ $appId = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe'
46
+ [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($appId).Show($toast)
47
+ `.trim();
48
+
49
+ /**
50
+ * Собирает команду нативного уведомления для платформы.
51
+ * Чистая функция: ничего не запускает.
52
+ */
53
+ export function buildNativeNotificationCommand(
54
+ platform: NodeJS.Platform,
55
+ message: NativeNotificationMessage
56
+ ): NativeCommand {
57
+ const title = (message.title ?? "OpenCode Scheduler").trim() || "OpenCode Scheduler";
58
+ const body = String(message.body ?? "");
59
+ const sound = message.sound !== false;
60
+
61
+ if (platform === "win32") {
62
+ return {
63
+ command: "powershell.exe",
64
+ args: [
65
+ "-NoProfile",
66
+ "-NonInteractive",
67
+ "-ExecutionPolicy",
68
+ "Bypass",
69
+ "-Command",
70
+ WINDOWS_TOAST_SCRIPT,
71
+ ],
72
+ env: {
73
+ OCS_NOTIFY_TITLE: title,
74
+ OCS_NOTIFY_BODY: body,
75
+ OCS_NOTIFY_SOUND: sound ? "1" : "0",
76
+ },
77
+ };
78
+ }
79
+
80
+ if (platform === "darwin") {
81
+ const script =
82
+ 'display notification (system attribute "OCS_NOTIFY_BODY") ' +
83
+ 'with title (system attribute "OCS_NOTIFY_TITLE")' +
84
+ (sound ? ' sound name "Glass"' : "");
85
+ return {
86
+ command: "osascript",
87
+ args: ["-e", script],
88
+ env: {
89
+ OCS_NOTIFY_TITLE: title,
90
+ OCS_NOTIFY_BODY: body,
91
+ },
92
+ };
93
+ }
94
+
95
+ return {
96
+ command: "notify-send",
97
+ args: [
98
+ "-a",
99
+ "OpenCode Scheduler",
100
+ "-u",
101
+ "normal",
102
+ "-i",
103
+ "dialog-information",
104
+ title,
105
+ body,
106
+ ],
107
+ };
108
+ }
109
+
110
+ export interface SendNativeOptions {
111
+ /** Подмена платформы для тестов. */
112
+ platform?: NodeJS.Platform;
113
+ /** Подмена запуска процесса для тестов. */
114
+ exec?: (command: string, args: string[], env: NodeJS.ProcessEnv) => Promise<void>;
115
+ /** Таймаут процесса в мс. */
116
+ timeoutMs?: number;
117
+ }
118
+
119
+ export interface NativeSendResult {
120
+ success: boolean;
121
+ error?: string;
122
+ }
123
+
124
+ /**
125
+ * Показывает нативное уведомление. Никогда не бросает исключение.
126
+ */
127
+ export async function sendNativeNotification(
128
+ message: NativeNotificationMessage,
129
+ options: SendNativeOptions = {}
130
+ ): Promise<NativeSendResult> {
131
+ const platform = options.platform ?? process.platform;
132
+ const command = buildNativeNotificationCommand(platform, message);
133
+ const env = { ...process.env, ...(command.env ?? {}) };
134
+ const timeoutMs = Math.max(1_000, Math.floor(options.timeoutMs ?? DEFAULT_TIMEOUT_MS));
135
+
136
+ try {
137
+ if (options.exec) {
138
+ await options.exec(command.command, command.args, env);
139
+ } else {
140
+ await execFileAsync(command.command, command.args, {
141
+ env,
142
+ timeout: timeoutMs,
143
+ windowsHide: true,
144
+ maxBuffer: 1024 * 1024,
145
+ });
146
+ }
147
+ return { success: true };
148
+ } catch (err: any) {
149
+ return {
150
+ success: false,
151
+ error: err instanceof Error ? err.message : String(err),
152
+ };
153
+ }
154
+ }
@@ -337,7 +337,7 @@ async function main() {
337
337
  return;
338
338
  }
339
339
 
340
- await handleCompletion(taskName, st, chainTarget, error, durationMs);
340
+ await handleCompletion(taskName, st, chainTarget, error, durationMs, tokens, costUsd);
341
341
  return;
342
342
  }
343
343
 
@@ -389,7 +389,7 @@ async function main() {
389
389
  definition?.deniedTools ?? null
390
390
  );
391
391
 
392
- await handleCompletion(taskName, st, chainTarget, error, durationMs);
392
+ await handleCompletion(taskName, st, chainTarget, error, durationMs, tokens, costUsd);
393
393
  }
394
394
 
395
395
  /**
@@ -401,11 +401,13 @@ async function handleCompletion(
401
401
  st: Status,
402
402
  chainTarget: string | null,
403
403
  error: string | null,
404
- durationMs: number
404
+ durationMs: number,
405
+ tokens?: number | null,
406
+ costUsd?: number | null
405
407
  ): Promise<void> {
406
408
  // Уведомление о завершении (webhook). Ошибки отправки логируются внутри
407
409
  // и не влияют на историю, цепочки и повторы.
408
- await notifyTaskCompletion(taskName, st, durationMs, error);
410
+ await notifyTaskCompletion(taskName, st, durationMs, error, tokens, costUsd);
409
411
 
410
412
  // Matrix (Спринт 15): клон завершился — двигаем sequential-цепочку или
411
413
  // очередь concurrency-лимита (Спринт 17), а когда все клоны готовы —
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Telegram Bot API: отправка уведомлений (Спринт 25).
3
+ *
4
+ * Модуль намеренно не зависит от настроек и сетевого слоя приложения:
5
+ * всё, что нужно, передаётся аргументами. Это позволяет тестировать
6
+ * экранирование и сборку запроса без реальных вызовов Telegram.
7
+ */
8
+ export type TelegramParseMode = "" | "HTML" | "Markdown" | "MarkdownV2";
9
+
10
+ /** Таймаут запроса по умолчанию. */
11
+ const DEFAULT_TIMEOUT_MS = 10_000;
12
+
13
+ export interface TelegramSendOptions {
14
+ /** База API; по умолчанию https://api.telegram.org. */
15
+ apiBase?: string;
16
+ /** Разметка; пусто — plain text. */
17
+ parseMode?: TelegramParseMode;
18
+ /** Отправить без звука. */
19
+ disableNotification?: boolean;
20
+ /** ID темы форума, если указан. */
21
+ messageThreadId?: number | null;
22
+ /** Добавить ссылку на дашборд. */
23
+ includeDashboardLink?: boolean;
24
+ /** URL дашборда; null/пусто — ссылка не добавляется. */
25
+ dashboardUrl?: string | null;
26
+ /** Таймаут запроса в мс. */
27
+ timeoutMs?: number;
28
+ /** Подмена fetch для тестов. */
29
+ fetchImpl?: typeof fetch;
30
+ }
31
+
32
+ /** Экранирует текст под выбранный parse_mode. */
33
+ export function escapeTelegramText(
34
+ text: string,
35
+ parseMode: TelegramParseMode = ""
36
+ ): string {
37
+ const value = String(text ?? "");
38
+ if (parseMode === "HTML") {
39
+ return value
40
+ .replace(/&/g, "&amp;")
41
+ .replace(/</g, "&lt;")
42
+ .replace(/>/g, "&gt;");
43
+ }
44
+ if (parseMode === "MarkdownV2") {
45
+ return value.replace(/([\\_*[\]()~`>#+\-=|{}.!])/g, "\\$1");
46
+ }
47
+ if (parseMode === "Markdown") {
48
+ return value.replace(/([\\_*[\]`])/g, "\\$1");
49
+ }
50
+ return value;
51
+ }
52
+
53
+ /** Экранирует URL для HTML-атрибута. */
54
+ function escapeHtmlAttribute(url: string): string {
55
+ return url
56
+ .replace(/&/g, "&amp;")
57
+ .replace(/</g, "&lt;")
58
+ .replace(/>/g, "&gt;")
59
+ .replace(/"/g, "&quot;")
60
+ .replace(/'/g, "&#39;");
61
+ }
62
+
63
+ /**
64
+ * Готовит текст сообщения: экранирует пользовательские данные и добавляет
65
+ * ссылку на дашборд в разметке выбранного режима.
66
+ */
67
+ export function formatTelegramText(
68
+ text: string,
69
+ parseMode: TelegramParseMode = "",
70
+ dashboardUrl?: string | null
71
+ ): string {
72
+ const body = escapeTelegramText(text, parseMode);
73
+ const url = (dashboardUrl ?? "").trim();
74
+ if (!url) return body;
75
+
76
+ if (parseMode === "HTML") {
77
+ return `${body}\n\n<a href="${escapeHtmlAttribute(url)}">📊 Открыть дашборд</a>`;
78
+ }
79
+ if (parseMode === "MarkdownV2") {
80
+ const escapedUrl = url.replace(/[)\\]/g, "\\$&");
81
+ return `${body}\n\n[📊 Открыть дашборд](${escapedUrl})`;
82
+ }
83
+ if (parseMode === "Markdown") {
84
+ const escapedUrl = url.replace(/[)]/g, "\\)");
85
+ return `${body}\n\n[📊 Открыть дашборд](${escapedUrl})`;
86
+ }
87
+ return `${body}\n\n📊 Открыть дашборд: ${url}`;
88
+ }
89
+
90
+ /** Проверяет формат токена бота; возвращает trimmed-значение. */
91
+ export function validateTelegramToken(token: string): string {
92
+ const value = (token ?? "").trim();
93
+ if (!value) {
94
+ throw new Error("Не задан токен Telegram-бота.");
95
+ }
96
+ // Формат BotFather: <digits>:<base64-ish>. Проверяем достаточно мягко,
97
+ // чтобы не ломать тестовые токены, но отсекать явный мусор.
98
+ if (!/^\d+:[A-Za-z0-9_-]{5,}$/.test(value)) {
99
+ throw new Error("Некорректный токен Telegram-бота.");
100
+ }
101
+ return value;
102
+ }
103
+
104
+ /** Маскирует токен для сообщений об ошибках и логов. */
105
+ export function maskTelegramToken(token: string): string {
106
+ const value = (token ?? "").trim();
107
+ if (!value) return "***";
108
+ const colon = value.indexOf(":");
109
+ if (colon <= 0) return "***";
110
+ const id = value.slice(0, colon);
111
+ const secret = value.slice(colon + 1);
112
+ const tail = secret.length >= 4 ? secret.slice(-4) : "";
113
+ return `${id}:***${tail}`;
114
+ }
115
+
116
+ /** Убирает токен из произвольного текста ошибки. */
117
+ function sanitizeErrorText(text: string, token: string): string {
118
+ if (!text) return text;
119
+ return text.split(token).join(maskTelegramToken(token));
120
+ }
121
+
122
+ function resolveApiBase(apiBase?: string): string {
123
+ const value = (apiBase ?? "https://api.telegram.org").trim().replace(/\/+$/, "");
124
+ let parsed: URL;
125
+ try {
126
+ parsed = new URL(value);
127
+ } catch {
128
+ throw new Error("Некорректный адрес Telegram API.");
129
+ }
130
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
131
+ throw new Error("Telegram API поддерживает только http:// или https://.");
132
+ }
133
+ return value;
134
+ }
135
+
136
+ /**
137
+ * Отправляет сообщение через Bot API `sendMessage`.
138
+ *
139
+ * Бросает Error с безопасным текстом (токен замаскирован). Вызывающий код
140
+ * обязан перехватить ошибку, чтобы уведомление не ломало задачу.
141
+ */
142
+ export async function sendTelegramMessage(
143
+ token: string,
144
+ chatId: string,
145
+ text: string,
146
+ options: TelegramSendOptions = {}
147
+ ): Promise<void> {
148
+ const safeToken = validateTelegramToken(token);
149
+ const target = (chatId ?? "").trim();
150
+ if (!target) {
151
+ throw new Error("Не задан chat_id Telegram.");
152
+ }
153
+
154
+ const apiBase = resolveApiBase(options.apiBase);
155
+ const parseMode = options.parseMode ?? "";
156
+ const body: Record<string, unknown> = {
157
+ chat_id: target,
158
+ text: formatTelegramText(
159
+ text,
160
+ parseMode,
161
+ options.includeDashboardLink === false ? null : options.dashboardUrl
162
+ ),
163
+ };
164
+ if (parseMode) body.parse_mode = parseMode;
165
+ if (options.disableNotification) body.disable_notification = true;
166
+ if (
167
+ typeof options.messageThreadId === "number" &&
168
+ Number.isFinite(options.messageThreadId) &&
169
+ options.messageThreadId > 0
170
+ ) {
171
+ body.message_thread_id = Math.floor(options.messageThreadId);
172
+ }
173
+
174
+ const timeoutMs = Math.max(
175
+ 1_000,
176
+ Math.floor(options.timeoutMs ?? DEFAULT_TIMEOUT_MS)
177
+ );
178
+ const fetchImpl = options.fetchImpl ?? fetch;
179
+ const controller = new AbortController();
180
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
181
+
182
+ try {
183
+ const response = await fetchImpl(
184
+ `${apiBase}/bot${safeToken}/sendMessage`,
185
+ {
186
+ method: "POST",
187
+ headers: { "Content-Type": "application/json" },
188
+ body: JSON.stringify(body),
189
+ signal: controller.signal,
190
+ }
191
+ );
192
+
193
+ const raw = await response.text().catch(() => "");
194
+ let parsed: any = null;
195
+ try {
196
+ parsed = raw ? JSON.parse(raw) : null;
197
+ } catch {
198
+ parsed = null;
199
+ }
200
+
201
+ if (!response.ok || parsed?.ok === false) {
202
+ const description =
203
+ (typeof parsed?.description === "string" && parsed.description) ||
204
+ raw.slice(0, 200) ||
205
+ `HTTP ${response.status}`;
206
+ throw new Error(
207
+ `Telegram API: ${sanitizeErrorText(description, safeToken)}`
208
+ );
209
+ }
210
+ } catch (err: any) {
211
+ if (err?.name === "AbortError") {
212
+ throw new Error(`Таймаут Telegram API (${Math.floor(timeoutMs / 1000)} с).`);
213
+ }
214
+ const message = err instanceof Error ? err.message : String(err);
215
+ throw new Error(sanitizeErrorText(message, safeToken));
216
+ } finally {
217
+ clearTimeout(timer);
218
+ }
219
+ }