opencode-windows-scheduler 1.2.3 → 1.4.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.
Files changed (58) hide show
  1. package/CHANGELOG.md +61 -2
  2. package/README.md +21 -4
  3. package/ROADMAP-STRATEGY.md +61 -159
  4. package/ROADMAP.md +60 -98
  5. package/dist/core/audit.d.ts +68 -0
  6. package/dist/core/audit.d.ts.map +1 -0
  7. package/dist/core/audit.js +206 -0
  8. package/dist/core/native-notify.d.ts +36 -0
  9. package/dist/core/native-notify.d.ts.map +1 -0
  10. package/dist/core/native-notify.js +110 -0
  11. package/dist/core/record-history.js +4 -4
  12. package/dist/core/secrets.d.ts +57 -0
  13. package/dist/core/secrets.d.ts.map +1 -0
  14. package/dist/core/secrets.js +331 -0
  15. package/dist/core/structured-log.d.ts.map +1 -1
  16. package/dist/core/structured-log.js +9 -0
  17. package/dist/core/telegram.d.ts +45 -0
  18. package/dist/core/telegram.d.ts.map +1 -0
  19. package/dist/core/telegram.js +160 -0
  20. package/dist/db/schema.d.ts +1 -1
  21. package/dist/db/schema.d.ts.map +1 -1
  22. package/dist/db/schema.js +15 -0
  23. package/dist/index.d.ts +30 -4
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +349 -22
  26. package/dist/notifications.d.ts +26 -6
  27. package/dist/notifications.d.ts.map +1 -1
  28. package/dist/notifications.js +191 -34
  29. package/dist/rpc.d.ts +400 -0
  30. package/dist/rpc.d.ts.map +1 -1
  31. package/dist/rpc.js +146 -0
  32. package/dist/server.d.ts.map +1 -1
  33. package/dist/server.js +67 -0
  34. package/dist/settings.d.ts +63 -2
  35. package/dist/settings.d.ts.map +1 -1
  36. package/dist/settings.js +126 -2
  37. package/dist/workspaces.d.ts +8 -2
  38. package/dist/workspaces.d.ts.map +1 -1
  39. package/dist/workspaces.js +21 -4
  40. package/docs/ARCHITECTURE.md +16 -6
  41. package/docs/FEATURES.md +57 -12
  42. package/docs/README.ru.md +23 -4
  43. package/gui-experimental.cjs +4 -4
  44. package/package.json +5 -2
  45. package/src/core/audit.ts +291 -0
  46. package/src/core/native-notify.ts +154 -0
  47. package/src/core/record-history.ts +6 -4
  48. package/src/core/secrets.ts +385 -0
  49. package/src/core/structured-log.ts +9 -0
  50. package/src/core/telegram.ts +219 -0
  51. package/src/db/schema.ts +15 -0
  52. package/src/gui.tsx +543 -6
  53. package/src/index.ts +459 -22
  54. package/src/notifications.ts +232 -40
  55. package/src/rpc.ts +157 -0
  56. package/src/server.ts +67 -0
  57. package/src/settings.ts +213 -4
  58. package/src/workspaces.ts +22 -4
@@ -1,6 +1,8 @@
1
1
  import { loadSettings, saveSettings, } from "./settings.js";
2
2
  import { buildAnalytics, } from "./core/analytics.js";
3
3
  import { getHistory } from "./db/history-repo.js";
4
+ import { sendTelegramMessage } from "./core/telegram.js";
5
+ import { sendNativeNotification } from "./core/native-notify.js";
4
6
  /** Таймаут HTTP-запроса по умолчанию: уведомление не должно подвешивать задачу. */
5
7
  const REQUEST_TIMEOUT_MS = 10000;
6
8
  /** Максимальная задержка backoff между повторами. */
@@ -57,6 +59,16 @@ export function formatNotificationMessage(payload, templates) {
57
59
  const duration = formatDuration(durationMs);
58
60
  const isSuccess = status === "success";
59
61
  const reason = typeof error === "string" && error.trim() ? `: ${error.trim()}` : "";
62
+ const tokens = typeof payload.tokens === "number" && payload.tokens > 0
63
+ ? String(Math.round(payload.tokens))
64
+ : "";
65
+ const cost = typeof payload.costUsd === "number" && payload.costUsd > 0
66
+ ? `$${payload.costUsd.toFixed(4)}`
67
+ : "";
68
+ const usage = [tokens ? `${tokens} tok` : "", cost].filter(Boolean).join(" · ");
69
+ const usageSuffix = usage ? ` · ${usage}` : "";
70
+ const costVar = usageSuffix;
71
+ const tokensVar = tokens;
60
72
  if (templates && isSuccess && templates.success.trim()) {
61
73
  return renderTemplate(templates.success, {
62
74
  task: taskName,
@@ -64,6 +76,8 @@ export function formatNotificationMessage(payload, templates) {
64
76
  duration,
65
77
  error: "",
66
78
  emoji: "✅",
79
+ cost: costVar,
80
+ tokens: tokensVar,
67
81
  });
68
82
  }
69
83
  if (templates && !isSuccess && templates.error.trim()) {
@@ -73,12 +87,14 @@ export function formatNotificationMessage(payload, templates) {
73
87
  duration,
74
88
  error: reason,
75
89
  emoji: "❌",
90
+ cost: costVar,
91
+ tokens: tokensVar,
76
92
  });
77
93
  }
78
94
  if (isSuccess) {
79
- return `✅ Задача "${taskName}" выполнена (${duration})`;
95
+ return `✅ Задача "${taskName}" выполнена (${duration})${usageSuffix}`;
80
96
  }
81
- return `❌ Задача "${taskName}" упала (${duration})${reason}`;
97
+ return `❌ Задача "${taskName}" упала (${duration})${reason}${usageSuffix}`;
82
98
  }
83
99
  /** Текст уведомления о завершении матрицы. */
84
100
  export function formatMatrixMessage(info) {
@@ -189,20 +205,120 @@ function webhookOptionsFrom(config) {
189
205
  retryDelayMs: webhook?.retryDelayMs,
190
206
  };
191
207
  }
192
- /** Отправляет текст во включённый webhook; ошибки только логируются. */
193
- async function deliver(config, message) {
194
- const webhook = config.webhook;
195
- if (!webhook?.enabled || !webhook.url.trim())
208
+ /**
209
+ * Тихие часы: true, если сейчас действует окно `quiet`. Диапазон может
210
+ * переходить через полночь (22:00 → 08:00). Некорректное время — false.
211
+ */
212
+ export function isQuietHours(now, quiet) {
213
+ if (!quiet?.enabled)
196
214
  return false;
197
- try {
198
- await sendWebhook(webhook.url, message, webhookOptionsFrom(config));
199
- console.log(`[windows-scheduler] Уведомление отправлено в webhook: ${message}`);
215
+ const parse = (value) => {
216
+ const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(typeof value === "string" ? value.trim() : "");
217
+ return match ? Number(match[1]) * 60 + Number(match[2]) : null;
218
+ };
219
+ const from = parse(quiet.from);
220
+ const to = parse(quiet.to);
221
+ if (from === null || to === null)
222
+ return false;
223
+ const minutes = now.getHours() * 60 + now.getMinutes();
224
+ if (from === to)
200
225
  return true;
226
+ if (from < to)
227
+ return minutes >= from && minutes < to;
228
+ return minutes >= from || minutes < to;
229
+ }
230
+ /** URL дашборда: настройка, иначе фактический порт сервера, иначе null. */
231
+ async function resolveDashboardUrl(config) {
232
+ const custom = (config.dashboardUrl ?? "").trim();
233
+ if (custom)
234
+ return custom;
235
+ try {
236
+ const { getDashboardPort } = await import("./server.js");
237
+ const port = getDashboardPort();
238
+ return port ? `http://localhost:${port}` : null;
201
239
  }
202
- catch (err) {
203
- console.error(`[windows-scheduler] Не удалось отправить webhook-уведомление: ${err instanceof Error ? err.message : String(err)}`);
204
- return false;
240
+ catch {
241
+ return null;
242
+ }
243
+ }
244
+ /** Токен и chat_id Telegram: настройки важнее переменных окружения. */
245
+ function telegramCredentials(config) {
246
+ const token = (config.telegram?.botToken ?? "").trim() ||
247
+ (process.env.OPENCODE_SCHEDULER_TELEGRAM_BOT_TOKEN ?? "").trim();
248
+ const chatId = (config.telegram?.chatId ?? "").trim() ||
249
+ (process.env.OPENCODE_SCHEDULER_TELEGRAM_CHAT_ID ?? "").trim();
250
+ return { token, chatId };
251
+ }
252
+ /**
253
+ * Отправляет сообщение во все включённые каналы и возвращает результат
254
+ * по каждому. Ошибки каналов не прерывают остальные и не содержат секретов.
255
+ */
256
+ async function deliverDetailed(config, message, only) {
257
+ const results = [];
258
+ const dashboardUrl = await resolveDashboardUrl(config);
259
+ const webhook = config.webhook;
260
+ if ((!only || only === "webhook") &&
261
+ config.enabled &&
262
+ webhook?.enabled &&
263
+ webhook.url.trim()) {
264
+ try {
265
+ await sendWebhook(webhook.url, message, webhookOptionsFrom(config));
266
+ console.log("[windows-scheduler] Уведомление отправлено в webhook.");
267
+ results.push({ channel: "webhook", ok: true });
268
+ }
269
+ catch (err) {
270
+ const text = err instanceof Error ? err.message : String(err);
271
+ console.error(`[windows-scheduler] Webhook: ${text}`);
272
+ results.push({ channel: "webhook", ok: false, error: text });
273
+ }
274
+ }
275
+ const telegram = config.telegram;
276
+ if ((!only || only === "telegram") && config.enabled && telegram?.enabled) {
277
+ const { token, chatId } = telegramCredentials(config);
278
+ if (!token || !chatId) {
279
+ const text = "Telegram включён, но не заданы botToken/chatId.";
280
+ console.error(`[windows-scheduler] ${text}`);
281
+ results.push({ channel: "telegram", ok: false, error: text });
282
+ }
283
+ else {
284
+ try {
285
+ await sendTelegramMessage(token, chatId, message, {
286
+ apiBase: telegram.apiBase,
287
+ parseMode: telegram.parseMode,
288
+ disableNotification: telegram.disableNotification,
289
+ messageThreadId: telegram.messageThreadId,
290
+ includeDashboardLink: telegram.includeDashboardLink,
291
+ dashboardUrl,
292
+ });
293
+ console.log("[windows-scheduler] Уведомление отправлено в Telegram.");
294
+ results.push({ channel: "telegram", ok: true });
295
+ }
296
+ catch (err) {
297
+ const text = err instanceof Error ? err.message : String(err);
298
+ console.error(`[windows-scheduler] Telegram: ${text}`);
299
+ results.push({ channel: "telegram", ok: false, error: text });
300
+ }
301
+ }
205
302
  }
303
+ const native = config.native;
304
+ if ((!only || only === "native") && config.enabled && native?.enabled) {
305
+ const result = await sendNativeNotification({ title: "OpenCode Scheduler", body: message, sound: native.sound }, {});
306
+ if (result.success) {
307
+ console.log("[windows-scheduler] Нативное уведомление показано.");
308
+ results.push({ channel: "native", ok: true });
309
+ }
310
+ else {
311
+ const text = result.error ?? "не удалось показать уведомление";
312
+ console.error(`[windows-scheduler] Нативное уведомление: ${text}`);
313
+ results.push({ channel: "native", ok: false, error: text });
314
+ }
315
+ }
316
+ return results;
317
+ }
318
+ /** Отправляет текст во все включённые каналы; true — хотя бы один успешен. */
319
+ async function deliver(config, message) {
320
+ const results = await deliverDetailed(config, message);
321
+ return results.some((item) => item.ok);
206
322
  }
207
323
  /**
208
324
  * Уведомляет о завершении задачи во все включённые каналы.
@@ -213,7 +329,7 @@ async function deliver(config, message) {
213
329
  * - фильтры include/exclude отсекают задачи по имени;
214
330
  * - ошибки отправки только логируются, наружу не выбрасываются.
215
331
  */
216
- export async function notifyTaskCompletion(taskName, status, durationMs, error) {
332
+ export async function notifyTaskCompletion(taskName, status, durationMs, error, tokens, costUsd) {
217
333
  try {
218
334
  const settings = await loadSettings();
219
335
  const config = settings.notifications;
@@ -223,7 +339,13 @@ export async function notifyTaskCompletion(taskName, status, durationMs, error)
223
339
  return;
224
340
  if (!isTaskAllowed(taskName, config.filters))
225
341
  return;
226
- const message = formatNotificationMessage({ taskName, status, durationMs, error }, config.templates);
342
+ // Тихие часы подавляют успешные запуски, но не ошибки и таймауты.
343
+ if (isQuietHours(new Date(), config.quietHours) &&
344
+ status !== "error" &&
345
+ status !== "timeout") {
346
+ return;
347
+ }
348
+ const message = formatNotificationMessage({ taskName, status, durationMs, error, tokens, costUsd }, config.templates);
227
349
  await deliver(config, message);
228
350
  }
229
351
  catch (err) {
@@ -254,6 +376,9 @@ export async function notifyMatrixCompletion(info) {
254
376
  return;
255
377
  if (info.status === "success" && config.onlyOnError)
256
378
  return;
379
+ if (isQuietHours(new Date(), config.quietHours) && info.status !== "error") {
380
+ return;
381
+ }
257
382
  await deliver(config, formatMatrixMessage(info));
258
383
  }
259
384
  catch (err) {
@@ -405,9 +530,18 @@ export async function sendDigestNow(options = {}) {
405
530
  if (!config?.enabled) {
406
531
  return { success: false, message: "Уведомления выключены." };
407
532
  }
408
- const webhook = config.webhook;
409
- if (!webhook?.enabled || !webhook.url.trim()) {
410
- return { success: false, message: "Webhook выключен. Включите канал и укажите URL." };
533
+ const channels = [];
534
+ if (config.webhook?.enabled && config.webhook.url.trim())
535
+ channels.push("webhook");
536
+ if (config.telegram?.enabled)
537
+ channels.push("telegram");
538
+ if (config.native?.enabled)
539
+ channels.push("native");
540
+ if (channels.length === 0) {
541
+ return {
542
+ success: false,
543
+ message: "Все каналы выключены. Включите webhook, Telegram или нативные уведомления.",
544
+ };
411
545
  }
412
546
  const digest = config.digest;
413
547
  if (!digest) {
@@ -419,7 +553,9 @@ export async function sendDigestNow(options = {}) {
419
553
  now,
420
554
  });
421
555
  const text = formatDigestMessage(summary, now);
422
- await sendWebhook(webhook.url, text, webhookOptionsFrom(config));
556
+ if (!(await deliver(config, text))) {
557
+ return { success: false, message: "Не удалось отправить дайджест ни в один канал." };
558
+ }
423
559
  if (options.updateLastSentAt) {
424
560
  await saveSettings({
425
561
  notifications: {
@@ -463,30 +599,51 @@ export async function maybeSendDigest(now = new Date()) {
463
599
  }
464
600
  }
465
601
  /**
466
- * Отправляет тестовое сообщение в webhook (кнопка «🧪 Тестовое уведомление»).
467
- *
468
- * В отличие от notifyTaskCompletion, результат возвращается пользователю:
469
- * при тесте важно увидеть причину ошибки.
602
+ * Отправляет тестовое сообщение в выбранный канал или во все включённые
603
+ * (кнопка «🧪 Тестовое уведомление»). В отличие от notifyTaskCompletion,
604
+ * результат возвращается пользователю: при тесте важна причина ошибки.
470
605
  */
471
- export async function sendTestNotification() {
606
+ export async function sendTestNotification(channel = "all") {
472
607
  try {
473
608
  const settings = await loadSettings();
474
- const webhook = settings.notifications?.webhook;
475
- if (!webhook?.enabled) {
609
+ const config = settings.notifications;
610
+ if (!config?.enabled) {
611
+ return {
612
+ success: false,
613
+ message: "Уведомления выключены. Включите главный переключатель.",
614
+ };
615
+ }
616
+ const enabled = [];
617
+ if (config.webhook?.enabled && config.webhook.url.trim())
618
+ enabled.push("webhook");
619
+ if (config.telegram?.enabled)
620
+ enabled.push("telegram");
621
+ if (config.native?.enabled)
622
+ enabled.push("native");
623
+ if (enabled.length === 0) {
476
624
  return {
477
625
  success: false,
478
- message: "Webhook выключен. Включите канал и укажите URL.",
626
+ message: "Все каналы выключены. Включите webhook, Telegram или нативные уведомления.",
479
627
  };
480
628
  }
481
- if (!webhook.url.trim()) {
482
- return { success: false, message: "Не задан URL вебхука." };
629
+ if (channel !== "all" && !enabled.includes(channel)) {
630
+ return { success: false, message: `Канал ${channel} выключен.` };
483
631
  }
484
- await sendWebhook(webhook.url, "🧪 Тестовое уведомление от OpenCode Scheduler — webhook настроен корректно.", {
485
- timeoutMs: webhook.timeoutMs,
486
- retryCount: webhook.retryCount,
487
- retryDelayMs: webhook.retryDelayMs,
488
- });
489
- return { success: true, message: "Тестовое уведомление отправлено." };
632
+ const results = await deliverDetailed(config, "🧪 Тестовое уведомление от OpenCode Scheduler — канал настроен корректно.", channel === "all" ? undefined : channel);
633
+ const sent = results.filter((item) => item.ok).map((item) => item.channel);
634
+ const failed = results.filter((item) => !item.ok);
635
+ const parts = [];
636
+ if (sent.length > 0)
637
+ parts.push(`Отправлено: ${sent.join(", ")}.`);
638
+ if (failed.length > 0) {
639
+ parts.push(`Ошибки: ${failed
640
+ .map((item) => `${item.channel} — ${item.error ?? "неизвестная ошибка"}`)
641
+ .join("; ")}.`);
642
+ }
643
+ return {
644
+ success: failed.length === 0 && sent.length > 0,
645
+ message: parts.join(" ") || "Тестовое уведомление не отправлено.",
646
+ };
490
647
  }
491
648
  catch (err) {
492
649
  return {