opencode-windows-scheduler 1.5.0 → 1.5.1

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 (67) hide show
  1. package/CHANGELOG.md +37 -1
  2. package/LICENSE +21 -21
  3. package/README.md +24 -2
  4. package/ROADMAP-STRATEGY.md +16 -16
  5. package/ROADMAP.md +410 -141
  6. package/dist/core/dry-run.d.ts +10 -0
  7. package/dist/core/dry-run.d.ts.map +1 -1
  8. package/dist/core/dry-run.js +55 -34
  9. package/dist/core/git-trigger.d.ts.map +1 -1
  10. package/dist/core/git-trigger.js +15 -9
  11. package/dist/core/matrix.d.ts.map +1 -1
  12. package/dist/core/matrix.js +48 -22
  13. package/dist/core/schedule-v2.d.ts.map +1 -1
  14. package/dist/core/schedule-v2.js +29 -17
  15. package/dist/core/scheduler/types.d.ts +6 -0
  16. package/dist/core/scheduler/types.d.ts.map +1 -1
  17. package/dist/core/scheduler/windows.d.ts +6 -2
  18. package/dist/core/scheduler/windows.d.ts.map +1 -1
  19. package/dist/core/scheduler/windows.js +25 -10
  20. package/dist/core/telegram.d.ts.map +1 -1
  21. package/dist/core/telegram.js +13 -10
  22. package/dist/i18n.d.ts +52 -0
  23. package/dist/i18n.d.ts.map +1 -0
  24. package/dist/i18n.js +292 -0
  25. package/dist/index.d.ts +6 -0
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +781 -179
  28. package/dist/notifications.d.ts.map +1 -1
  29. package/dist/notifications.js +74 -40
  30. package/dist/rpc.d.ts +15 -2
  31. package/dist/rpc.d.ts.map +1 -1
  32. package/dist/rpc.js +6 -2
  33. package/dist/server.d.ts.map +1 -1
  34. package/dist/server.js +89 -48
  35. package/dist/settings.d.ts +3 -0
  36. package/dist/settings.d.ts.map +1 -1
  37. package/dist/settings.js +20 -8
  38. package/dist/task-transfer.d.ts +13 -0
  39. package/dist/task-transfer.d.ts.map +1 -1
  40. package/dist/task-transfer.js +11 -0
  41. package/dist/types.d.ts +11 -0
  42. package/dist/types.d.ts.map +1 -1
  43. package/dist/types.js +32 -0
  44. package/docs/ARCHITECTURE.md +36 -1
  45. package/docs/FEATURES.md +19 -0
  46. package/docs/README.ru.md +17 -1
  47. package/gui-experimental.cjs +9 -9
  48. package/locales/en.json +695 -0
  49. package/locales/ru.json +695 -0
  50. package/package.json +6 -3
  51. package/scripts/test-locale.mjs +44 -0
  52. package/src/core/dry-run.ts +76 -38
  53. package/src/core/git-trigger.ts +15 -9
  54. package/src/core/matrix.ts +52 -26
  55. package/src/core/schedule-v2.ts +47 -17
  56. package/src/core/scheduler/types.ts +6 -0
  57. package/src/core/scheduler/windows.ts +25 -10
  58. package/src/core/telegram.ts +16 -10
  59. package/src/gui.tsx +575 -480
  60. package/src/i18n.ts +339 -0
  61. package/src/index.ts +943 -191
  62. package/src/notifications.ts +83 -42
  63. package/src/rpc.ts +6 -2
  64. package/src/server.ts +89 -48
  65. package/src/settings.ts +38 -10
  66. package/src/task-transfer.ts +24 -0
  67. package/src/types.ts +37 -0
@@ -15,6 +15,7 @@ import {
15
15
  import { getHistory } from "./db/history-repo.js";
16
16
  import { sendTelegramMessage } from "./core/telegram.js";
17
17
  import { sendNativeNotification } from "./core/native-notify.js";
18
+ import { t } from "./i18n.js";
18
19
 
19
20
  /** Статус завершения задачи, который приходит из record-history. */
20
21
  export type NotificationStatus = "success" | "error" | "timeout" | string;
@@ -100,16 +101,18 @@ export function formatNotificationMessage(
100
101
  const duration = formatDuration(durationMs);
101
102
  const isSuccess = status === "success";
102
103
  const reason =
103
- typeof error === "string" && error.trim() ? `: ${error.trim()}` : "";
104
+ typeof error === "string" && error.trim()
105
+ ? t("notify.reason", { error: error.trim() })
106
+ : "";
104
107
  const tokens =
105
108
  typeof payload.tokens === "number" && payload.tokens > 0
106
- ? String(Math.round(payload.tokens))
109
+ ? t("notify.usage.tokens", { tokens: String(Math.round(payload.tokens)) })
107
110
  : "";
108
111
  const cost =
109
112
  typeof payload.costUsd === "number" && payload.costUsd > 0
110
113
  ? `$${payload.costUsd.toFixed(4)}`
111
114
  : "";
112
- const usage = [tokens ? `${tokens} tok` : "", cost].filter(Boolean).join(" · ");
115
+ const usage = [tokens, cost].filter(Boolean).join(" · ");
113
116
  const usageSuffix = usage ? ` · ${usage}` : "";
114
117
  const costVar = usageSuffix;
115
118
  const tokensVar = tokens;
@@ -138,9 +141,18 @@ export function formatNotificationMessage(
138
141
  }
139
142
 
140
143
  if (isSuccess) {
141
- return `✅ Задача "${taskName}" выполнена (${duration})${usageSuffix}`;
144
+ return t("notify.task.success", {
145
+ task: taskName,
146
+ duration,
147
+ cost: usageSuffix,
148
+ });
142
149
  }
143
- return `❌ Задача "${taskName}" упала (${duration})${reason}${usageSuffix}`;
150
+ return t("notify.task.error", {
151
+ task: taskName,
152
+ duration,
153
+ error: reason,
154
+ cost: usageSuffix,
155
+ });
144
156
  }
145
157
 
146
158
  /** Информация о завершении матрицы для уведомления. */
@@ -156,16 +168,17 @@ export interface MatrixNotificationInfo {
156
168
  /** Текст уведомления о завершении матрицы. */
157
169
  export function formatMatrixMessage(info: MatrixNotificationInfo): string {
158
170
  const { parentName, status, total, success, error } = info;
171
+ const params = { parent: parentName, total, success, error };
159
172
  if (status === "success") {
160
- return `✅ Матрица "${parentName}" завершилась: ${success} из ${total} клонов успешно.`;
173
+ return t("notify.matrix.success", params);
161
174
  }
162
175
  if (status === "partial") {
163
- return `⚠️ Матрица "${parentName}" завершилась частично: успешно ${success} из ${total}, ошибок ${error}.`;
176
+ return t("notify.matrix.partial", params);
164
177
  }
165
178
  if (total > 0 && error >= total) {
166
- return `❌ Матрица "${parentName}": все ${total} клонов упали.`;
179
+ return t("notify.matrix.failedAll", params);
167
180
  }
168
- return `❌ Матрица "${parentName}" завершилась с ошибками: успешно ${success}, ошибок ${error} из ${total}.`;
181
+ return t("notify.matrix.failed", params);
169
182
  }
170
183
 
171
184
  /** Ошибка отправки webhook с признаком, имеет ли смысл повторять запрос. */
@@ -194,16 +207,16 @@ const defaultSleep = (ms: number) =>
194
207
  function validateWebhookUrl(url: string): URL {
195
208
  const trimmed = (url ?? "").trim();
196
209
  if (!trimmed) {
197
- throw new Error("URL вебхука не задан.");
210
+ throw new Error(t("notify.error.webhookUrlMissing"));
198
211
  }
199
212
  let parsed: URL;
200
213
  try {
201
214
  parsed = new URL(trimmed);
202
215
  } catch {
203
- throw new Error("Некорректный URL вебхука.");
216
+ throw new Error(t("notify.error.webhookUrlInvalid"));
204
217
  }
205
218
  if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
206
- throw new Error("Вебхук поддерживает только http:// или https://.");
219
+ throw new Error(t("notify.error.webhookScheme"));
207
220
  }
208
221
  return parsed;
209
222
  }
@@ -234,7 +247,10 @@ async function postOnce(
234
247
  }
235
248
  } catch (err: any) {
236
249
  if (err?.name === "AbortError") {
237
- throw new WebhookError(`Таймаут запроса (${timeoutMs / 1000} с).`, true);
250
+ throw new WebhookError(
251
+ t("notify.error.webhookTimeout", { seconds: timeoutMs / 1000 }),
252
+ true
253
+ );
238
254
  }
239
255
  if (err instanceof WebhookError) throw err;
240
256
  // Сетевые ошибки fetch (DNS, соединение) имеет смысл повторять.
@@ -389,7 +405,7 @@ async function deliverDetailed(
389
405
  if ((!only || only === "telegram") && config.enabled && telegram?.enabled) {
390
406
  const { token, chatId } = telegramCredentials(config);
391
407
  if (!token || !chatId) {
392
- const text = "Telegram включён, но не заданы botToken/chatId.";
408
+ const text = t("notify.error.telegramNoCreds");
393
409
  console.error(`[windows-scheduler] ${text}`);
394
410
  results.push({ channel: "telegram", ok: false, error: text });
395
411
  } else {
@@ -415,14 +431,14 @@ async function deliverDetailed(
415
431
  const native = config.native;
416
432
  if ((!only || only === "native") && config.enabled && native?.enabled) {
417
433
  const result = await sendNativeNotification(
418
- { title: "OpenCode Scheduler", body: message, sound: native.sound },
434
+ { title: t("notify.native.title"), body: message, sound: native.sound },
419
435
  {}
420
436
  );
421
437
  if (result.success) {
422
438
  console.log("[windows-scheduler] Нативное уведомление показано.");
423
439
  results.push({ channel: "native", ok: true });
424
440
  } else {
425
- const text = result.error ?? "не удалось показать уведомление";
441
+ const text = result.error ?? t("notify.error.nativeFailed");
426
442
  console.error(`[windows-scheduler] Нативное уведомление: ${text}`);
427
443
  results.push({ channel: "native", ok: false, error: text });
428
444
  }
@@ -567,10 +583,12 @@ export function findStuckMatrixClones(
567
583
 
568
584
  /** Текст уведомления о зависшем клоне матрицы. */
569
585
  export function formatStuckMatrixMessage(stuck: StuckMatrixClone): string {
570
- return (
571
- `⏳ Матрица "${stuck.parentName}": клон "${stuck.cloneName}" выполняется ` +
572
- `дольше ${stuck.minutes} мин (запущен ${stuck.startedAt}).`
573
- );
586
+ return t("notify.stuck", {
587
+ parent: stuck.parentName,
588
+ clone: stuck.cloneName,
589
+ minutes: stuck.minutes,
590
+ startedAt: stuck.startedAt,
591
+ });
574
592
  }
575
593
 
576
594
  /** Отправляет уведомление о зависшем клоне, если матрицы включены. */
@@ -649,19 +667,33 @@ export function formatDigestMessage(
649
667
  summary: DigestSummary,
650
668
  now: Date = new Date()
651
669
  ): string {
652
- const periodLabel = summary.period === "weekly" ? "за неделю" : "за сутки";
670
+ const periodLabel =
671
+ summary.period === "weekly"
672
+ ? t("notify.digest.period.weekly")
673
+ : t("notify.digest.period.daily");
653
674
  const lines = [
654
- `📊 Дайджест ${periodLabel} (${formatLocalDate(now)})`,
655
- `Запусков: ${summary.total} — ✅ ${summary.success}, ❌ ${summary.error}, ⚠️ ${summary.partial} (${summary.successRate}%)`,
656
- `Стоимость: ${formatMoney(summary.costUsd)} · токенов: ${summary.tokens}`,
675
+ t("notify.digest.title", { period: periodLabel, date: formatLocalDate(now) }),
676
+ t("notify.digest.runs", {
677
+ total: summary.total,
678
+ success: summary.success,
679
+ error: summary.error,
680
+ partial: summary.partial,
681
+ rate: summary.successRate,
682
+ }),
683
+ t("notify.digest.cost", {
684
+ cost: formatMoney(summary.costUsd),
685
+ tokens: summary.tokens,
686
+ }),
657
687
  ];
658
688
  if (summary.topErrors.length > 0) {
659
- lines.push("Топ ошибок:");
689
+ lines.push(t("notify.digest.topErrors"));
660
690
  for (const row of summary.topErrors) {
661
- lines.push(`• ${row.message} — ${row.count}`);
691
+ lines.push(
692
+ t("notify.digest.topErrorRow", { message: row.message, count: row.count })
693
+ );
662
694
  }
663
695
  } else if (summary.total > 0) {
664
- lines.push("Ошибок нет 🎉");
696
+ lines.push(t("notify.digest.noErrors"));
665
697
  }
666
698
  return lines.join("\n");
667
699
  }
@@ -707,7 +739,7 @@ export async function sendDigestNow(
707
739
  const settings = await loadSettings();
708
740
  const config = settings.notifications;
709
741
  if (!config?.enabled) {
710
- return { success: false, message: "Уведомления выключены." };
742
+ return { success: false, message: t("notify.error.digestDisabled") };
711
743
  }
712
744
  const channels: NotificationChannel[] = [];
713
745
  if (config.webhook?.enabled && config.webhook.url.trim()) channels.push("webhook");
@@ -716,12 +748,12 @@ export async function sendDigestNow(
716
748
  if (channels.length === 0) {
717
749
  return {
718
750
  success: false,
719
- message: "Все каналы выключены. Включите webhook, Telegram или нативные уведомления.",
751
+ message: t("notify.error.digestNoChannels"),
720
752
  };
721
753
  }
722
754
  const digest = config.digest;
723
755
  if (!digest) {
724
- return { success: false, message: "Настройки дайджеста не найдены." };
756
+ return { success: false, message: t("notify.error.digestMissing") };
725
757
  }
726
758
 
727
759
  const records = getHistory(null, 5000) as AnalyticsRecord[];
@@ -731,7 +763,7 @@ export async function sendDigestNow(
731
763
  });
732
764
  const text = formatDigestMessage(summary, now);
733
765
  if (!(await deliver(config, text))) {
734
- return { success: false, message: "Не удалось отправить дайджест ни в один канал." };
766
+ return { success: false, message: t("notify.error.digestFailed") };
735
767
  }
736
768
 
737
769
  if (options.updateLastSentAt) {
@@ -742,7 +774,7 @@ export async function sendDigestNow(
742
774
  },
743
775
  });
744
776
  }
745
- return { success: true, message: "Дайджест отправлен." };
777
+ return { success: true, message: t("notify.ok.digestSent") };
746
778
  } catch (err: any) {
747
779
  return {
748
780
  success: false,
@@ -794,7 +826,7 @@ export async function sendTestNotification(
794
826
  if (!config?.enabled) {
795
827
  return {
796
828
  success: false,
797
- message: "Уведомления выключены. Включите главный переключатель.",
829
+ message: t("notify.error.testDisabled"),
798
830
  };
799
831
  }
800
832
 
@@ -805,33 +837,42 @@ export async function sendTestNotification(
805
837
  if (enabled.length === 0) {
806
838
  return {
807
839
  success: false,
808
- message:
809
- "Все каналы выключены. Включите webhook, Telegram или нативные уведомления.",
840
+ message: t("notify.error.testNoChannels"),
810
841
  };
811
842
  }
812
843
  if (channel !== "all" && !enabled.includes(channel)) {
813
- return { success: false, message: `Канал ${channel} выключен.` };
844
+ return {
845
+ success: false,
846
+ message: t("notify.error.testChannelOff", { channel }),
847
+ };
814
848
  }
815
849
 
816
850
  const results = await deliverDetailed(
817
851
  config,
818
- "🧪 Тестовое уведомление от OpenCode Scheduler — канал настроен корректно.",
852
+ t("notify.test.body"),
819
853
  channel === "all" ? undefined : channel
820
854
  );
821
855
  const sent = results.filter((item) => item.ok).map((item) => item.channel);
822
856
  const failed = results.filter((item) => !item.ok);
823
857
  const parts: string[] = [];
824
- if (sent.length > 0) parts.push(`Отправлено: ${sent.join(", ")}.`);
858
+ if (sent.length > 0) {
859
+ parts.push(t("notify.test.sent", { channels: sent.join(", ") }));
860
+ }
825
861
  if (failed.length > 0) {
826
862
  parts.push(
827
- `Ошибки: ${failed
828
- .map((item) => `${item.channel} — ${item.error ?? "неизвестная ошибка"}`)
829
- .join("; ")}.`
863
+ t("notify.test.errors", {
864
+ errors: failed
865
+ .map(
866
+ (item) =>
867
+ `${item.channel} — ${item.error ?? t("notify.error.testUnknown")}`
868
+ )
869
+ .join("; "),
870
+ })
830
871
  );
831
872
  }
832
873
  return {
833
874
  success: failed.length === 0 && sent.length > 0,
834
- message: parts.join(" ") || "Тестовое уведомление не отправлено.",
875
+ message: parts.join(" ") || t("notify.error.testNotSent"),
835
876
  };
836
877
  } catch (err: any) {
837
878
  return {
package/src/rpc.ts CHANGED
@@ -574,18 +574,21 @@ const GetSettingsOutput = {
574
574
  type: "object" as const,
575
575
  properties: {
576
576
  maxConcurrent: { type: "number" },
577
+ locale: { type: "string", enum: ["ru", "en"] },
577
578
  winterMode: { type: "boolean" },
578
579
  notifications: NotificationSettingsSchema,
579
580
  history: HistorySettingsSchema,
580
581
  audit: AuditSettingsSchema,
581
582
  },
582
- required: ["maxConcurrent", "winterMode", "notifications"],
583
+ required: ["maxConcurrent", "locale", "winterMode", "notifications"],
583
584
  } as const;
584
585
 
585
586
  const SaveSettingsInput = {
586
587
  type: "object" as const,
587
588
  properties: {
588
589
  maxConcurrent: { type: "number" },
590
+ /** Язык интерфейса (Спринт 28): ru по умолчанию, en — опционально. */
591
+ locale: { type: "string", enum: ["ru", "en"] },
589
592
  winterMode: { type: "boolean" },
590
593
  notifications: NotificationSettingsSchema,
591
594
  history: HistorySettingsSchema,
@@ -599,12 +602,13 @@ const SaveSettingsOutput = {
599
602
  properties: {
600
603
  success: { type: "boolean" },
601
604
  maxConcurrent: { type: "number" },
605
+ locale: { type: "string", enum: ["ru", "en"] },
602
606
  winterMode: { type: "boolean" },
603
607
  notifications: NotificationSettingsSchema,
604
608
  history: HistorySettingsSchema,
605
609
  audit: AuditSettingsSchema,
606
610
  },
607
- required: ["success", "maxConcurrent", "winterMode", "notifications"],
611
+ required: ["success", "maxConcurrent", "locale", "winterMode", "notifications"],
608
612
  } as const;
609
613
 
610
614
  const CleanupHistoryInput = {