opencode-windows-scheduler 1.5.0 → 1.5.2

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 (87) hide show
  1. package/CHANGELOG.md +47 -1
  2. package/LICENSE +21 -21
  3. package/README.md +24 -2
  4. package/ROADMAP-STRATEGY.md +16 -16
  5. package/ROADMAP.md +649 -160
  6. package/dist/core/audit.d.ts +27 -0
  7. package/dist/core/audit.d.ts.map +1 -1
  8. package/dist/core/audit.js +60 -0
  9. package/dist/core/dry-run.d.ts +10 -0
  10. package/dist/core/dry-run.d.ts.map +1 -1
  11. package/dist/core/dry-run.js +55 -34
  12. package/dist/core/git-trigger.d.ts.map +1 -1
  13. package/dist/core/git-trigger.js +15 -9
  14. package/dist/core/matrix.d.ts.map +1 -1
  15. package/dist/core/matrix.js +48 -22
  16. package/dist/core/ps-wrapper.d.ts +1 -1
  17. package/dist/core/ps-wrapper.d.ts.map +1 -1
  18. package/dist/core/ps-wrapper.js +47 -10
  19. package/dist/core/schedule-v2.d.ts.map +1 -1
  20. package/dist/core/schedule-v2.js +29 -17
  21. package/dist/core/scheduler/types.d.ts +6 -0
  22. package/dist/core/scheduler/types.d.ts.map +1 -1
  23. package/dist/core/scheduler/windows.d.ts +6 -2
  24. package/dist/core/scheduler/windows.d.ts.map +1 -1
  25. package/dist/core/scheduler/windows.js +25 -10
  26. package/dist/core/secrets.d.ts +10 -3
  27. package/dist/core/secrets.d.ts.map +1 -1
  28. package/dist/core/secrets.js +28 -4
  29. package/dist/core/telegram.d.ts.map +1 -1
  30. package/dist/core/telegram.js +13 -10
  31. package/dist/core/wrappers/bash.d.ts +1 -0
  32. package/dist/core/wrappers/bash.d.ts.map +1 -1
  33. package/dist/core/wrappers/bash.js +91 -5
  34. package/dist/i18n.d.ts +52 -0
  35. package/dist/i18n.d.ts.map +1 -0
  36. package/dist/i18n.js +292 -0
  37. package/dist/index.d.ts +6 -0
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +788 -183
  40. package/dist/notifications.d.ts.map +1 -1
  41. package/dist/notifications.js +74 -40
  42. package/dist/rpc.d.ts +15 -2
  43. package/dist/rpc.d.ts.map +1 -1
  44. package/dist/rpc.js +6 -2
  45. package/dist/server.d.ts.map +1 -1
  46. package/dist/server.js +89 -48
  47. package/dist/settings.d.ts +3 -0
  48. package/dist/settings.d.ts.map +1 -1
  49. package/dist/settings.js +20 -8
  50. package/dist/task-transfer.d.ts +13 -0
  51. package/dist/task-transfer.d.ts.map +1 -1
  52. package/dist/task-transfer.js +11 -0
  53. package/dist/types.d.ts +11 -0
  54. package/dist/types.d.ts.map +1 -1
  55. package/dist/types.js +32 -0
  56. package/dist/workspaces.d.ts +2 -2
  57. package/dist/workspaces.d.ts.map +1 -1
  58. package/dist/workspaces.js +6 -4
  59. package/docs/ARCHITECTURE.md +96 -4
  60. package/docs/FEATURES.md +34 -5
  61. package/docs/README.ru.md +17 -1
  62. package/gui-experimental.cjs +9 -9
  63. package/locales/en.json +695 -0
  64. package/locales/ru.json +695 -0
  65. package/package.json +6 -3
  66. package/scripts/test-locale.mjs +44 -0
  67. package/src/core/audit.ts +89 -0
  68. package/src/core/dry-run.ts +76 -38
  69. package/src/core/git-trigger.ts +15 -9
  70. package/src/core/matrix.ts +52 -26
  71. package/src/core/ps-wrapper.ts +47 -10
  72. package/src/core/schedule-v2.ts +47 -17
  73. package/src/core/scheduler/types.ts +6 -0
  74. package/src/core/scheduler/windows.ts +25 -10
  75. package/src/core/secrets.ts +34 -10
  76. package/src/core/telegram.ts +16 -10
  77. package/src/core/wrappers/bash.ts +112 -5
  78. package/src/gui.tsx +575 -480
  79. package/src/i18n.ts +339 -0
  80. package/src/index.ts +960 -193
  81. package/src/notifications.ts +83 -42
  82. package/src/rpc.ts +6 -2
  83. package/src/server.ts +89 -48
  84. package/src/settings.ts +38 -10
  85. package/src/task-transfer.ts +24 -0
  86. package/src/types.ts +37 -0
  87. package/src/workspaces.ts +9 -4
package/dist/index.js CHANGED
@@ -5,8 +5,8 @@ import { existsSync } from "node:fs";
5
5
  import fs from "node:fs/promises";
6
6
  import path from "node:path";
7
7
  import { LockManager } from "./core/lock.js";
8
- import { LOCK_DIR, LOG_DIR, PLUGIN_DIR, sanitizeName } from "./types.js";
9
- import { parseCron, buildScheduleGate, isValidIanaTimeZone, validateLaunchWindow, prevRun, normalizeActiveDays, activeWindowState, nextWindowOpenDelayMs } from "./core/schedule-v2.js";
8
+ import { LOCK_DIR, LOG_DIR, PLUGIN_DIR, STALE_LOCK_MAX_AGE_MS, WRAPPER_DIR, sanitizeName, validateTaskName, } from "./types.js";
9
+ import { parseCron, buildScheduleGate, isValidIanaTimeZone, validateLaunchWindow, prevRun, nextRun as cronNextRun, normalizeActiveDays, activeWindowState, nextWindowOpenDelayMs } from "./core/schedule-v2.js";
10
10
  import { buildLaunchdOneShotCleanup, normalizeOneShotRunAt, } from "./core/one-shot.js";
11
11
  import { generateSessionId, normalizeSessionMode, preservedSessionRunCount, } from "./core/session.js";
12
12
  import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath, requestImmediateRun } from "./core/ps-wrapper.js";
@@ -19,6 +19,7 @@ import { aggregateMatrixResults, cancelPendingMatrixClones, expandMatrixTask, fi
19
19
  import { SchedulerRpc } from "./rpc.js";
20
20
  import { latestHistoryByTask, loadHistory, loadMetrics } from "./history.js";
21
21
  import { loadSettings, saveSettings } from "./settings.js";
22
+ import { setLocale, t } from "./i18n.js";
22
23
  import { runHistoryRetention, maybeRunHistoryRetention } from "./core/retention.js";
23
24
  import { buildAnalytics } from "./core/analytics.js";
24
25
  import { getHistory, listRunningRecords } from "./db/history-repo.js";
@@ -33,10 +34,10 @@ import { DEFAULT_PROFILE, createProfile, deleteProfile, getProfileDir, getProfil
33
34
  import { closeDb, initDb } from "./db/index.js";
34
35
  import { migrateJsonToDb } from "./db/migrate.js";
35
36
  import { checkJsonBackups, recoverInterruptedRuns } from "./db/recovery.js";
36
- import { getTask, listMatrixClones, saveTask } from "./db/tasks-repo.js";
37
+ import { getTask, listMatrixClones, listTasks as listTaskDefinitions, saveTask } from "./db/tasks-repo.js";
37
38
  import { addWorkspace, deleteWorkspace, getWorkspace, listWorkspaces, updateWorkspace, validateWorkspacePath, readGitBranch, writeWorkspaceEnvFile, maskEnvForLog, } from "./workspaces.js";
38
- import { deleteSecret, hasSecret, listSecrets, setSecret, } from "./core/secrets.js";
39
- import { readAuditLog, recordAudit, } from "./core/audit.js";
39
+ import { deleteSecret, collectSecretNames, hasSecret, listSecrets, setSecret, } from "./core/secrets.js";
40
+ import { readAuditLog, recordAudit, recordTaskToolBlocks, } from "./core/audit.js";
40
41
  // Путь к вспомогательному node-скрипту записи истории/метрик (dist/core/record-history.js).
41
42
  const require = createRequire(import.meta.url);
42
43
  const resolvedRecorder = require.resolve("./core/record-history.js");
@@ -116,7 +117,9 @@ export const matrixSchema = z.object({
116
117
  });
117
118
  /** Zod-схема аргументов schedule_task */
118
119
  export const scheduleTaskSchema = z.object({
119
- name: z.string().describe("Unique task name (the plugin prefix is applied automatically)."),
120
+ name: z
121
+ .string()
122
+ .describe("Unique task name (the plugin prefix is applied automatically). Allowed: letters (including Cyrillic), digits, space, dot, underscore and hyphen."),
120
123
  schedule: z
121
124
  .string()
122
125
  .optional()
@@ -267,6 +270,10 @@ export const scheduleTaskSchema = z.object({
267
270
  .array(z.string())
268
271
  .optional()
269
272
  .describe("Role-scoped tool deny-list (takes precedence over allowedTools). Metadata-only."),
273
+ runWhenLoggedOff: z
274
+ .boolean()
275
+ .optional()
276
+ .describe("Windows only: run the task even when no user is logged on (/ru SYSTEM). The task runs in session 0 without the user's profile, mapped drives or saved credentials, so tasks that need the user's environment may fail. Creating such a task usually requires an elevated shell. Default false: interactive only — the task runs only while the user is logged on."),
270
277
  matrix: matrixSchema
271
278
  .optional()
272
279
  .describe("Matrix fan-out: the task becomes a template that is expanded into clones, one per workspace. The parent never runs itself. Cannot be combined with workspaceId."),
@@ -276,7 +283,7 @@ export const scheduleTaskSchema = z.object({
276
283
  ctx.addIssue({
277
284
  code: z.ZodIssueCode.custom,
278
285
  path: ["schedule"],
279
- message: "Для triggerType=cron нужно cron-выражение schedule.",
286
+ message: t("tool.error.cronSchedule"),
280
287
  });
281
288
  }
282
289
  if (trigger === "once" &&
@@ -285,21 +292,21 @@ export const scheduleTaskSchema = z.object({
285
292
  ctx.addIssue({
286
293
  code: z.ZodIssueCode.custom,
287
294
  path: ["runAt"],
288
- message: "Для triggerType=once нужен runAt (ISO-8601) или delaySeconds.",
295
+ message: t("tool.error.onceSchedule"),
289
296
  });
290
297
  }
291
298
  if (trigger === "once" && value.matrix) {
292
299
  ctx.addIssue({
293
300
  code: z.ZodIssueCode.custom,
294
301
  path: ["matrix"],
295
- message: "One-shot нельзя комбинировать с matrix: матрица запускается только вручную.",
302
+ message: t("tool.error.onceMatrixSchema"),
296
303
  });
297
304
  }
298
305
  if (trigger !== "once" && (value.runAt || value.delaySeconds !== undefined)) {
299
306
  ctx.addIssue({
300
307
  code: z.ZodIssueCode.custom,
301
308
  path: ["runAt"],
302
- message: "runAt/delaySeconds допустимы только при triggerType=once.",
309
+ message: t("tool.error.onceFields"),
303
310
  });
304
311
  }
305
312
  });
@@ -357,6 +364,10 @@ export const updateTaskSchema = z.object({
357
364
  .enum(["skip", "postpone", "run"])
358
365
  .optional()
359
366
  .describe("New behaviour outside the window: postpone (default), skip or run."),
367
+ runWhenLoggedOff: z
368
+ .boolean()
369
+ .optional()
370
+ .describe("Windows only: true runs the task without a logged-on user (/ru SYSTEM, session 0 without the user profile, mapped drives or saved credentials; usually requires an elevated shell). false/omitted keeps the task interactive-only."),
360
371
  watchGlobs: z
361
372
  .array(z.string())
362
373
  .optional()
@@ -462,14 +473,14 @@ export const updateTaskSchema = z.object({
462
473
  ctx.addIssue({
463
474
  code: z.ZodIssueCode.custom,
464
475
  path: ["runAt"],
465
- message: "runAt/delaySeconds допустимы только при triggerType=once.",
476
+ message: t("tool.error.onceFields"),
466
477
  });
467
478
  }
468
479
  if (value.triggerType === "once" && value.matrix) {
469
480
  ctx.addIssue({
470
481
  code: z.ZodIssueCode.custom,
471
482
  path: ["matrix"],
472
- message: "One-shot нельзя комбинировать с matrix.",
483
+ message: t("tool.error.onceMatrixUpdate"),
473
484
  });
474
485
  }
475
486
  });
@@ -522,12 +533,12 @@ const manageWorkspacesSchema = z.object({
522
533
  .record(z.string(), z.string())
523
534
  .nullable()
524
535
  .optional()
525
- .describe("Env-переменные workspace (ключ → значение). Переопределяют значения из envFile; секреты маскируются в логах (add/update)."),
536
+ .describe("Workspace environment variables (key → value). Override envFile values; secrets are masked in logs (add/update)."),
526
537
  envFile: z
527
538
  .string()
528
539
  .nullable()
529
540
  .optional()
530
- .describe("Путь к .env-файлу workspace (add/update, null — очистить)."),
541
+ .describe("Path to the workspace .env file (add/update, null clears it)."),
531
542
  });
532
543
  export const matrixControlSchema = z.object({
533
544
  action: z
@@ -585,6 +596,10 @@ export const manageSettingsSchema = z.object({
585
596
  .max(16)
586
597
  .optional()
587
598
  .describe("How many task runs may execute at the same time."),
599
+ locale: z
600
+ .enum(["ru", "en"])
601
+ .optional()
602
+ .describe("Interface language: ru (default) or en. Applies without restart."),
588
603
  winterMode: z
589
604
  .boolean()
590
605
  .optional()
@@ -725,9 +740,78 @@ function wrapExecute(fn) {
725
740
  }
726
741
  };
727
742
  }
743
+ /**
744
+ * Спринт 27.5.2: ближайший запуск по определению задачи, без чтения ОС.
745
+ *
746
+ * - `once` → `runAt` (запланированный момент);
747
+ * - пауза (`paused` или будущий `pausedUntil`) → null;
748
+ * - `cron` → ближайшее совпадение cron с учётом окна и дней недели:
749
+ * * `run` — окно игнорируется;
750
+ * * `skip` — ищем следующее совпадение внутри окна;
751
+ * * `postpone` (по умолчанию) — перенос на открытие окна, как в schedule-gate;
752
+ * - `file`/`git`/`mcp-event` → null (расписания нет).
753
+ */
754
+ function computeTaskNextRun(def, options = {}) {
755
+ if (!def)
756
+ return null;
757
+ if (options.paused)
758
+ return null;
759
+ const now = options.now ?? new Date();
760
+ if (def.pausedUntil) {
761
+ const until = Date.parse(def.pausedUntil);
762
+ if (Number.isFinite(until) && until > now.getTime())
763
+ return null;
764
+ }
765
+ const type = def.triggerType ?? "cron";
766
+ if (type === "once") {
767
+ if (!def.runAt)
768
+ return null;
769
+ const at = Date.parse(def.runAt);
770
+ return Number.isFinite(at) ? new Date(at).toISOString() : null;
771
+ }
772
+ if (type !== "cron")
773
+ return null;
774
+ const schedule = (def.schedule || "").trim();
775
+ if (!schedule)
776
+ return null;
777
+ const timeZone = def.timezone?.trim() || undefined;
778
+ const policy = def.windowPolicy === "skip" || def.windowPolicy === "run"
779
+ ? def.windowPolicy
780
+ : "postpone";
781
+ const windowOptions = {
782
+ notBefore: def.notBefore,
783
+ notAfter: def.notAfter,
784
+ days: Array.isArray(def.activeDays) ? def.activeDays : undefined,
785
+ timeZone,
786
+ };
787
+ let tick;
788
+ try {
789
+ tick = cronNextRun(schedule, now, timeZone);
790
+ }
791
+ catch {
792
+ // Некорректное выражение не должно ломать ответ инструмента.
793
+ return null;
794
+ }
795
+ // skip-политика может пропустить сколько угодно тиков вне окна;
796
+ // ограничение защищает от бесконечного перебора (5-летнее окно cron).
797
+ for (let guard = 0; tick && guard < 600; guard += 1) {
798
+ if (policy === "run")
799
+ return tick.toISOString();
800
+ const state = activeWindowState(tick, windowOptions);
801
+ if (state.active)
802
+ return tick.toISOString();
803
+ if (policy === "skip") {
804
+ tick = cronNextRun(schedule, tick, timeZone);
805
+ continue;
806
+ }
807
+ // postpone: gate ждёт открытия окна и запускает задачу тогда же.
808
+ return state.nextOpenAt ? state.nextOpenAt.toISOString() : null;
809
+ }
810
+ return null;
811
+ }
728
812
  /** schedule_task — создаёт задачу в schtasks через общий schedulerCreateTask. */
729
813
  const scheduleTaskExecute = wrapExecute(async (args) => {
730
- const { name, schedule, runAt, delaySeconds, prompt, timeoutSeconds, model, priority, beforeScript, afterScript, qualityGate, dependsOn, retryCount, retryDelay, nextTaskOnSuccess, nextTaskOnError, triggerType, mcpEvent, watchPath, workingDirectory, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, session, sessionMaxRuns, activeDays, windowPolicy, watchGlobs, watchIgnore, gitBranch, gitPaths, gitIgnore, gitPollSeconds, } = args;
814
+ const { name, schedule, runAt, delaySeconds, prompt, timeoutSeconds, model, priority, beforeScript, afterScript, qualityGate, dependsOn, retryCount, retryDelay, nextTaskOnSuccess, nextTaskOnError, triggerType, mcpEvent, watchPath, workingDirectory, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, session, sessionMaxRuns, activeDays, windowPolicy, watchGlobs, watchIgnore, gitBranch, gitPaths, gitIgnore, gitPollSeconds, runWhenLoggedOff, } = args;
731
815
  let effectiveRunAt;
732
816
  if ((triggerType ?? "cron") === "once") {
733
817
  const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
@@ -752,7 +836,9 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
752
836
  gitPaths,
753
837
  gitIgnore,
754
838
  gitPollSeconds,
755
- });
839
+ },
840
+ // Спринт 27.5.4: Windows — работать без входа (/ru SYSTEM).
841
+ runWhenLoggedOff === true);
756
842
  }
757
843
  catch (err) {
758
844
  return {
@@ -767,13 +853,31 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
767
853
  await refreshTriggers();
768
854
  const workspace = workspaceId ? getWorkspace(workspaceId) : undefined;
769
855
  const effectiveWorkdir = workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
856
+ // Спринт 27.5.2: отдаём ближайший запуск сразу, не дожидаясь обновления
857
+ // списка задач планировщика ОС (schtasks иногда отдаёт nextRunTime с задержкой).
858
+ const nextRun = computeTaskNextRun({
859
+ schedule: schedule ?? "",
860
+ triggerType: triggerType ?? "cron",
861
+ runAt: effectiveRunAt,
862
+ timezone,
863
+ notBefore,
864
+ notAfter,
865
+ activeDays,
866
+ windowPolicy,
867
+ });
770
868
  return {
771
869
  content: JSON.stringify({
772
870
  success: true,
773
- message: `Задача "${name}" успешно создана.`,
871
+ paused: false,
872
+ nextRun,
873
+ runWhenLoggedOff: runWhenLoggedOff === true,
874
+ message: t("tool.task.created", { name }),
774
875
  task: {
775
876
  name,
776
877
  schedule,
878
+ nextRun,
879
+ paused: false,
880
+ runWhenLoggedOff: runWhenLoggedOff === true,
777
881
  timeoutSeconds: timeoutSeconds ?? 3600,
778
882
  model: model?.trim() || null,
779
883
  priority: priority ?? 5,
@@ -804,21 +908,29 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
804
908
  });
805
909
  /** list_tasks — список задач плагина (та же логика, что и у get_tasks). */
806
910
  const listTasksExecute = wrapExecute(async () => {
807
- const tasks = await collectTasksView();
911
+ const { tasks, osAvailable, osError } = await collectTasksView();
808
912
  if (tasks.length === 0) {
809
913
  return {
810
914
  content: JSON.stringify({
811
915
  success: true,
812
- message: "Задачи плагина не найдены.",
916
+ message: osAvailable
917
+ ? t("tool.task.listEmpty")
918
+ : t("tool.task.listOsUnavailable"),
813
919
  tasks: [],
920
+ osAvailable,
921
+ ...(osError ? { osError } : {}),
814
922
  }),
815
923
  };
816
924
  }
817
925
  return {
818
926
  content: JSON.stringify({
819
927
  success: true,
820
- message: `Найдено задач: ${tasks.length}.`,
928
+ message: osAvailable
929
+ ? t("tool.task.found", { count: tasks.length })
930
+ : t("tool.task.foundOsUnavailable", { count: tasks.length }),
821
931
  tasks,
932
+ osAvailable,
933
+ ...(osError ? { osError } : {}),
822
934
  }),
823
935
  };
824
936
  });
@@ -831,7 +943,7 @@ const listTasksExecute = wrapExecute(async () => {
831
943
  async function cancelMatrixRun(name) {
832
944
  const definition = (await loadTaskDefinitions()).find((def) => def.name.toLowerCase() === name.trim().toLowerCase());
833
945
  if (!definition?.matrix) {
834
- throw new Error(`Задача "${name}" не является матрицей.`);
946
+ throw new Error(t("tool.error.matrixNotMatrix", { name }));
835
947
  }
836
948
  const result = await cancelPendingMatrixClones(definition.name);
837
949
  const warnings = [];
@@ -844,28 +956,38 @@ async function cancelMatrixRun(name) {
844
956
  await scheduler.deleteTask(clone.name);
845
957
  }
846
958
  catch (err) {
847
- warnings.push(`${clone.name}: не удалось остановить — ${err instanceof Error ? err.message : String(err)}`);
959
+ warnings.push(t("tool.matrix.stopFailed", {
960
+ clone: clone.name,
961
+ error: err instanceof Error ? err.message : String(err),
962
+ }));
848
963
  continue;
849
964
  }
850
965
  // Возвращаем placeholder-задачу, чтобы следующая fan-out-волна работала.
851
966
  try {
852
- await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, definition.name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil);
967
+ await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, definition.name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil, clone.runAt, clone.session, clone.sessionId, clone.sessionMaxRuns, undefined, clone.runWhenLoggedOff, clone.paused);
853
968
  }
854
969
  catch (err) {
855
- warnings.push(`${clone.name}: не удалось пересоздать — ${err instanceof Error ? err.message : String(err)}`);
970
+ warnings.push(t("tool.matrix.recreateFailed", {
971
+ clone: clone.name,
972
+ error: err instanceof Error ? err.message : String(err),
973
+ }));
856
974
  }
857
975
  }
858
976
  const parts = [
859
- `Матрица "${definition.name}": отменено ${result.cancelled.length} из ${result.aggregate.totalCount} клонов.`,
977
+ t("tool.matrix.cancelSummary", {
978
+ matrix: definition.name,
979
+ cancelled: result.cancelled.length,
980
+ total: result.aggregate.totalCount,
981
+ }),
860
982
  ];
861
983
  if (result.running.length > 0) {
862
- parts.push(`Остановлено выполнявшихся: ${result.running.length}.`);
984
+ parts.push(t("tool.matrix.cancelRunning", { count: result.running.length }));
863
985
  }
864
986
  if (result.alreadyFinished.length > 0) {
865
- parts.push(`Уже завершены и не тронуты: ${result.alreadyFinished.length}.`);
987
+ parts.push(t("tool.matrix.cancelFinished", { count: result.alreadyFinished.length }));
866
988
  }
867
989
  if (warnings.length > 0) {
868
- parts.push(`Предупреждения: ${warnings.join("; ")}.`);
990
+ parts.push(t("tool.matrix.cancelWarnings", { warnings: warnings.join("; ") }));
869
991
  }
870
992
  return {
871
993
  cancelled: result.cancelled,
@@ -905,6 +1027,87 @@ async function cleanupOrphanedMatrixTasks() {
905
1027
  * - удаление родителя-матрицы каскадно удаляет клоны и агрегатор;
906
1028
  * - удаление клона поодиночке запрещено (защита от «сирот» и вечного running).
907
1029
  */
1030
+ /**
1031
+ * Удаляет файлы-артефакты задачи (wrapper, prompt, log, lock, env).
1032
+ * Отсутствующие файлы игнорируются — операция идемпотентна.
1033
+ */
1034
+ async function removeTaskArtifacts(name) {
1035
+ const sanitized = sanitizeName(name);
1036
+ const candidates = [
1037
+ path.join(WRAPPER_DIR, `run-${sanitized}.cmd`),
1038
+ path.join(WRAPPER_DIR, `run-${sanitized}.sh`),
1039
+ path.join(PLUGIN_DIR, "prompts", `${sanitized}.txt`),
1040
+ path.join(LOG_DIR, `${sanitized}.log`),
1041
+ path.join(PLUGIN_DIR, "env", `${sanitized}.env`),
1042
+ path.join(LOCK_DIR, `${sanitized}.lock`),
1043
+ path.join(LOCK_DIR, `${sanitized}.lock.defer`),
1044
+ path.join(LOCK_DIR, `${sanitized}.lock.force`),
1045
+ ];
1046
+ await Promise.all(candidates.map((file) => fs.unlink(file).catch(() => undefined)));
1047
+ }
1048
+ /**
1049
+ * Сборщик мусора по wrapper-ам при старте: удаляет файлы задач, которых
1050
+ * больше нет ни в БД, ни в планировщике ОС. Активные (свежий lock) не трогает.
1051
+ */
1052
+ async function garbageCollectTaskArtifacts() {
1053
+ let entries;
1054
+ try {
1055
+ entries = await fs.readdir(WRAPPER_DIR);
1056
+ }
1057
+ catch {
1058
+ return;
1059
+ }
1060
+ const wrappers = entries.filter((file) => /^run-.+\.(cmd|sh)$/.test(file));
1061
+ if (wrappers.length === 0)
1062
+ return;
1063
+ const known = new Set();
1064
+ try {
1065
+ for (const task of listTaskDefinitions())
1066
+ known.add(sanitizeName(task.name));
1067
+ }
1068
+ catch {
1069
+ // БД может быть ещё не готова — тогда опираемся на ОС.
1070
+ }
1071
+ try {
1072
+ for (const task of await scheduler.listTasks()) {
1073
+ known.add(sanitizeName(task.taskName || ""));
1074
+ }
1075
+ }
1076
+ catch {
1077
+ // Планировщик недоступен — не удаляем ничего, чтобы не потерять данные.
1078
+ return;
1079
+ }
1080
+ let cleaned = 0;
1081
+ for (const file of wrappers) {
1082
+ const stem = file.replace(/^run-/, "").replace(/\.(cmd|sh)$/, "");
1083
+ const lockPath = path.join(LOCK_DIR, `${stem}.lock`);
1084
+ if (known.has(stem))
1085
+ continue;
1086
+ try {
1087
+ const stat = await fs.stat(lockPath);
1088
+ if (Date.now() - stat.mtimeMs < STALE_LOCK_MAX_AGE_MS)
1089
+ continue;
1090
+ }
1091
+ catch {
1092
+ // lock-файла нет — можно удалять.
1093
+ }
1094
+ const candidates = [
1095
+ path.join(WRAPPER_DIR, `run-${stem}.cmd`),
1096
+ path.join(WRAPPER_DIR, `run-${stem}.sh`),
1097
+ path.join(PLUGIN_DIR, "prompts", `${stem}.txt`),
1098
+ path.join(LOG_DIR, `${stem}.log`),
1099
+ path.join(PLUGIN_DIR, "env", `${stem}.env`),
1100
+ path.join(LOCK_DIR, `${stem}.lock`),
1101
+ path.join(LOCK_DIR, `${stem}.lock.defer`),
1102
+ path.join(LOCK_DIR, `${stem}.lock.force`),
1103
+ ];
1104
+ await Promise.all(candidates.map((pathToFile) => fs.unlink(pathToFile).catch(() => undefined)));
1105
+ cleaned += 1;
1106
+ }
1107
+ if (cleaned > 0) {
1108
+ console.log(`[gc] Вычищено мусорных файлов задач: ${cleaned}`);
1109
+ }
1110
+ }
908
1111
  async function deleteTaskWithFamily(name) {
909
1112
  const trimmed = name.trim();
910
1113
  const guard = getMatrixDeletionGuard(trimmed);
@@ -940,6 +1143,7 @@ async function deleteTaskWithFamily(name) {
940
1143
  catch {
941
1144
  // Не критично.
942
1145
  }
1146
+ removeTaskArtifacts(child);
943
1147
  removed.push(child);
944
1148
  }
945
1149
  }
@@ -950,6 +1154,7 @@ async function deleteTaskWithFamily(name) {
950
1154
  catch {
951
1155
  // Определения могло уже не быть — задача всё равно удалена из ОС.
952
1156
  }
1157
+ removeTaskArtifacts(trimmed);
953
1158
  return { removed, existed };
954
1159
  }
955
1160
  /** delete_task — удаление задачи по имени (/f) */
@@ -962,8 +1167,8 @@ const deleteTaskExecute = wrapExecute(async (args) => {
962
1167
  if (!existed && removed.length === 0) {
963
1168
  return {
964
1169
  content: JSON.stringify({
965
- success: false,
966
- error: `Задача "${name}" не найдена — удалять нечего.`,
1170
+ success: true,
1171
+ message: t("tool.task.alreadyAbsent", { name }),
967
1172
  }),
968
1173
  };
969
1174
  }
@@ -971,8 +1176,8 @@ const deleteTaskExecute = wrapExecute(async (args) => {
971
1176
  content: JSON.stringify({
972
1177
  success: true,
973
1178
  message: removed.length > 0
974
- ? `Матрица "${name}" удалена вместе с клонами: ${removed.join(", ")}.`
975
- : `Задача "${name}" успешно удалена.`,
1179
+ ? t("tool.task.matrixDeletedList", { name, list: removed.join(", ") })
1180
+ : t("tool.task.deleted", { name }),
976
1181
  }),
977
1182
  };
978
1183
  }
@@ -1005,8 +1210,8 @@ const runTaskNowExecute = wrapExecute(async (args) => {
1005
1210
  content: JSON.stringify({
1006
1211
  success: true,
1007
1212
  message: alreadyRunning
1008
- ? `Задача "${name}" уже выполняется.`
1009
- : `Задача "${name}" запущена.`,
1213
+ ? t("tool.task.alreadyRunning", { name })
1214
+ : t("tool.task.started", { name }),
1010
1215
  }),
1011
1216
  };
1012
1217
  });
@@ -1053,11 +1258,11 @@ async function removeMatrixChildrenFromScheduler(name) {
1053
1258
  async function updateTaskFromInput(input) {
1054
1259
  const name = input.name?.trim();
1055
1260
  if (!name) {
1056
- return { success: false, message: "Не передано имя задачи." };
1261
+ return { success: false, message: t("tool.error.taskNameMissing") };
1057
1262
  }
1058
1263
  const previous = getTask(name);
1059
1264
  if (!previous) {
1060
- return { success: false, message: `Задача "${name}" не найдена.` };
1265
+ return { success: false, message: t("tool.error.taskNotFound", { name }) };
1061
1266
  }
1062
1267
  const schedule = clearableString(input.schedule ?? input.newSchedule, previous.schedule);
1063
1268
  const prompt = clearableString(input.prompt ?? input.newPrompt, previous.prompt);
@@ -1068,13 +1273,13 @@ async function updateTaskFromInput(input) {
1068
1273
  if (triggerType === "cron" && !schedule) {
1069
1274
  return {
1070
1275
  success: false,
1071
- message: `Для обновления задачи "${name}" нужен cron-график.`,
1276
+ message: t("tool.error.updateCron", { name }),
1072
1277
  };
1073
1278
  }
1074
1279
  if (!prompt) {
1075
1280
  return {
1076
1281
  success: false,
1077
- message: `Для обновления задачи "${name}" нужен промпт.`,
1282
+ message: t("tool.error.updatePrompt", { name }),
1078
1283
  };
1079
1284
  }
1080
1285
  // One-shot: без нового runAt/delaySeconds сохраняем прежнее время.
@@ -1093,7 +1298,7 @@ async function updateTaskFromInput(input) {
1093
1298
  if (!normalized.ok) {
1094
1299
  return {
1095
1300
  success: false,
1096
- message: `Задача "${name}": ${normalized.error}`,
1301
+ message: t("tool.error.taskReason", { name, error: normalized.error }),
1097
1302
  };
1098
1303
  }
1099
1304
  runAt = normalized.runAt;
@@ -1106,7 +1311,7 @@ async function updateTaskFromInput(input) {
1106
1311
  if (!normalizedSession) {
1107
1312
  return {
1108
1313
  success: false,
1109
- message: `Задача "${name}": неизвестный режим сессии "${String(input.session)}".`,
1314
+ message: t("tool.error.sessionUnknown", { name, session: String(input.session) }),
1110
1315
  };
1111
1316
  }
1112
1317
  session = normalizedSession;
@@ -1119,7 +1324,7 @@ async function updateTaskFromInput(input) {
1119
1324
  (!Number.isInteger(sessionMaxRuns) || sessionMaxRuns < 1)) {
1120
1325
  return {
1121
1326
  success: false,
1122
- message: `Задача "${name}": sessionMaxRuns должен быть целым числом ≥ 1.`,
1327
+ message: t("tool.error.sessionMaxRuns", { name }),
1123
1328
  };
1124
1329
  }
1125
1330
  let sessionId = previous.sessionId;
@@ -1134,8 +1339,7 @@ async function updateTaskFromInput(input) {
1134
1339
  if (triggerType === "once" && matrixNext) {
1135
1340
  return {
1136
1341
  success: false,
1137
- message: `Задача "${name}": one-shot нельзя комбинировать с matrix. ` +
1138
- `Запустите матрицу вручную или используйте cron/file-триггер.`,
1342
+ message: t("tool.error.oneShotMatrix", { name }),
1139
1343
  };
1140
1344
  }
1141
1345
  // Спринт 27: параметры триггеров сохраняются, если поле не передано.
@@ -1162,13 +1366,19 @@ async function updateTaskFromInput(input) {
1162
1366
  gitIgnore: mergeStringList(input.gitIgnore, previous.gitIgnore),
1163
1367
  gitPollSeconds: input.gitPollSeconds ?? previous.gitPollSeconds,
1164
1368
  };
1369
+ // Спринт 27.5.8: update = пересоздание задачи, поэтому паузу нужно вернуть
1370
+ // после create — иначе задача молча начинает выполняться по расписанию.
1371
+ const wasPaused = Boolean(previous.paused === true ||
1372
+ (previous.pausedUntil && Date.parse(previous.pausedUntil) > Date.now()));
1373
+ let previousDeleted = false;
1165
1374
  try {
1166
1375
  // Обновление = пересоздание в планировщике с сохранением старых значений.
1167
1376
  await scheduler.deleteTask(name);
1377
+ previousDeleted = true;
1168
1378
  await schedulerCreateTask(name, schedule ?? "", prompt, input.timeoutSeconds ?? previous.timeoutSeconds, clearableString(input.workingDirectory, previous.workingDirectory), input.retryCount ?? previous.retryCount, input.retryDelay ?? previous.retryDelay, clearableString(input.qualityGate, previous.qualityGate), clearableString(input.nextTaskOnSuccess, previous.nextTaskOnSuccess), clearableString(input.nextTaskOnError, previous.nextTaskOnError), triggerType, clearableString(input.watchPath, previous.watchPath), clearableList(input.dependsOn, previous.dependsOn), clearableString(input.model, previous.model), input.priority ?? previous.priority, clearableString(input.beforeScript, previous.beforeScript), clearableString(input.afterScript, previous.afterScript), input.mcpEvent ?? previous.mcpEvent, clearableString(input.workspaceId, previous.workspaceId), clearableList(input.allowedTools, previous.allowedTools), clearableList(input.deniedTools, previous.deniedTools), matrixNext, undefined,
1169
1379
  // Если задача была матрицей — синхронизируем клонов, а не
1170
1380
  // пересоздаём их с нуля (Спринт 17).
1171
- matrixWas && matrixNext ? "sync" : "create", timezone, notBefore, notAfter, previous.pausedUntil, runAt, session, sessionId, sessionMaxRuns, triggerExtras);
1381
+ matrixWas && matrixNext ? "sync" : "create", timezone, notBefore, notAfter, previous.pausedUntil, runAt, session, sessionId, sessionMaxRuns, triggerExtras, input.runWhenLoggedOff ?? previous.runWhenLoggedOff, wasPaused);
1172
1382
  // Матрица отключена при обновлении — убираем клонов и агрегатор.
1173
1383
  if (matrixWas && !matrixNext) {
1174
1384
  await removeMatrixChildrenFromScheduler(name);
@@ -1176,14 +1386,59 @@ async function updateTaskFromInput(input) {
1176
1386
  // Пересоздание могло изменить triggerType/watchPath — сразу
1177
1387
  // пересобираем набор файловых watcher-ов.
1178
1388
  await refreshTriggers();
1179
- return { success: true, message: `Задача "${name}" обновлена.` };
1180
- }
1181
- catch (err) {
1389
+ // Спринт 27.5.2: после пересоздания задачи сообщаем ближайший запуск,
1390
+ // рассчитанный из нового определения, не дожидаясь ОС.
1391
+ const updated = getTask(name);
1392
+ const paused = wasPaused;
1182
1393
  return {
1183
- success: false,
1184
- message: err instanceof Error ? err.message : String(err),
1394
+ success: true,
1395
+ paused,
1396
+ nextRun: computeTaskNextRun(updated, { paused }),
1397
+ message: t("tool.task.updated", { name }),
1185
1398
  };
1186
1399
  }
1400
+ catch (err) {
1401
+ const cause = err instanceof Error ? err.message : String(err);
1402
+ // Спринт 27.5.6: задача удалена из ОС, но новую версию создать не удалось.
1403
+ if (!previousDeleted) {
1404
+ return {
1405
+ success: false,
1406
+ restored: true,
1407
+ message: t("tool.task.rollbackKept", { cause }),
1408
+ };
1409
+ }
1410
+ // Убираем возможный частичный результат новой попытки: обёртка могла
1411
+ // успеть зарегистрироваться, хотя create вернул ошибку.
1412
+ try {
1413
+ await scheduler.deleteTask(name);
1414
+ }
1415
+ catch {
1416
+ // Задачи могло не быть — это ожидаемо.
1417
+ }
1418
+ // Определение в БД ещё не перезаписано, поэтому восстанавливаем ровно
1419
+ // прежнюю версию: расписание, промпт, обёртку и паузу.
1420
+ try {
1421
+ await recreateTaskFromDefinition(previous);
1422
+ await refreshTriggers().catch(() => undefined);
1423
+ return {
1424
+ success: false,
1425
+ restored: true,
1426
+ message: t("tool.task.rollbackRestored", { cause }),
1427
+ };
1428
+ }
1429
+ catch (restoreErr) {
1430
+ const restoreMessage = restoreErr instanceof Error ? restoreErr.message : String(restoreErr);
1431
+ return {
1432
+ success: false,
1433
+ restored: false,
1434
+ message: t("tool.task.rollbackFailed", {
1435
+ cause,
1436
+ restore: restoreMessage,
1437
+ name,
1438
+ }),
1439
+ };
1440
+ }
1441
+ }
1187
1442
  }
1188
1443
  /** update_task — частичное обновление существующей задачи. */
1189
1444
  const updateTaskExecute = wrapExecute(async (args) => {
@@ -1200,9 +1455,12 @@ async function pauseOrResumeTask(name, paused, until) {
1200
1455
  if (!definition) {
1201
1456
  return {
1202
1457
  success: false,
1203
- message: `Задача "${trimmed}" не найдена.`,
1458
+ message: t("tool.error.taskNotFound", { name: trimmed }),
1204
1459
  affected: [],
1205
1460
  warnings: [],
1461
+ paused,
1462
+ nextRun: null,
1463
+ pausedUntil: null,
1206
1464
  };
1207
1465
  }
1208
1466
  // Пауза до даты (Спринт 19): проверяем ISO-момент до каких-либо изменений.
@@ -1212,17 +1470,23 @@ async function pauseOrResumeTask(name, paused, until) {
1212
1470
  if (Number.isNaN(parsed)) {
1213
1471
  return {
1214
1472
  success: false,
1215
- message: `Задача "${trimmed}": некорректная дата паузы "${until}". Нужен ISO-момент, например 2026-12-01T09:00:00Z.`,
1473
+ message: t("tool.error.pauseDateInvalid", { name: trimmed, until }),
1216
1474
  affected: [],
1217
1475
  warnings: [],
1476
+ paused,
1477
+ nextRun: null,
1478
+ pausedUntil: definition.pausedUntil ?? null,
1218
1479
  };
1219
1480
  }
1220
1481
  if (parsed <= Date.now()) {
1221
1482
  return {
1222
1483
  success: false,
1223
- message: `Задача "${trimmed}": дата паузы уже прошла.`,
1484
+ message: t("tool.error.pauseDatePast", { name: trimmed }),
1224
1485
  affected: [],
1225
1486
  warnings: [],
1487
+ paused,
1488
+ nextRun: null,
1489
+ pausedUntil: definition.pausedUntil ?? null,
1226
1490
  };
1227
1491
  }
1228
1492
  pausedUntil = new Date(parsed).toISOString();
@@ -1233,9 +1497,12 @@ async function pauseOrResumeTask(name, paused, until) {
1233
1497
  if (targets.length === 0 && definition.matrix) {
1234
1498
  return {
1235
1499
  success: false,
1236
- message: `У матрицы "${trimmed}" нет клонов.`,
1500
+ message: t("tool.error.matrixNoClones", { name: trimmed }),
1237
1501
  affected: [],
1238
1502
  warnings: [],
1503
+ paused,
1504
+ nextRun: null,
1505
+ pausedUntil: definition.pausedUntil ?? null,
1239
1506
  };
1240
1507
  }
1241
1508
  const affected = [];
@@ -1254,37 +1521,65 @@ async function pauseOrResumeTask(name, paused, until) {
1254
1521
  warnings.push(`${target}: ${err instanceof Error ? err.message : String(err)}`);
1255
1522
  }
1256
1523
  }
1257
- // Фиксируем (или снимаем) автопродолжение в определении задачи. У матрицы
1524
+ // Фиксируем (или снимаем) паузу в определении задачи. У матрицы
1258
1525
  // родитель хранит pausedUntil за всех клонов — их включает авто-resume.
1526
+ // Спринт 27.5.8: бессрочная пауза тоже сохраняется в определении, иначе
1527
+ // update_task пересоздаёт задачу включённой и пауза теряется.
1259
1528
  const definitionUpdates = paused
1260
- ? pausedUntil
1261
- ? { pausedUntil }
1262
- : undefined
1263
- : definition.pausedUntil
1264
- ? { pausedUntil: undefined }
1529
+ ? { paused: true, ...(pausedUntil ? { pausedUntil } : {}) }
1530
+ : definition.paused || definition.pausedUntil
1531
+ ? { paused: false, pausedUntil: undefined }
1265
1532
  : undefined;
1266
1533
  if (definitionUpdates && affected.length > 0) {
1267
1534
  try {
1268
1535
  saveTask({ ...definition, ...definitionUpdates });
1269
1536
  }
1270
1537
  catch (err) {
1271
- warnings.push(`не удалось сохранить автопродолжение: ${err instanceof Error ? err.message : String(err)}`);
1538
+ warnings.push(t("tool.task.autosave", {
1539
+ error: err instanceof Error ? err.message : String(err),
1540
+ }));
1272
1541
  }
1273
1542
  }
1274
1543
  const untilText = pausedUntil
1275
- ? ` до ${new Date(pausedUntil).toLocaleString()}`
1544
+ ? t("tool.task.until", { date: new Date(pausedUntil).toLocaleString() })
1276
1545
  : "";
1277
- const verb = paused ? "поставлена на паузу" : "возобновлена";
1546
+ const verb = paused ? t("tool.task.paused") : t("tool.task.resumed");
1278
1547
  const message = definition.matrix
1279
- ? `Матрица "${trimmed}" ${verb}${untilText}: ${affected.length} из ${targets.length} клонов.` +
1280
- (warnings.length > 0 ? ` Ошибки: ${warnings.join("; ")}.` : "")
1281
- : `Задача "${trimmed}" ${verb}${untilText}.` +
1282
- (warnings.length > 0 ? ` Ошибка: ${warnings.join("; ")}.` : "");
1548
+ ? t("tool.task.matrixPaused", {
1549
+ name: trimmed,
1550
+ verb,
1551
+ until: untilText,
1552
+ affected: affected.length,
1553
+ total: targets.length,
1554
+ }) +
1555
+ (warnings.length > 0
1556
+ ? t("tool.task.matrixPauseErrors", { warnings: warnings.join("; ") })
1557
+ : "")
1558
+ : t("tool.task.pausedText", {
1559
+ name: trimmed,
1560
+ verb,
1561
+ until: untilText,
1562
+ }) +
1563
+ (warnings.length > 0
1564
+ ? t("tool.task.pauseError", { warnings: warnings.join("; ") })
1565
+ : "");
1566
+ // Спринт 27.5.2: состояние и ближайший запуск считаем из определения —
1567
+ // schtasks после /change (особенно /enable) отдаёт nextRunTime с задержкой.
1568
+ const effectivePausedUntil = paused
1569
+ ? pausedUntil ?? definition.pausedUntil ?? null
1570
+ : null;
1571
+ const after = definitionUpdates
1572
+ ? { ...definition, ...definitionUpdates }
1573
+ : { ...definition, paused: false, pausedUntil: undefined };
1574
+ const nextRun = paused ? null : computeTaskNextRun(after);
1283
1575
  return {
1284
1576
  success: warnings.length === 0,
1285
1577
  message,
1286
1578
  affected,
1287
1579
  warnings,
1580
+ paused,
1581
+ nextRun,
1582
+ pausedUntil: effectivePausedUntil,
1288
1583
  };
1289
1584
  }
1290
1585
  const pauseTaskExecute = wrapExecute(async (args) => {
@@ -1322,7 +1617,11 @@ async function resumeExpiredPauses() {
1322
1617
  for (const target of targets) {
1323
1618
  await scheduler.resumeTask(target);
1324
1619
  }
1325
- await saveTaskDefinition({ ...definition, pausedUntil: undefined });
1620
+ await saveTaskDefinition({
1621
+ ...definition,
1622
+ pausedUntil: undefined,
1623
+ paused: false,
1624
+ });
1326
1625
  console.log(`[windows-scheduler] Автопродолжение: задача "${definition.name}" включена (пауза истекла).`);
1327
1626
  }
1328
1627
  catch (err) {
@@ -1476,7 +1775,7 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
1476
1775
  return {
1477
1776
  content: JSON.stringify({
1478
1777
  success: false,
1479
- error: "Для action=add нужен path.",
1778
+ error: t("tool.workspace.needPath"),
1480
1779
  }),
1481
1780
  };
1482
1781
  }
@@ -1503,7 +1802,7 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
1503
1802
  return {
1504
1803
  content: JSON.stringify({
1505
1804
  success: false,
1506
- error: "Для action=update нужен id.",
1805
+ error: t("tool.workspace.needUpdateId"),
1507
1806
  }),
1508
1807
  };
1509
1808
  }
@@ -1518,7 +1817,7 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
1518
1817
  return {
1519
1818
  content: JSON.stringify({
1520
1819
  success: false,
1521
- error: "Workspace не найден.",
1820
+ error: t("tool.workspace.notFound"),
1522
1821
  }),
1523
1822
  };
1524
1823
  }
@@ -1542,7 +1841,7 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
1542
1841
  return {
1543
1842
  content: JSON.stringify({
1544
1843
  success: false,
1545
- error: "Для action=delete нужен id.",
1844
+ error: t("tool.workspace.needDeleteId"),
1546
1845
  }),
1547
1846
  };
1548
1847
  }
@@ -1551,8 +1850,8 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
1551
1850
  content: JSON.stringify({
1552
1851
  success: deleted,
1553
1852
  message: deleted
1554
- ? "Workspace удалён. Задачи сохранены, привязка очищена."
1555
- : "Workspace не найден.",
1853
+ ? t("tool.workspace.deleted")
1854
+ : t("tool.workspace.notFound"),
1556
1855
  }),
1557
1856
  };
1558
1857
  }
@@ -1598,8 +1897,8 @@ const matrixControlExecute = wrapExecute(async (args) => {
1598
1897
  content: JSON.stringify({
1599
1898
  success: true,
1600
1899
  message: removed.length > 0
1601
- ? `Удалено осиротевших задач: ${removed.length}.`
1602
- : "Осиротевших задач не найдено.",
1900
+ ? t("tool.matrix.orphansRemoved", { count: removed.length })
1901
+ : t("tool.matrix.orphansNone"),
1603
1902
  removed,
1604
1903
  }),
1605
1904
  };
@@ -1609,7 +1908,7 @@ const matrixControlExecute = wrapExecute(async (args) => {
1609
1908
  return {
1610
1909
  content: JSON.stringify({
1611
1910
  success: false,
1612
- error: `Для action=${args.action} нужен name матрицы.`,
1911
+ error: t("tool.matrix.actionName", { action: args.action }),
1613
1912
  }),
1614
1913
  };
1615
1914
  }
@@ -1673,6 +1972,7 @@ const manageSettingsExecute = wrapExecute(async (args) => {
1673
1972
  return { content: JSON.stringify({ success: true, settings: current }) };
1674
1973
  }
1675
1974
  if (args.maxConcurrent === undefined &&
1975
+ args.locale === undefined &&
1676
1976
  args.winterMode === undefined &&
1677
1977
  args.notifications === undefined &&
1678
1978
  args.history === undefined &&
@@ -1681,19 +1981,22 @@ const manageSettingsExecute = wrapExecute(async (args) => {
1681
1981
  return {
1682
1982
  content: JSON.stringify({
1683
1983
  success: false,
1684
- error: "Для action=update передайте хотя бы одно поле: maxConcurrent, winterMode, notifications, history, integrations или audit.",
1984
+ error: t("tool.settings.updateFields"),
1685
1985
  settings: current,
1686
1986
  }),
1687
1987
  };
1688
1988
  }
1689
1989
  const settings = await saveSettings({
1690
1990
  maxConcurrent: args.maxConcurrent,
1991
+ locale: args.locale,
1691
1992
  winterMode: args.winterMode,
1692
1993
  notifications: args.notifications,
1693
1994
  history: args.history,
1694
1995
  integrations: args.integrations,
1695
1996
  audit: args.audit,
1696
1997
  });
1998
+ // Локаль процесса меняется сразу — перезапуск плагина не нужен.
1999
+ setLocale(settings.locale);
1697
2000
  return { content: JSON.stringify({ success: true, settings }) };
1698
2001
  });
1699
2002
  /** manage_templates — список, сохранение и удаление шаблонов задач. */
@@ -1704,7 +2007,7 @@ const manageTemplatesExecute = wrapExecute(async (args) => {
1704
2007
  if (args.action === "delete") {
1705
2008
  const id = args.id?.trim();
1706
2009
  if (!id) {
1707
- return { content: JSON.stringify({ success: false, error: "Для action=delete нужен id шаблона." }) };
2010
+ return { content: JSON.stringify({ success: false, error: t("tool.template.needDeleteId") }) };
1708
2011
  }
1709
2012
  const before = await loadTemplates();
1710
2013
  const existed = before.some((template) => template.id === id);
@@ -1712,7 +2015,9 @@ const manageTemplatesExecute = wrapExecute(async (args) => {
1712
2015
  return {
1713
2016
  content: JSON.stringify({
1714
2017
  success: existed,
1715
- message: existed ? `Шаблон ${id} удалён.` : `Шаблон ${id} не найден.`,
2018
+ message: existed
2019
+ ? t("tool.template.deleted", { id })
2020
+ : t("tool.template.notFound", { id }),
1716
2021
  }),
1717
2022
  };
1718
2023
  }
@@ -1721,7 +2026,7 @@ const manageTemplatesExecute = wrapExecute(async (args) => {
1721
2026
  return {
1722
2027
  content: JSON.stringify({
1723
2028
  success: false,
1724
- error: "Для action=save нужны непустые name и prompt.",
2029
+ error: t("tool.template.saveRequired"),
1725
2030
  }),
1726
2031
  };
1727
2032
  }
@@ -1745,7 +2050,7 @@ const manageProfilesExecute = wrapExecute(async (args) => {
1745
2050
  return {
1746
2051
  content: JSON.stringify({
1747
2052
  success: false,
1748
- error: `Для action=${args.action} нужно имя профиля.`,
2053
+ error: t("tool.profile.nameRequired", { action: args.action }),
1749
2054
  }),
1750
2055
  };
1751
2056
  }
@@ -1755,7 +2060,7 @@ const manageProfilesExecute = wrapExecute(async (args) => {
1755
2060
  return {
1756
2061
  content: JSON.stringify({
1757
2062
  success: true,
1758
- message: `Профиль "${meta.name}" создан (порт дашборда ${meta.port}).`,
2063
+ message: t("tool.profile.created", { name: meta.name, port: meta.port }),
1759
2064
  profile: profile ?? {
1760
2065
  name: meta.name,
1761
2066
  dir: getProfileDir(meta.name),
@@ -1775,8 +2080,8 @@ const manageProfilesExecute = wrapExecute(async (args) => {
1775
2080
  current,
1776
2081
  restartRequired: true,
1777
2082
  message: isProfilePinnedByEnv()
1778
- ? `Профиль задан переменной OPENCODE_SCHEDULER_PROFILE=${current}. Перезапустите OpenCode.`
1779
- : `Активный профиль: ${sanitizeProfileName(name)}. Перезапустите OpenCode, чтобы применить изменения.`,
2083
+ ? t("tool.profile.envVar", { name: current })
2084
+ : t("tool.profile.active", { name: sanitizeProfileName(name) }),
1780
2085
  }),
1781
2086
  };
1782
2087
  }
@@ -1785,8 +2090,8 @@ const manageProfilesExecute = wrapExecute(async (args) => {
1785
2090
  content: JSON.stringify({
1786
2091
  success: removed,
1787
2092
  message: removed
1788
- ? `Профиль "${sanitizeProfileName(name)}" удалён вместе с его БД и настройками.`
1789
- : "Профиль не найден.",
2093
+ ? t("tool.profile.deleted", { name: sanitizeProfileName(name) })
2094
+ : t("tool.profile.notFound"),
1790
2095
  }),
1791
2096
  };
1792
2097
  });
@@ -1798,14 +2103,14 @@ const transferTasksExecute = wrapExecute(async (args) => {
1798
2103
  return { content: JSON.stringify({ success: true, data, count }) };
1799
2104
  }
1800
2105
  if (!args.data) {
1801
- return { content: JSON.stringify({ success: false, error: "Для action=import нужны данные экспорта." }) };
2106
+ return { content: JSON.stringify({ success: false, error: t("tool.transfer.importData") }) };
1802
2107
  }
1803
2108
  const parsed = parseImportJson(args.data);
1804
2109
  if (parsed.tasks.length === 0) {
1805
2110
  return {
1806
2111
  content: JSON.stringify({
1807
2112
  success: false,
1808
- error: "В данных нет задач для импорта.",
2113
+ error: t("tool.transfer.noTasks"),
1809
2114
  errors: parsed.errors,
1810
2115
  }),
1811
2116
  };
@@ -1859,7 +2164,12 @@ const cleanupHistoryExecute = wrapExecute(async (args) => {
1859
2164
  success: true,
1860
2165
  message: report.skipped
1861
2166
  ? report.skipped
1862
- : `Удалено ${report.deleted} записей (по возрасту: ${report.deletedByAge}, по лимиту: ${report.deletedByCount}), осталось ${report.kept}.`,
2167
+ : t("tool.history.cleaned", {
2168
+ deleted: report.deleted,
2169
+ byAge: report.deletedByAge,
2170
+ byCount: report.deletedByCount,
2171
+ kept: report.kept,
2172
+ }),
1863
2173
  report,
1864
2174
  }),
1865
2175
  };
@@ -1868,7 +2178,7 @@ const cleanupHistoryExecute = wrapExecute(async (args) => {
1868
2178
  const emitEventExecute = wrapExecute(async (args) => {
1869
2179
  const eventName = args.eventName?.trim();
1870
2180
  if (!eventName) {
1871
- return { content: JSON.stringify({ success: false, error: "Не передано имя события." }) };
2181
+ return { content: JSON.stringify({ success: false, error: t("tool.event.nameRequired") }) };
1872
2182
  }
1873
2183
  const payload = args.payload ?? {};
1874
2184
  const definitions = await loadTaskDefinitions();
@@ -1891,8 +2201,8 @@ const emitEventExecute = wrapExecute(async (args) => {
1891
2201
  content: JSON.stringify({
1892
2202
  success: true,
1893
2203
  message: triggered.length > 0
1894
- ? `Запущено задач: ${triggered.length}.`
1895
- : `Нет задач, подписанных на событие "${eventName}".`,
2204
+ ? t("tool.event.triggered", { count: triggered.length })
2205
+ : t("tool.event.none", { event: eventName }),
1896
2206
  triggered,
1897
2207
  }),
1898
2208
  };
@@ -1907,7 +2217,7 @@ const manageSecretsExecute = wrapExecute(async (args) => {
1907
2217
  return {
1908
2218
  content: JSON.stringify({
1909
2219
  success: false,
1910
- error: "Для set/delete нужно имя секрета.",
2220
+ error: t("tool.secret.nameRequired"),
1911
2221
  }),
1912
2222
  };
1913
2223
  }
@@ -1918,8 +2228,8 @@ const manageSecretsExecute = wrapExecute(async (args) => {
1918
2228
  content: JSON.stringify({
1919
2229
  success: existed,
1920
2230
  message: existed
1921
- ? `Секрет ${name} удалён.`
1922
- : `Секрет ${name} не найден.`,
2231
+ ? t("tool.secret.deleted", { name })
2232
+ : t("tool.secret.notFound", { name }),
1923
2233
  }),
1924
2234
  };
1925
2235
  }
@@ -1928,7 +2238,7 @@ const manageSecretsExecute = wrapExecute(async (args) => {
1928
2238
  return {
1929
2239
  content: JSON.stringify({
1930
2240
  success: false,
1931
- error: "Для action=set нужно непустое значение value.",
2241
+ error: t("tool.secret.valueRequired"),
1932
2242
  }),
1933
2243
  };
1934
2244
  }
@@ -1936,7 +2246,7 @@ const manageSecretsExecute = wrapExecute(async (args) => {
1936
2246
  return {
1937
2247
  content: JSON.stringify({
1938
2248
  success: true,
1939
- message: `Секрет ${item.name} сохранён в зашифрованном виде.`,
2249
+ message: t("tool.secret.saved", { name: item.name }),
1940
2250
  secret: item,
1941
2251
  }),
1942
2252
  };
@@ -2153,6 +2463,14 @@ export default Plugin.define({
2153
2463
  // Папка проекта — рабочая директория задач по умолчанию. Благодаря ей
2154
2464
  // `opencode run` подхватывает opencode.json с MCP-серверами проекта.
2155
2465
  projectDirectory = ctx.location?.directory || process.cwd();
2466
+ // Спринт 28: язык интерфейса берём из настроек. Ошибка чтения не должна
2467
+ // мешать старту — в этом случае остаётся локаль по умолчанию (ru).
2468
+ try {
2469
+ setLocale((await loadSettings()).locale);
2470
+ }
2471
+ catch {
2472
+ // Локаль по умолчанию уже активна.
2473
+ }
2156
2474
  // Спринт 12: SQLite — основное хранилище. Открываем БД, при первом запуске
2157
2475
  // автоматически переносим данные из JSON, затем восстанавливаем прерванные
2158
2476
  // запуски. Ошибки миграции не должны мешать плагину стартовать.
@@ -2170,6 +2488,9 @@ export default Plugin.define({
2170
2488
  console.error(`[recovery] Не удалось восстановить незавершённые запуски: ${err instanceof Error ? err.message : String(err)}`);
2171
2489
  }
2172
2490
  checkJsonBackups();
2491
+ void garbageCollectTaskArtifacts().catch((err) => {
2492
+ console.log(`[gc] Не удалось вычистить мусорные файлы: ${err instanceof Error ? err.message : String(err)}`);
2493
+ });
2173
2494
  // Спринт 18: ежедневная очистка истории. Ошибка ретеншна не должна мешать
2174
2495
  // плагину стартовать — пишем в лог и продолжаем.
2175
2496
  void maybeRunHistoryRetention()
@@ -2518,16 +2839,21 @@ export default Plugin.define({
2518
2839
  // schedule_task и create_task использовали один и тот же путь.
2519
2840
  const rpcHandlers = {
2520
2841
  get_tasks: async () => {
2521
- return { tasks: await collectTasksView() };
2842
+ const view = await collectTasksView();
2843
+ return {
2844
+ tasks: view.tasks,
2845
+ osAvailable: view.osAvailable,
2846
+ ...(view.osError ? { osError: view.osError } : {}),
2847
+ };
2522
2848
  },
2523
2849
  create_task: async (input) => {
2524
2850
  console.log("[windows-scheduler] create_task input:", input);
2525
- const { name, schedule, prompt, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, dependsOn, triggerType, watchPath, workingDirectory, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, runAt, delaySeconds, session, sessionMaxRuns, } = input;
2851
+ const { name, schedule, prompt, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, dependsOn, triggerType, watchPath, workingDirectory, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, runAt, delaySeconds, session, sessionMaxRuns, runWhenLoggedOff, } = input;
2526
2852
  let effectiveRunAt;
2527
2853
  if (triggerType === "once") {
2528
2854
  const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
2529
2855
  if (!normalized.ok) {
2530
- return { success: false, message: `Задача "${name}": ${normalized.error}` };
2856
+ return { success: false, message: t("tool.error.taskReason", { name, error: normalized.error }) };
2531
2857
  }
2532
2858
  effectiveRunAt = normalized.runAt;
2533
2859
  }
@@ -2535,18 +2861,31 @@ export default Plugin.define({
2535
2861
  if (session !== undefined) {
2536
2862
  const normalizedSession = normalizeSessionMode(session);
2537
2863
  if (!normalizedSession) {
2538
- return { success: false, message: `Задача "${name}": неизвестный режим сессии "${String(session)}".` };
2864
+ return { success: false, message: t("tool.error.sessionUnknown", { name, session: String(session) }) };
2539
2865
  }
2540
2866
  effectiveSession = normalizedSession;
2541
2867
  }
2542
2868
  if (sessionMaxRuns !== undefined &&
2543
2869
  (!Number.isInteger(sessionMaxRuns) || sessionMaxRuns < 1)) {
2544
- return { success: false, message: `Задача "${name}": sessionMaxRuns должен быть целым числом ≥ 1.` };
2870
+ return { success: false, message: t("tool.error.sessionMaxRuns", { name }) };
2545
2871
  }
2546
2872
  const effectiveSessionId = effectiveSession === "reuse" ? generateSessionId() : undefined;
2547
2873
  try {
2548
- await schedulerCreateTask(name, schedule ?? "", prompt, undefined, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, undefined, "create", timezone, notBefore, notAfter, undefined, effectiveRunAt, effectiveSession, effectiveSessionId, sessionMaxRuns);
2549
- return { success: true, message: `Задача "${name}" успешно создана.` };
2874
+ await schedulerCreateTask(name, schedule ?? "", prompt, undefined, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, undefined, "create", timezone, notBefore, notAfter, undefined, effectiveRunAt, effectiveSession, effectiveSessionId, sessionMaxRuns, undefined, runWhenLoggedOff === true);
2875
+ const nextRun = computeTaskNextRun({
2876
+ schedule: schedule ?? "",
2877
+ triggerType: triggerType ?? "cron",
2878
+ runAt: effectiveRunAt,
2879
+ timezone,
2880
+ notBefore,
2881
+ notAfter,
2882
+ });
2883
+ return {
2884
+ success: true,
2885
+ paused: false,
2886
+ nextRun,
2887
+ message: t("tool.task.created", { name }),
2888
+ };
2550
2889
  }
2551
2890
  catch (err) {
2552
2891
  const message = err instanceof Error ? err.message : String(err);
@@ -2560,8 +2899,11 @@ export default Plugin.define({
2560
2899
  return {
2561
2900
  success: true,
2562
2901
  message: removed.length > 0
2563
- ? `Матрица "${name}" удалена вместе с ${removed.length} задачами (клоны и агрегатор).`
2564
- : `Задача "${name}" успешно удалена.`,
2902
+ ? t("tool.task.matrixDeletedCount", {
2903
+ name,
2904
+ count: removed.length,
2905
+ })
2906
+ : t("tool.task.deleted", { name }),
2565
2907
  };
2566
2908
  }
2567
2909
  catch (err) {
@@ -2592,8 +2934,8 @@ export default Plugin.define({
2592
2934
  return {
2593
2935
  success: true,
2594
2936
  message: removed.length > 0
2595
- ? `Удалено осиротевших задач: ${removed.length}.`
2596
- : "Осиротевших задач не найдено.",
2937
+ ? t("tool.matrix.orphansRemoved", { count: removed.length })
2938
+ : t("tool.matrix.orphansNone"),
2597
2939
  removed,
2598
2940
  };
2599
2941
  }
@@ -2613,9 +2955,21 @@ export default Plugin.define({
2613
2955
  if (definition?.matrix) {
2614
2956
  const matrixResult = await runMatrix(definition);
2615
2957
  const total = definition.matrix.workspaceIds.length;
2616
- const message = `Матрица "${name}": запущено ${matrixResult.started.length} из ${total}` +
2617
- (matrixResult.skipped.length ? `, пропущено ${matrixResult.skipped.length}` : "") +
2618
- (matrixResult.errors.length ? `. Ошибки: ${matrixResult.errors.join("; ")}` : ".");
2958
+ const message = t("tool.matrix.started", {
2959
+ name,
2960
+ started: matrixResult.started.length,
2961
+ total,
2962
+ }) +
2963
+ (matrixResult.skipped.length
2964
+ ? t("tool.matrix.startedSkipped", {
2965
+ count: matrixResult.skipped.length,
2966
+ })
2967
+ : "") +
2968
+ (matrixResult.errors.length
2969
+ ? t("tool.matrix.startedErrors", {
2970
+ errors: matrixResult.errors.join("; "),
2971
+ })
2972
+ : ".");
2619
2973
  return { success: matrixResult.success, message };
2620
2974
  }
2621
2975
  // Контроль параллелизма: не позволяем запускать новую задачу,
@@ -2627,7 +2981,7 @@ export default Plugin.define({
2627
2981
  if (runningCount >= settings.maxConcurrent) {
2628
2982
  return {
2629
2983
  success: false,
2630
- message: "Достигнут лимит одновременных задач. Дождитесь завершения текущих.",
2984
+ message: t("tool.matrix.limit"),
2631
2985
  };
2632
2986
  }
2633
2987
  }
@@ -2636,9 +2990,9 @@ export default Plugin.define({
2636
2990
  // в том числе инициированном из GUI, — дублировать запись здесь не нужно.
2637
2991
  if (result.alreadyRunning) {
2638
2992
  // Мягкое предупреждение: задача уже идёт, это не ошибка запуска.
2639
- return { success: true, message: `Задача "${name}" уже выполняется.` };
2993
+ return { success: true, message: t("tool.task.alreadyRunning", { name }) };
2640
2994
  }
2641
- return { success: true, message: `Задача "${name}" запущена.` };
2995
+ return { success: true, message: t("tool.task.started", { name }) };
2642
2996
  }
2643
2997
  catch (err) {
2644
2998
  return { success: false, message: `schtasks error: ${err instanceof Error ? err.message : String(err)}` };
@@ -2648,7 +3002,7 @@ export default Plugin.define({
2648
3002
  const { eventName, payload } = input;
2649
3003
  const normalized = eventName?.trim();
2650
3004
  if (!normalized) {
2651
- return { success: false, message: "Не передано имя события (eventName).", triggered: [] };
3005
+ return { success: false, message: t("tool.event.nameRequiredShort"), triggered: [] };
2652
3006
  }
2653
3007
  // Ищем задачи с MCP-триггером, совпадающим по имени события и фильтру.
2654
3008
  const definitions = await loadTaskDefinitions();
@@ -2671,18 +3025,18 @@ export default Plugin.define({
2671
3025
  return {
2672
3026
  success: true,
2673
3027
  triggered,
2674
- message: `Событие "${normalized}" обработано. Запущено задач: ${triggered.length}.`,
3028
+ message: t("tool.event.processed", { event: normalized, count: triggered.length }),
2675
3029
  };
2676
3030
  },
2677
3031
  pause_task: async (input) => {
2678
3032
  const { name, until } = input;
2679
3033
  const result = await pauseOrResumeTask(name, true, until);
2680
- return { success: result.success, message: result.message };
3034
+ return result;
2681
3035
  },
2682
3036
  resume_task: async (input) => {
2683
3037
  const { name } = input;
2684
3038
  const result = await pauseOrResumeTask(name, false);
2685
- return { success: result.success, message: result.message };
3039
+ return result;
2686
3040
  },
2687
3041
  update_task: async (input) => {
2688
3042
  return await updateTaskFromInput(input);
@@ -2716,8 +3070,12 @@ export default Plugin.define({
2716
3070
  const report = await runHistoryRetention({ retentionDays, maxRecords });
2717
3071
  const message = report.skipped
2718
3072
  ? report.skipped
2719
- : `Удалено ${report.deleted} записей (по возрасту: ${report.deletedByAge}, по лимиту: ` +
2720
- `${report.deletedByCount}), осталось ${report.kept}.`;
3073
+ : t("tool.history.cleaned", {
3074
+ deleted: report.deleted,
3075
+ byAge: report.deletedByAge,
3076
+ byCount: report.deletedByCount,
3077
+ kept: report.kept,
3078
+ });
2721
3079
  return {
2722
3080
  success: true,
2723
3081
  message,
@@ -2733,7 +3091,9 @@ export default Plugin.define({
2733
3091
  catch (err) {
2734
3092
  return {
2735
3093
  success: false,
2736
- message: `Не удалось очистить историю: ${err instanceof Error ? err.message : String(err)}`,
3094
+ message: t("tool.history.cleanFailed", {
3095
+ error: err instanceof Error ? err.message : String(err),
3096
+ }),
2737
3097
  deleted: 0,
2738
3098
  deletedByAge: 0,
2739
3099
  deletedByCount: 0,
@@ -2817,7 +3177,7 @@ export default Plugin.define({
2817
3177
  const { parentId } = input;
2818
3178
  const target = (parentId ?? "").trim();
2819
3179
  if (!target) {
2820
- return { success: false, error: "Не передан parentId матрицы." };
3180
+ return { success: false, error: t("tool.matrix.parentMissing") };
2821
3181
  }
2822
3182
  try {
2823
3183
  const report = aggregateMatrixResults(target);
@@ -2894,7 +3254,7 @@ export default Plugin.define({
2894
3254
  const { id, name, path: workspacePath, color, env, envFile } = input;
2895
3255
  const workspace = updateWorkspace(id, { name, path: workspacePath, color, env, envFile });
2896
3256
  if (!workspace) {
2897
- return { success: false, error: "Workspace не найден." };
3257
+ return { success: false, error: t("tool.workspace.notFound") };
2898
3258
  }
2899
3259
  // env-файлы существующих задач перегенерируются сразу (Спринт 21).
2900
3260
  await refreshWorkspaceEnvFiles(workspace.id);
@@ -2918,8 +3278,8 @@ export default Plugin.define({
2918
3278
  return {
2919
3279
  success: deleted,
2920
3280
  message: deleted
2921
- ? "Workspace удалён. Задачи сохранены, привязка очищена."
2922
- : "Workspace не найден.",
3281
+ ? t("tool.workspace.deleted")
3282
+ : t("tool.workspace.notFound"),
2923
3283
  };
2924
3284
  }
2925
3285
  catch (err) {
@@ -2943,8 +3303,8 @@ export default Plugin.define({
2943
3303
  current,
2944
3304
  restartRequired: true,
2945
3305
  message: isProfilePinnedByEnv()
2946
- ? `Профиль задан переменной OPENCODE_SCHEDULER_PROFILE=${current}. Перезапустите OpenCode, чтобы применить изменения.`
2947
- : `Активный профиль: ${sanitizeProfileName(name)}. Перезапустите OpenCode, чтобы применить изменения.`,
3306
+ ? t("tool.profile.envVarLong", { name: current })
3307
+ : t("tool.profile.active", { name: sanitizeProfileName(name) }),
2948
3308
  };
2949
3309
  }
2950
3310
  catch (err) {
@@ -2963,7 +3323,7 @@ export default Plugin.define({
2963
3323
  const profile = listProfiles().find((item) => item.name === meta.name);
2964
3324
  return {
2965
3325
  success: true,
2966
- message: `Профиль "${meta.name}" создан (порт дашборда ${meta.port}).`,
3326
+ message: t("tool.profile.created", { name: meta.name, port: meta.port }),
2967
3327
  profile: profile ?? {
2968
3328
  name: meta.name,
2969
3329
  dir: getProfileDir(meta.name),
@@ -2987,8 +3347,8 @@ export default Plugin.define({
2987
3347
  return {
2988
3348
  success: removed,
2989
3349
  message: removed
2990
- ? `Профиль "${sanitizeProfileName(name)}" удалён вместе с его БД и настройками.`
2991
- : "Профиль не найден.",
3350
+ ? t("tool.profile.deleted", { name: sanitizeProfileName(name) })
3351
+ : t("tool.profile.notFound"),
2992
3352
  };
2993
3353
  }
2994
3354
  catch (err) {
@@ -2999,9 +3359,10 @@ export default Plugin.define({
2999
3359
  return await loadSettings();
3000
3360
  },
3001
3361
  save_settings: async (input) => {
3002
- const { maxConcurrent, winterMode, notifications, history, integrations, audit } = input;
3362
+ const { maxConcurrent, locale, winterMode, notifications, history, integrations, audit } = input;
3003
3363
  const current = await loadSettings();
3004
3364
  if (maxConcurrent === undefined &&
3365
+ locale === undefined &&
3005
3366
  winterMode === undefined &&
3006
3367
  notifications === undefined &&
3007
3368
  history === undefined &&
@@ -3010,6 +3371,7 @@ export default Plugin.define({
3010
3371
  return {
3011
3372
  success: false,
3012
3373
  maxConcurrent: current.maxConcurrent,
3374
+ locale: current.locale,
3013
3375
  winterMode: current.winterMode,
3014
3376
  notifications: current.notifications,
3015
3377
  history: current.history,
@@ -3019,15 +3381,19 @@ export default Plugin.define({
3019
3381
  }
3020
3382
  const settings = await saveSettings({
3021
3383
  maxConcurrent,
3384
+ locale,
3022
3385
  winterMode,
3023
3386
  notifications,
3024
3387
  history,
3025
3388
  integrations,
3026
3389
  audit,
3027
3390
  });
3391
+ // Локаль процесса меняется сразу — перезапуск не нужен.
3392
+ setLocale(settings.locale);
3028
3393
  return {
3029
3394
  success: true,
3030
3395
  maxConcurrent: settings.maxConcurrent,
3396
+ locale: settings.locale,
3031
3397
  winterMode: settings.winterMode,
3032
3398
  notifications: settings.notifications,
3033
3399
  history: settings.history,
@@ -3051,15 +3417,15 @@ export default Plugin.define({
3051
3417
  const source = (input ?? {});
3052
3418
  const name = (source.name ?? "").trim();
3053
3419
  if (!name) {
3054
- return { success: false, message: "Нужно имя секрета." };
3420
+ return { success: false, message: t("tool.secret.needName") };
3055
3421
  }
3056
3422
  if (typeof source.value !== "string" || source.value.length === 0) {
3057
- return { success: false, message: "Нужно непустое значение секрета." };
3423
+ return { success: false, message: t("tool.secret.needValue") };
3058
3424
  }
3059
3425
  const secret = setSecret(name, source.value);
3060
3426
  return {
3061
3427
  success: true,
3062
- message: `Секрет ${secret.name} сохранён в зашифрованном виде.`,
3428
+ message: t("tool.secret.saved", { name: secret.name }),
3063
3429
  secret,
3064
3430
  };
3065
3431
  }
@@ -3074,15 +3440,15 @@ export default Plugin.define({
3074
3440
  try {
3075
3441
  const name = ((input ?? {}).name ?? "").trim();
3076
3442
  if (!name) {
3077
- return { success: false, message: "Нужно имя секрета." };
3443
+ return { success: false, message: t("tool.secret.needName") };
3078
3444
  }
3079
3445
  const existed = hasSecret(name);
3080
3446
  deleteSecret(name);
3081
3447
  return {
3082
3448
  success: existed,
3083
3449
  message: existed
3084
- ? `Секрет ${name} удалён.`
3085
- : `Секрет ${name} не найден.`,
3450
+ ? t("tool.secret.deleted", { name })
3451
+ : t("tool.secret.notFound", { name }),
3086
3452
  };
3087
3453
  }
3088
3454
  catch (err) {
@@ -3119,7 +3485,7 @@ export default Plugin.define({
3119
3485
  if (!source?.name?.trim() || !source?.prompt?.trim()) {
3120
3486
  return {
3121
3487
  success: false,
3122
- error: "Нужны непустые название шаблона и промпт.",
3488
+ error: t("tool.template.namePromptRequired"),
3123
3489
  };
3124
3490
  }
3125
3491
  const template = await saveTemplate({
@@ -3146,7 +3512,7 @@ export default Plugin.define({
3146
3512
  delete_template: async (input) => {
3147
3513
  const { id } = input;
3148
3514
  if (!id) {
3149
- return { success: false, error: "Не передан id шаблона." };
3515
+ return { success: false, error: t("tool.template.needId") };
3150
3516
  }
3151
3517
  try {
3152
3518
  await deleteTemplate(id);
@@ -3176,14 +3542,14 @@ export default Plugin.define({
3176
3542
  import_tasks: async (input) => {
3177
3543
  const { data } = input;
3178
3544
  if (!data) {
3179
- return { success: false, error: "Не переданы данные для импорта." };
3545
+ return { success: false, error: t("tool.transfer.noData") };
3180
3546
  }
3181
3547
  try {
3182
3548
  const parsed = parseImportJson(data);
3183
3549
  if (parsed.tasks.length === 0) {
3184
3550
  return {
3185
3551
  success: false,
3186
- error: "В файле нет задач для импорта.",
3552
+ error: t("tool.transfer.noTasksInFile"),
3187
3553
  errors: parsed.errors,
3188
3554
  };
3189
3555
  }
@@ -3191,7 +3557,16 @@ export default Plugin.define({
3191
3557
  const errors = [...parsed.errors];
3192
3558
  for (const def of parsed.tasks) {
3193
3559
  try {
3194
- await schedulerCreateTask(def.name, def.schedule, def.prompt, def.timeoutSeconds, def.workingDirectory ?? def.workdir, def.retryCount, def.retryDelay, def.qualityGate, def.nextTaskOnSuccess, def.nextTaskOnError, def.triggerType, def.watchPath, def.dependsOn, def.model, def.priority, def.beforeScript, def.afterScript, def.mcpEvent, def.workspaceId, def.allowedTools, def.deniedTools, def.matrix, def.matrixParentId, "create", def.timezone, def.notBefore, def.notAfter, def.pausedUntil, def.runAt);
3560
+ await schedulerCreateTask(def.name, def.schedule, def.prompt, def.timeoutSeconds, def.workingDirectory ?? def.workdir, def.retryCount, def.retryDelay, def.qualityGate, def.nextTaskOnSuccess, def.nextTaskOnError, def.triggerType, def.watchPath, def.dependsOn, def.model, def.priority, def.beforeScript, def.afterScript, def.mcpEvent, def.workspaceId, def.allowedTools, def.deniedTools, def.matrix, def.matrixParentId, "create", def.timezone, def.notBefore, def.notAfter, def.pausedUntil, def.runAt, def.session ?? "new", def.sessionId, def.sessionMaxRuns, {
3561
+ activeDays: def.activeDays,
3562
+ windowPolicy: def.windowPolicy,
3563
+ watchGlobs: def.watchGlobs,
3564
+ watchIgnore: def.watchIgnore,
3565
+ gitBranch: def.gitBranch,
3566
+ gitPaths: def.gitPaths,
3567
+ gitIgnore: def.gitIgnore,
3568
+ gitPollSeconds: def.gitPollSeconds,
3569
+ }, def.runWhenLoggedOff === true, def.paused === true);
3195
3570
  await saveTaskDefinition(def);
3196
3571
  imported.push(def.name);
3197
3572
  }
@@ -3220,7 +3595,7 @@ export default Plugin.define({
3220
3595
  // Повторный вызов не создаёт второй сервер — защита от двойного запуска
3221
3596
  // реализована внутри startDashboardServer.
3222
3597
  const dashboard = await startDashboardServer({
3223
- getTasks: collectTasksView,
3598
+ getTasks: async () => (await collectTasksView()).tasks,
3224
3599
  runTask: (name) => runTaskEntry(name),
3225
3600
  deleteTask: async (name) => {
3226
3601
  await deleteTaskWithFamily(name);
@@ -3255,7 +3630,7 @@ function resolveMatrixExtraConfig(name, matrix, ids) {
3255
3630
  if (typeof matrix.concurrency !== "number" ||
3256
3631
  !Number.isFinite(matrix.concurrency) ||
3257
3632
  matrix.concurrency < 1) {
3258
- throw new Error(`Задача "${name}": matrix.concurrency должен быть числом не меньше 1.`);
3633
+ throw new Error(t("tool.error.matrixConcurrency", { task: name }));
3259
3634
  }
3260
3635
  extra.concurrency = Math.floor(matrix.concurrency);
3261
3636
  }
@@ -3265,8 +3640,10 @@ function resolveMatrixExtraConfig(name, matrix, ids) {
3265
3640
  for (const [key, value] of Object.entries(matrix.overrides)) {
3266
3641
  const workspaceKey = key.trim();
3267
3642
  if (!allowed.has(workspaceKey)) {
3268
- throw new Error(`Задача "${name}": matrix.overrides содержит workspace "${workspaceKey}", ` +
3269
- `которого нет в workspaceIds.`);
3643
+ throw new Error(t("tool.error.matrixOverride", {
3644
+ task: name,
3645
+ workspace: workspaceKey,
3646
+ }));
3270
3647
  }
3271
3648
  if (!value || typeof value !== "object")
3272
3649
  continue;
@@ -3310,7 +3687,26 @@ sessionId,
3310
3687
  /** Сколько запусков переживает reuse-сессия до ротации (0/undefined — без ограничения). */
3311
3688
  sessionMaxRuns,
3312
3689
  /** Спринт 27: дни недели, политика окна, glob- и git-фильтры. */
3313
- triggerExtras) {
3690
+ triggerExtras,
3691
+ /** Спринт 27.5.4: Windows — запускать без входа пользователя (/ru SYSTEM). */
3692
+ runWhenLoggedOff,
3693
+ /**
3694
+ * Спринт 27.5.8: пересоздать задачу сразу отключённой (пауза переживает
3695
+ * update). Для матрицы пауза применяется к клонам.
3696
+ */
3697
+ paused) {
3698
+ // Спринт 27.5 (hotfix 1.5.1): проверяем имя до создания wrapper/prompt и записи
3699
+ // в БД. Недопустимые символы отклоняются с понятным сообщением, а не ошибкой
3700
+ // schtasks; имя нормализуется (trim) для всех путей: MCP, RPC и импорт.
3701
+ const normalizedName = name.trim();
3702
+ const nameError = validateTaskName(normalizedName);
3703
+ if (nameError) {
3704
+ throw new Error(nameError);
3705
+ }
3706
+ name = normalizedName;
3707
+ // Для отката файлов: при обновлении существующей задачи файлы переиспользуются,
3708
+ // удалять их при сбое нельзя — в БД остаётся прежнее определение.
3709
+ const definitionExisted = Boolean(getTask(normalizedName));
3314
3710
  const normalizedModel = model?.trim() || undefined;
3315
3711
  const normalizedPriority = normalizePriority(priority);
3316
3712
  const normalizedBefore = beforeScript?.trim() || undefined;
@@ -3319,6 +3715,10 @@ triggerExtras) {
3319
3715
  const normalizedNotBefore = notBefore?.trim() || undefined;
3320
3716
  const normalizedNotAfter = notAfter?.trim() || undefined;
3321
3717
  const normalizedPausedUntil = pausedUntil?.trim() || undefined;
3718
+ // Спринт 27.5.4: true → задача работает без входа (Windows /ru SYSTEM).
3719
+ const normalizedRunWhenLoggedOff = runWhenLoggedOff === true ? true : undefined;
3720
+ // Спринт 27.5.8: пауза сохраняется при пересоздании задачи.
3721
+ const normalizedPaused = paused === true ? true : undefined;
3322
3722
  // Спринт 27: дни недели, политика окна и glob/git-фильтры.
3323
3723
  const normalizeGlobList = (raw) => {
3324
3724
  if (!Array.isArray(raw))
@@ -3357,7 +3757,7 @@ triggerExtras) {
3357
3757
  if (effectiveTriggerType === "once") {
3358
3758
  const normalized = normalizeOneShotRunAt({ runAt });
3359
3759
  if (!normalized.ok) {
3360
- throw new Error(`Задача "${name}": ${normalized.error}`);
3760
+ throw new Error(t("tool.error.taskReason", { name, error: normalized.error }));
3361
3761
  }
3362
3762
  effectiveRunAt = normalized.runAt;
3363
3763
  }
@@ -3368,7 +3768,10 @@ triggerExtras) {
3368
3768
  if (session !== undefined) {
3369
3769
  const normalizedSession = normalizeSessionMode(session);
3370
3770
  if (!normalizedSession) {
3371
- throw new Error(`Задача "${name}": неизвестный режим сессии "${String(session)}".`);
3771
+ throw new Error(t("tool.error.sessionUnknown", {
3772
+ name,
3773
+ session: String(session),
3774
+ }));
3372
3775
  }
3373
3776
  effectiveSession = normalizedSession;
3374
3777
  }
@@ -3389,7 +3792,7 @@ triggerExtras) {
3389
3792
  return cleaned.length > 0 ? cleaned : undefined;
3390
3793
  };
3391
3794
  if (Array.isArray(allowedTools) && allowedTools.filter((t) => typeof t === "string" && t.trim()).length === 0) {
3392
- throw new Error(`Задача "${name}": пустой allowedTools запрещён — задайте список инструментов или уберите поле.`);
3795
+ throw new Error(t("tool.error.allowedToolsEmpty", { task: name }));
3393
3796
  }
3394
3797
  const normalizedAllowedTools = normalizeToolList(allowedTools);
3395
3798
  const normalizedDeniedTools = normalizeToolList(deniedTools);
@@ -3398,25 +3801,29 @@ triggerExtras) {
3398
3801
  let normalizedMatrix;
3399
3802
  if (matrix) {
3400
3803
  if (workspaceId?.trim()) {
3401
- throw new Error(`Задача "${name}": нельзя одновременно workspaceId и matrix.workspaceIds.`);
3804
+ throw new Error(t("tool.error.workspaceIdConflict", { task: name }));
3402
3805
  }
3403
3806
  const ids = Array.from(new Set((Array.isArray(matrix.workspaceIds) ? matrix.workspaceIds : [])
3404
3807
  .filter((id) => typeof id === "string")
3405
3808
  .map((id) => id.trim())
3406
3809
  .filter(Boolean)));
3407
3810
  if (ids.length === 0) {
3408
- throw new Error(`Задача "${name}": matrix.workspaceIds не может быть пустым.`);
3811
+ throw new Error(t("tool.error.workspaceIdsEmpty", { task: name }));
3409
3812
  }
3410
3813
  for (const id of ids) {
3411
3814
  const ws = getWorkspace(id);
3412
3815
  if (!ws) {
3413
- throw new Error(`Задача "${name}": workspace "${id}" не найден.`);
3816
+ throw new Error(t("tool.error.workspaceMissing", { task: name, id }));
3414
3817
  }
3415
3818
  try {
3416
3819
  validateWorkspacePath(ws.path);
3417
3820
  }
3418
3821
  catch {
3419
- throw new Error(`Задача "${name}": workspace "${ws.name}" недоступен по пути "${ws.path}".`);
3822
+ throw new Error(t("tool.error.workspaceUnavailable", {
3823
+ task: name,
3824
+ workspace: ws.name,
3825
+ path: ws.path,
3826
+ }));
3420
3827
  }
3421
3828
  }
3422
3829
  normalizedMatrix = {
@@ -3435,7 +3842,7 @@ triggerExtras) {
3435
3842
  }
3436
3843
  // MCP-триггер без имени события бессмыслен — валидируем до создания файлов.
3437
3844
  if (effectiveTriggerType === "mcp-event" && !normalizedMcpEvent) {
3438
- throw new Error("Для MCP-триггера нужно указать имя события (mcpEvent.event).");
3845
+ throw new Error(t("tool.error.mcpEventRequired"));
3439
3846
  }
3440
3847
  // Спринт 27: git-триггеру нужен git-репозиторий в рабочей директории.
3441
3848
  if (effectiveTriggerType === "git") {
@@ -3443,10 +3850,10 @@ triggerExtras) {
3443
3850
  ? getWorkspace(workspaceId.trim())?.path
3444
3851
  : workingDirectory?.trim() || projectDirectory || process.cwd();
3445
3852
  if (!gitCwd) {
3446
- throw new Error(`Задача "${name}": для git-триггера нужна рабочая директория или workspace.`);
3853
+ throw new Error(t("tool.error.gitCwdRequired", { task: name }));
3447
3854
  }
3448
3855
  if (!readGitBranch(gitCwd)) {
3449
- throw new Error(`Задача "${name}": git-триггер требует git-репозиторий в "${gitCwd}".`);
3856
+ throw new Error(t("tool.error.gitNoRepo", { task: name, path: gitCwd }));
3450
3857
  }
3451
3858
  }
3452
3859
  // Валидируем cron-выражение до создания файлов. Для file/mcp-event
@@ -3461,12 +3868,14 @@ triggerExtras) {
3461
3868
  throw new Error(err.message || String(err));
3462
3869
  }
3463
3870
  if (normalizedTz && !isValidIanaTimeZone(normalizedTz)) {
3464
- throw new Error(`Задача "${name}": неизвестный часовой пояс "${normalizedTz}". ` +
3465
- `Укажите IANA-зону, например Europe/Moscow.`);
3871
+ throw new Error(t("tool.error.timezone", {
3872
+ task: name,
3873
+ timezone: normalizedTz,
3874
+ }));
3466
3875
  }
3467
3876
  const windowError = validateLaunchWindow(normalizedNotBefore, normalizedNotAfter);
3468
3877
  if (windowError) {
3469
- throw new Error(`Задача "${name}": ${windowError}`);
3878
+ throw new Error(t("tool.error.window", { task: name, error: windowError }));
3470
3879
  }
3471
3880
  }
3472
3881
  // Спринт 27: окно и дни недели применимы и к событийным триггерам
@@ -3474,7 +3883,7 @@ triggerExtras) {
3474
3883
  if (effectiveTriggerType !== "cron") {
3475
3884
  const windowError = validateLaunchWindow(normalizedNotBefore, normalizedNotAfter);
3476
3885
  if (windowError) {
3477
- throw new Error(`Задача "${name}": ${windowError}`);
3886
+ throw new Error(t("tool.error.window", { task: name, error: windowError }));
3478
3887
  }
3479
3888
  }
3480
3889
  const sanitized = sanitizeName(name);
@@ -3498,14 +3907,19 @@ triggerExtras) {
3498
3907
  const normalizedWorkspaceId = workspaceId?.trim() || undefined;
3499
3908
  const workspace = normalizedWorkspaceId ? getWorkspace(normalizedWorkspaceId) : undefined;
3500
3909
  if (normalizedWorkspaceId && !workspace) {
3501
- throw new Error(`Workspace '${normalizedWorkspaceId}' не найден.`);
3910
+ throw new Error(t("tool.error.workspaceIdMissing", {
3911
+ id: normalizedWorkspaceId,
3912
+ }));
3502
3913
  }
3503
3914
  if (workspace) {
3504
3915
  try {
3505
3916
  validateWorkspacePath(workspace.path);
3506
3917
  }
3507
3918
  catch {
3508
- throw new Error(`Workspace '${workspace.name}' недоступен по пути '${workspace.path}'`);
3919
+ throw new Error(t("tool.error.workspacePathMissing", {
3920
+ name: workspace.name,
3921
+ path: workspace.path,
3922
+ }));
3509
3923
  }
3510
3924
  if (workingDirectory?.trim() && workingDirectory.trim() !== workspace.path) {
3511
3925
  console.warn(`[workspace] Задача "${name}": workingDirectory "${workingDirectory.trim()}" ` +
@@ -3514,8 +3928,9 @@ triggerExtras) {
3514
3928
  }
3515
3929
  const effectiveWorkingDirectory = workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
3516
3930
  // Спринт 21: env-переменные workspace → отдельный файл, который читает обёртка.
3517
- // Значения не логируются; в лог попадает только факт загрузки.
3518
- const taskEnvFile = writeWorkspaceEnvFile(workspace, PLUGIN_DIR, sanitized);
3931
+ // Спринт 29.3: инжектит в env только реально используемые секреты (scoped-инъекция).
3932
+ const usedSecretNames = collectSecretNames(prompt, beforeScript, afterScript, qualityGate);
3933
+ const taskEnvFile = writeWorkspaceEnvFile(workspace, PLUGIN_DIR, sanitized, usedSecretNames);
3519
3934
  if (taskEnvFile) {
3520
3935
  console.log(`[workspace] Задача "${name}": env-переменные workspace подключены.`);
3521
3936
  }
@@ -3526,7 +3941,9 @@ triggerExtras) {
3526
3941
  await fs.writeFile(logFile, "", "utf8");
3527
3942
  }
3528
3943
  catch (err) {
3529
- throw new Error(`Не удалось подготовить файлы задачи: ${err.message || String(err)}`);
3944
+ throw new Error(t("tool.error.prepareFiles", {
3945
+ error: err.message || String(err),
3946
+ }));
3530
3947
  }
3531
3948
  // Обёртка зависит от платформы:
3532
3949
  // - Windows: .cmd → PowerShell-скрипт (lock, таймаут, метрики);
@@ -3565,8 +3982,17 @@ triggerExtras) {
3565
3982
  }
3566
3983
  }
3567
3984
  catch (err) {
3568
- throw new Error(`Не удалось создать обёртку задачи: ${err.message || String(err)}`);
3985
+ throw new Error(t("tool.error.wrapper", {
3986
+ error: err.message || String(err),
3987
+ }));
3569
3988
  }
3989
+ // 27.5.5.3: при сбое создания новой задачи убираем подготовленные файлы.
3990
+ // При обновлении файлы переиспользуются существующей задачей — не удаляем.
3991
+ const rollbackArtifacts = async () => {
3992
+ if (definitionExisted)
3993
+ return;
3994
+ await Promise.all([wrapperPath, promptFile, logFile, taskEnvFile].map((file) => file ? fs.unlink(file).catch(() => undefined) : Promise.resolve()));
3995
+ };
3570
3996
  try {
3571
3997
  // Бэкенд сам преобразует cron в родное расписание ОС.
3572
3998
  await scheduler.createTask({
@@ -3583,11 +4009,47 @@ triggerExtras) {
3583
4009
  timezone: normalizedTz,
3584
4010
  notBefore: normalizedNotBefore,
3585
4011
  notAfter: normalizedNotAfter,
4012
+ runWhenLoggedOff: normalizedRunWhenLoggedOff,
3586
4013
  });
3587
4014
  }
3588
4015
  catch (err) {
4016
+ await rollbackArtifacts();
3589
4017
  throw new Error(err instanceof Error ? err.message : String(err));
3590
4018
  }
4019
+ // Проверяем фактическое наличие задачи в планировщике: до 3 попыток с паузой
4020
+ // 200 мс. Это ловит случай, когда ОС/обёртка вернула код 0, но задачи нет.
4021
+ const isListed = (tasks) => tasks.some((task) => (task.taskName || "").trim().toLowerCase() === name.toLowerCase());
4022
+ let listedTasks;
4023
+ let verifyQueryError;
4024
+ for (let attempt = 0; attempt < 3; attempt += 1) {
4025
+ try {
4026
+ listedTasks = await scheduler.listTasks();
4027
+ if (isListed(listedTasks))
4028
+ break;
4029
+ }
4030
+ catch (err) {
4031
+ verifyQueryError = err;
4032
+ }
4033
+ if (attempt < 2) {
4034
+ await new Promise((resolve) => setTimeout(resolve, 200));
4035
+ }
4036
+ }
4037
+ if (listedTasks && !isListed(listedTasks)) {
4038
+ await rollbackArtifacts();
4039
+ throw new Error(t("tool.error.schedulerNotConfirmed", {
4040
+ task: name,
4041
+ scheduler: scheduler.title,
4042
+ }) +
4043
+ " " +
4044
+ (definitionExisted
4045
+ ? t("tool.error.schedulerKeptFiles")
4046
+ : t("tool.error.schedulerRemovedFiles")));
4047
+ }
4048
+ if (!listedTasks && verifyQueryError) {
4049
+ // Список получить не удалось — не удаляем возможно созданную задачу,
4050
+ // но явно предупреждаем: проверка наличия не выполнена.
4051
+ console.warn(`[windows-scheduler] Задача "${name}" создана, но проверить её в планировщике не удалось: ${verifyQueryError instanceof Error ? verifyQueryError.message : String(verifyQueryError)}`);
4052
+ }
3591
4053
  // Сохраняем определение задачи для последующего экспорта/импорта.
3592
4054
  // Определение до перезаписи: нужно и для очереди матрицы, и для счётчика сессии.
3593
4055
  const previousDefinition = getTask(name);
@@ -3623,6 +4085,10 @@ triggerExtras) {
3623
4085
  timezone: normalizedTz,
3624
4086
  notBefore: normalizedNotBefore,
3625
4087
  notAfter: normalizedNotAfter,
4088
+ // Спринт 27.5.4: режим входа (Windows: /ru SYSTEM при true).
4089
+ runWhenLoggedOff: normalizedRunWhenLoggedOff,
4090
+ // Спринт 27.5.8: бессрочная пауза переживает пересоздание.
4091
+ paused: normalizedPaused,
3626
4092
  // Спринт 27: дни недели, политика окна, glob- и git-фильтры.
3627
4093
  activeDays: normalizedActiveDays,
3628
4094
  windowPolicy: normalizedWindowPolicy,
@@ -3651,6 +4117,8 @@ triggerExtras) {
3651
4117
  };
3652
4118
  try {
3653
4119
  await saveTaskDefinition(taskDefinition);
4120
+ // Аудит политики прав: фиксируем, какие инструменты задача блокирует.
4121
+ recordTaskToolBlocks(name, normalizedAllowedTools, normalizedDeniedTools);
3654
4122
  }
3655
4123
  catch {
3656
4124
  // Не критично — основная задача уже создана.
@@ -3661,7 +4129,7 @@ triggerExtras) {
3661
4129
  // с нуля, а синхронизируются с новым определением; выполняющиеся — не трогаем.
3662
4130
  if (normalizedMatrix) {
3663
4131
  const createClone = async (clone) => {
3664
- await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil);
4132
+ await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil, clone.runAt, clone.session, clone.sessionId, clone.sessionMaxRuns, undefined, clone.runWhenLoggedOff, clone.paused);
3665
4133
  };
3666
4134
  const removeChild = async (child) => {
3667
4135
  try {
@@ -3676,6 +4144,8 @@ triggerExtras) {
3676
4144
  catch {
3677
4145
  // Не критично.
3678
4146
  }
4147
+ // Спринт 27.5.7: при откате прогона не оставляем и файлы клона.
4148
+ await removeTaskArtifacts(child);
3679
4149
  };
3680
4150
  // Создаёт/обновляет/удаляет matrix-complete по текущему определению.
3681
4151
  const syncAggregator = async () => {
@@ -3688,8 +4158,10 @@ triggerExtras) {
3688
4158
  const cloneNames = listMatrixClones(name).map((clone) => clone.name);
3689
4159
  if (cloneNames.length === 0)
3690
4160
  return undefined;
3691
- await schedulerCreateTask(aggregatorName, schedule, `Матрица "${name}" завершена. Проверь результаты клонов: ` +
3692
- `${cloneNames.join(", ")}.`, timeoutSeconds, undefined, undefined, undefined, undefined, undefined, undefined, "file", undefined, cloneNames, normalizedModel, normalizedPriority);
4161
+ await schedulerCreateTask(aggregatorName, schedule, t("tool.matrix.completed", {
4162
+ name,
4163
+ clones: cloneNames.join(", "),
4164
+ }), timeoutSeconds, undefined, undefined, undefined, undefined, undefined, undefined, "file", undefined, cloneNames, normalizedModel, normalizedPriority);
3693
4165
  return aggregatorName;
3694
4166
  };
3695
4167
  if (matrixMode === "sync") {
@@ -3714,13 +4186,101 @@ triggerExtras) {
3714
4186
  for (const child of removeMatrixChildren(name)) {
3715
4187
  await removeChild(child);
3716
4188
  }
3717
- const clones = expandMatrixTask(taskDefinition);
3718
- for (const clone of clones) {
3719
- await createClone(clone);
4189
+ // Спринт 27.5.7: если клон не создался, откатываем весь прогон. Иначе
4190
+ // остаётся родитель с половиной клонов — он выглядит рабочим, но часть
4191
+ // workspace никогда не запускается. Ошибку expandMatrixTask (неизвестный
4192
+ // workspace) обрабатываем там же: родитель уже записан в БД.
4193
+ const createdInRun = [];
4194
+ try {
4195
+ const clones = expandMatrixTask(taskDefinition);
4196
+ for (const clone of clones) {
4197
+ try {
4198
+ await createClone(clone);
4199
+ createdInRun.push(clone.name);
4200
+ }
4201
+ catch (err) {
4202
+ const workspaceLabel = clone.workspaceId
4203
+ ? getWorkspace(clone.workspaceId)?.name ?? clone.workspaceId
4204
+ : "без workspace";
4205
+ throw new Error(t("tool.error.matrixCloneFailed", {
4206
+ clone: clone.name,
4207
+ workspace: workspaceLabel,
4208
+ error: err instanceof Error ? err.message : String(err),
4209
+ }));
4210
+ }
4211
+ }
4212
+ await syncAggregator();
4213
+ }
4214
+ catch (err) {
4215
+ for (const child of [...createdInRun].reverse()) {
4216
+ await removeChild(child);
4217
+ }
4218
+ const aggregatorName = matrixCompleteName(name);
4219
+ if (getTask(aggregatorName)) {
4220
+ await removeChild(aggregatorName);
4221
+ }
4222
+ // Новая матрица: без клонов родитель бесполезен — убираем и его,
4223
+ // вместе с подготовленными файлами обёртки.
4224
+ if (!definitionExisted) {
4225
+ try {
4226
+ await scheduler.deleteTask(name);
4227
+ }
4228
+ catch {
4229
+ // Задачи могло не быть: бэкенд уже вернул ошибку.
4230
+ }
4231
+ try {
4232
+ await removeTaskDefinition(name);
4233
+ }
4234
+ catch {
4235
+ // Не критично: запись могла не сохраниться.
4236
+ }
4237
+ await rollbackArtifacts();
4238
+ }
4239
+ throw new Error(t("tool.error.matrixExpandRuntime", {
4240
+ name,
4241
+ error: err instanceof Error ? err.message : String(err),
4242
+ }));
3720
4243
  }
3721
- await syncAggregator();
3722
4244
  }
3723
4245
  }
4246
+ // Спринт 27.5.8: пересозданная задача должна остаться на паузе. У матрицы
4247
+ // пауза применяется к клонам — родитель сам никогда не выполняется.
4248
+ if (normalizedPaused) {
4249
+ const pauseTargets = normalizedMatrix
4250
+ ? listMatrixClones(name).map((clone) => clone.name)
4251
+ : [name];
4252
+ for (const target of pauseTargets) {
4253
+ try {
4254
+ await scheduler.pauseTask(target);
4255
+ }
4256
+ catch (err) {
4257
+ console.warn(`[windows-scheduler] Задача "${target}": пауза не восстановлена после пересоздания: ${err instanceof Error ? err.message : String(err)}`);
4258
+ }
4259
+ }
4260
+ }
4261
+ }
4262
+ /**
4263
+ * Спринт 27.5.6: восстановление задачи из определения в БД.
4264
+ *
4265
+ * update_task пересоздаёт задачу в планировщике (delete + create). Раньше при
4266
+ * сбое create после успешного delete старая версия терялась навсегда: в ОС её
4267
+ * уже нет, а в БД лежит новое (не применённое) определение. Здесь мы заново
4268
+ * создаём задачу из прежнего определения — обёртка, промпт, расписание и
4269
+ * пауза восстанавливаются тем же путём, что и при обычном create.
4270
+ */
4271
+ async function recreateTaskFromDefinition(definition) {
4272
+ const paused = Boolean(definition.paused === true ||
4273
+ (definition.pausedUntil && Date.parse(definition.pausedUntil) > Date.now()));
4274
+ await schedulerCreateTask(definition.name, definition.schedule ?? "", definition.prompt, definition.timeoutSeconds, definition.workingDirectory, definition.retryCount, definition.retryDelay, definition.qualityGate, definition.nextTaskOnSuccess, definition.nextTaskOnError, definition.triggerType ?? "cron", definition.watchPath, Array.isArray(definition.dependsOn) ? definition.dependsOn : undefined, definition.model, definition.priority, definition.beforeScript, definition.afterScript, definition.mcpEvent, definition.workspaceId, definition.allowedTools, definition.deniedTools, definition.matrix, definition.matrixParentId, "create", definition.timezone, definition.notBefore, definition.notAfter, definition.pausedUntil, definition.runAt, definition.session ?? "new", definition.sessionId, definition.sessionMaxRuns, {
4275
+ activeDays: definition.activeDays,
4276
+ windowPolicy: definition.windowPolicy,
4277
+ watchGlobs: definition.watchGlobs,
4278
+ watchIgnore: definition.watchIgnore,
4279
+ gitBranch: definition.gitBranch,
4280
+ gitPaths: definition.gitPaths,
4281
+ gitIgnore: definition.gitIgnore,
4282
+ gitPollSeconds: definition.gitPollSeconds,
4283
+ }, definition.runWhenLoggedOff, paused);
3724
4284
  }
3725
4285
  /**
3726
4286
  * Запуск задачи «как есть», но с учётом матрицы: родитель раскладывается
@@ -3749,18 +4309,51 @@ async function runTaskEntry(name) {
3749
4309
  throw err;
3750
4310
  }
3751
4311
  }
4312
+ /**
4313
+ * Спринт 27.5.3: чтение задач ОС с одним повтором.
4314
+ *
4315
+ * Сразу после мутации (create/delete/pause/resume) `schtasks /query` иногда
4316
+ * отдаёт пустой список, хотя в БД задачи уже есть, или падает. Один короткий
4317
+ * retry убирает ложный «задач нет»; если ОС так и не ответила осмысленно —
4318
+ * возвращаем `osAvailable: false`, и вызывающий код показывает состояние БД.
4319
+ */
4320
+ async function readOsTasksWithRetry(expectNonEmpty, delayMs = 300) {
4321
+ let lastError;
4322
+ for (let attempt = 0; attempt < 2; attempt += 1) {
4323
+ if (attempt > 0) {
4324
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
4325
+ }
4326
+ try {
4327
+ const tasks = await scheduler.listTasks();
4328
+ if (tasks.length > 0 || !expectNonEmpty) {
4329
+ return { tasks, osAvailable: true };
4330
+ }
4331
+ lastError = "планировщик ОС вернул пустой список, хотя в БД есть задачи";
4332
+ }
4333
+ catch (err) {
4334
+ lastError = err instanceof Error ? err.message : String(err);
4335
+ }
4336
+ }
4337
+ return { tasks: [], osAvailable: false, osError: lastError };
4338
+ }
3752
4339
  /**
3753
4340
  * Собирает задачи плагина в формате, который отдают оба потребителя:
3754
4341
  * RPC get_tasks (GUI) и инструмент list_tasks (агент).
4342
+ *
4343
+ * Спринт 27.5.3: возвращает также состояние чтения ОС. Если ОС недоступна,
4344
+ * `tasks` — состояние из БД (задачи помечены `orphaned: true`), а не пустой
4345
+ * массив: иначе GUI и агент решали бы, что задач нет.
3755
4346
  */
3756
4347
  async function collectTasksView() {
3757
- const tasks = await scheduler.listTasks();
4348
+ const defs = await loadTaskDefinitions();
4349
+ const osRead = await readOsTasksWithRetry(defs.length > 0);
4350
+ const tasks = osRead.tasks;
3758
4351
  // Читаем историю один раз, чтобы определить финальный статус по последней записи.
3759
4352
  const history = await loadHistory();
3760
4353
  // loadHistory() отдаёт записи от новых к старым; helper оставляет самую свежую.
3761
4354
  const lastByTask = latestHistoryByTask(history);
3762
- // Читаем определения задач один раз (расписание, повторы, цепочки, директория).
3763
- const defs = await loadTaskDefinitions();
4355
+ // Определения задач читаются один раз заранее (см. выше) — расписание,
4356
+ // повторы, цепочки, директория.
3764
4357
  const workspaces = listWorkspaces();
3765
4358
  const workspaceById = new Map(workspaces.map((workspace) => [workspace.id, workspace]));
3766
4359
  // Счётчики запусков по задачам. Основной источник — таблица metrics
@@ -3800,7 +4393,7 @@ async function collectTasksView() {
3800
4393
  orphaned: true,
3801
4394
  })),
3802
4395
  ];
3803
- return sources.map(({ task: t, orphaned }) => {
4396
+ const view = sources.map(({ task: t, orphaned }) => {
3804
4397
  // Все бэкенды возвращают короткие имена (без папки планировщика).
3805
4398
  const name = t.taskName || "";
3806
4399
  // Приоритет 1: статус, который сообщает планировщик ОС.
@@ -3840,6 +4433,13 @@ async function collectTasksView() {
3840
4433
  error: 0,
3841
4434
  partial: 0,
3842
4435
  };
4436
+ // Спринт 27.5.2: пауза учитывает и флаг ОС, и активный pausedUntil.
4437
+ // nextRun считаем из определения — schtasks после мутации отдаёт
4438
+ // nextRunTime с задержкой, из-за чего API показывал null после resume.
4439
+ const pausedUntil = def?.pausedUntil ?? null;
4440
+ const paused = Boolean(t.paused) ||
4441
+ def?.paused === true ||
4442
+ Boolean(pausedUntil && Date.parse(pausedUntil) > Date.now());
3843
4443
  return {
3844
4444
  name,
3845
4445
  schedule: def?.schedule ?? "",
@@ -3848,15 +4448,15 @@ async function collectTasksView() {
3848
4448
  // Спринт 24 (фикс): явный признак паузы. Раньше GUI пытался вывести его
3849
4449
  // из текстового статуса, но mapStatus() превращает "disabled" в "unknown",
3850
4450
  // поэтому кнопка «возобновить» была недоступна.
3851
- paused: Boolean(t.paused),
4451
+ paused,
3852
4452
  runsTotal: counts.total,
3853
4453
  runsSuccess: counts.success,
3854
4454
  runsError: counts.error,
3855
4455
  runsPartial: counts.partial,
3856
- // Для разовой задачи показываем запланированное время, а не пустое расписание.
3857
- nextRun: def?.triggerType === "once"
3858
- ? def?.runAt ?? (t.nextRunTime ? String(t.nextRunTime) : null)
3859
- : t.nextRunTime ? String(t.nextRunTime) : null,
4456
+ nextRun: paused
4457
+ ? null
4458
+ : computeTaskNextRun(def) ??
4459
+ (t.nextRunTime ? String(t.nextRunTime) : null),
3860
4460
  runAt: def?.runAt ?? null,
3861
4461
  session: def?.session ?? "new",
3862
4462
  sessionId: def?.sessionId ?? null,
@@ -3879,6 +4479,10 @@ async function collectTasksView() {
3879
4479
  notBefore: def?.notBefore ?? null,
3880
4480
  notAfter: def?.notAfter ?? null,
3881
4481
  pausedUntil: def?.pausedUntil ?? null,
4482
+ // Спринт 27.5.4: режим входа — из ОС (Interactive/Background) и из
4483
+ // определения (запуск без входа через /ru SYSTEM).
4484
+ logonMode: t.logonMode ?? null,
4485
+ runWhenLoggedOff: Boolean(def?.runWhenLoggedOff),
3882
4486
  workingDirectory: workspace?.path ?? def?.workingDirectory ?? def?.workdir ?? null,
3883
4487
  workspaceId: workspace?.id ?? def?.workspaceId ?? null,
3884
4488
  workspaceName: workspace?.name ?? null,
@@ -3901,6 +4505,7 @@ async function collectTasksView() {
3901
4505
  prompt: def?.prompt ?? "",
3902
4506
  };
3903
4507
  });
4508
+ return { tasks: view, osAvailable: osRead.osAvailable, osError: osRead.osError };
3904
4509
  }
3905
4510
  /**
3906
4511
  * Проверяет фильтр MCP-события.