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.
- package/CHANGELOG.md +47 -1
- package/LICENSE +21 -21
- package/README.md +24 -2
- package/ROADMAP-STRATEGY.md +16 -16
- package/ROADMAP.md +649 -160
- package/dist/core/audit.d.ts +27 -0
- package/dist/core/audit.d.ts.map +1 -1
- package/dist/core/audit.js +60 -0
- package/dist/core/dry-run.d.ts +10 -0
- package/dist/core/dry-run.d.ts.map +1 -1
- package/dist/core/dry-run.js +55 -34
- package/dist/core/git-trigger.d.ts.map +1 -1
- package/dist/core/git-trigger.js +15 -9
- package/dist/core/matrix.d.ts.map +1 -1
- package/dist/core/matrix.js +48 -22
- package/dist/core/ps-wrapper.d.ts +1 -1
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +47 -10
- package/dist/core/schedule-v2.d.ts.map +1 -1
- package/dist/core/schedule-v2.js +29 -17
- package/dist/core/scheduler/types.d.ts +6 -0
- package/dist/core/scheduler/types.d.ts.map +1 -1
- package/dist/core/scheduler/windows.d.ts +6 -2
- package/dist/core/scheduler/windows.d.ts.map +1 -1
- package/dist/core/scheduler/windows.js +25 -10
- package/dist/core/secrets.d.ts +10 -3
- package/dist/core/secrets.d.ts.map +1 -1
- package/dist/core/secrets.js +28 -4
- package/dist/core/telegram.d.ts.map +1 -1
- package/dist/core/telegram.js +13 -10
- package/dist/core/wrappers/bash.d.ts +1 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +91 -5
- package/dist/i18n.d.ts +52 -0
- package/dist/i18n.d.ts.map +1 -0
- package/dist/i18n.js +292 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +788 -183
- package/dist/notifications.d.ts.map +1 -1
- package/dist/notifications.js +74 -40
- package/dist/rpc.d.ts +15 -2
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +6 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +89 -48
- package/dist/settings.d.ts +3 -0
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +20 -8
- package/dist/task-transfer.d.ts +13 -0
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +11 -0
- package/dist/types.d.ts +11 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +32 -0
- package/dist/workspaces.d.ts +2 -2
- package/dist/workspaces.d.ts.map +1 -1
- package/dist/workspaces.js +6 -4
- package/docs/ARCHITECTURE.md +96 -4
- package/docs/FEATURES.md +34 -5
- package/docs/README.ru.md +17 -1
- package/gui-experimental.cjs +9 -9
- package/locales/en.json +695 -0
- package/locales/ru.json +695 -0
- package/package.json +6 -3
- package/scripts/test-locale.mjs +44 -0
- package/src/core/audit.ts +89 -0
- package/src/core/dry-run.ts +76 -38
- package/src/core/git-trigger.ts +15 -9
- package/src/core/matrix.ts +52 -26
- package/src/core/ps-wrapper.ts +47 -10
- package/src/core/schedule-v2.ts +47 -17
- package/src/core/scheduler/types.ts +6 -0
- package/src/core/scheduler/windows.ts +25 -10
- package/src/core/secrets.ts +34 -10
- package/src/core/telegram.ts +16 -10
- package/src/core/wrappers/bash.ts +112 -5
- package/src/gui.tsx +575 -480
- package/src/i18n.ts +339 -0
- package/src/index.ts +960 -193
- package/src/notifications.ts +83 -42
- package/src/rpc.ts +6 -2
- package/src/server.ts +89 -48
- package/src/settings.ts +38 -10
- package/src/task-transfer.ts +24 -0
- package/src/types.ts +37 -0
- package/src/workspaces.ts +9 -4
package/src/index.ts
CHANGED
|
@@ -6,8 +6,16 @@ import { existsSync } from "node:fs";
|
|
|
6
6
|
import fs from "node:fs/promises";
|
|
7
7
|
import path from "node:path";
|
|
8
8
|
import { LockManager } from "./core/lock.js";
|
|
9
|
-
import {
|
|
10
|
-
|
|
9
|
+
import {
|
|
10
|
+
LOCK_DIR,
|
|
11
|
+
LOG_DIR,
|
|
12
|
+
PLUGIN_DIR,
|
|
13
|
+
STALE_LOCK_MAX_AGE_MS,
|
|
14
|
+
WRAPPER_DIR,
|
|
15
|
+
sanitizeName,
|
|
16
|
+
validateTaskName,
|
|
17
|
+
} from "./types.js";
|
|
18
|
+
import { parseCron, buildScheduleGate, isValidIanaTimeZone, validateLaunchWindow, prevRun, nextRun as cronNextRun, normalizeActiveDays, activeWindowState, nextWindowOpenDelayMs } from "./core/schedule-v2.js";
|
|
11
19
|
import {
|
|
12
20
|
buildLaunchdOneShotCleanup,
|
|
13
21
|
normalizeOneShotRunAt,
|
|
@@ -39,6 +47,7 @@ import {
|
|
|
39
47
|
import { SchedulerRpc } from "./rpc.js";
|
|
40
48
|
import { latestHistoryByTask, loadHistory, loadMetrics } from "./history.js";
|
|
41
49
|
import { loadSettings, saveSettings } from "./settings.js";
|
|
50
|
+
import { setLocale, t, type Locale } from "./i18n.js";
|
|
42
51
|
import type {
|
|
43
52
|
AuditSettings,
|
|
44
53
|
HistorySettings,
|
|
@@ -89,7 +98,7 @@ import {
|
|
|
89
98
|
import { closeDb, initDb } from "./db/index.js";
|
|
90
99
|
import { migrateJsonToDb } from "./db/migrate.js";
|
|
91
100
|
import { checkJsonBackups, recoverInterruptedRuns } from "./db/recovery.js";
|
|
92
|
-
import { getTask, listMatrixClones, saveTask } from "./db/tasks-repo.js";
|
|
101
|
+
import { getTask, listMatrixClones, listTasks as listTaskDefinitions, saveTask } from "./db/tasks-repo.js";
|
|
93
102
|
import {
|
|
94
103
|
addWorkspace,
|
|
95
104
|
deleteWorkspace,
|
|
@@ -103,6 +112,7 @@ import {
|
|
|
103
112
|
} from "./workspaces.js";
|
|
104
113
|
import {
|
|
105
114
|
deleteSecret,
|
|
115
|
+
collectSecretNames,
|
|
106
116
|
hasSecret,
|
|
107
117
|
listSecrets,
|
|
108
118
|
setSecret,
|
|
@@ -111,6 +121,7 @@ import {
|
|
|
111
121
|
cleanupAuditLog,
|
|
112
122
|
readAuditLog,
|
|
113
123
|
recordAudit,
|
|
124
|
+
recordTaskToolBlocks,
|
|
114
125
|
} from "./core/audit.js";
|
|
115
126
|
import type { AuditEntryInput } from "./core/audit.js";
|
|
116
127
|
|
|
@@ -211,7 +222,11 @@ export const matrixSchema = z.object({
|
|
|
211
222
|
|
|
212
223
|
/** Zod-схема аргументов schedule_task */
|
|
213
224
|
export const scheduleTaskSchema = z.object({
|
|
214
|
-
name: z
|
|
225
|
+
name: z
|
|
226
|
+
.string()
|
|
227
|
+
.describe(
|
|
228
|
+
"Unique task name (the plugin prefix is applied automatically). Allowed: letters (including Cyrillic), digits, space, dot, underscore and hyphen."
|
|
229
|
+
),
|
|
215
230
|
schedule: z
|
|
216
231
|
.string()
|
|
217
232
|
.optional()
|
|
@@ -412,6 +427,12 @@ export const scheduleTaskSchema = z.object({
|
|
|
412
427
|
.describe(
|
|
413
428
|
"Role-scoped tool deny-list (takes precedence over allowedTools). Metadata-only."
|
|
414
429
|
),
|
|
430
|
+
runWhenLoggedOff: z
|
|
431
|
+
.boolean()
|
|
432
|
+
.optional()
|
|
433
|
+
.describe(
|
|
434
|
+
"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."
|
|
435
|
+
),
|
|
415
436
|
matrix: matrixSchema
|
|
416
437
|
.optional()
|
|
417
438
|
.describe(
|
|
@@ -423,7 +444,7 @@ export const scheduleTaskSchema = z.object({
|
|
|
423
444
|
ctx.addIssue({
|
|
424
445
|
code: z.ZodIssueCode.custom,
|
|
425
446
|
path: ["schedule"],
|
|
426
|
-
message: "
|
|
447
|
+
message: t("tool.error.cronSchedule"),
|
|
427
448
|
});
|
|
428
449
|
}
|
|
429
450
|
if (
|
|
@@ -434,21 +455,21 @@ export const scheduleTaskSchema = z.object({
|
|
|
434
455
|
ctx.addIssue({
|
|
435
456
|
code: z.ZodIssueCode.custom,
|
|
436
457
|
path: ["runAt"],
|
|
437
|
-
message: "
|
|
458
|
+
message: t("tool.error.onceSchedule"),
|
|
438
459
|
});
|
|
439
460
|
}
|
|
440
461
|
if (trigger === "once" && value.matrix) {
|
|
441
462
|
ctx.addIssue({
|
|
442
463
|
code: z.ZodIssueCode.custom,
|
|
443
464
|
path: ["matrix"],
|
|
444
|
-
message: "
|
|
465
|
+
message: t("tool.error.onceMatrixSchema"),
|
|
445
466
|
});
|
|
446
467
|
}
|
|
447
468
|
if (trigger !== "once" && (value.runAt || value.delaySeconds !== undefined)) {
|
|
448
469
|
ctx.addIssue({
|
|
449
470
|
code: z.ZodIssueCode.custom,
|
|
450
471
|
path: ["runAt"],
|
|
451
|
-
message: "
|
|
472
|
+
message: t("tool.error.onceFields"),
|
|
452
473
|
});
|
|
453
474
|
}
|
|
454
475
|
});
|
|
@@ -520,6 +541,12 @@ export const updateTaskSchema = z.object({
|
|
|
520
541
|
.enum(["skip", "postpone", "run"])
|
|
521
542
|
.optional()
|
|
522
543
|
.describe("New behaviour outside the window: postpone (default), skip or run."),
|
|
544
|
+
runWhenLoggedOff: z
|
|
545
|
+
.boolean()
|
|
546
|
+
.optional()
|
|
547
|
+
.describe(
|
|
548
|
+
"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."
|
|
549
|
+
),
|
|
523
550
|
watchGlobs: z
|
|
524
551
|
.array(z.string())
|
|
525
552
|
.optional()
|
|
@@ -629,14 +656,14 @@ export const updateTaskSchema = z.object({
|
|
|
629
656
|
ctx.addIssue({
|
|
630
657
|
code: z.ZodIssueCode.custom,
|
|
631
658
|
path: ["runAt"],
|
|
632
|
-
message: "
|
|
659
|
+
message: t("tool.error.onceFields"),
|
|
633
660
|
});
|
|
634
661
|
}
|
|
635
662
|
if (value.triggerType === "once" && value.matrix) {
|
|
636
663
|
ctx.addIssue({
|
|
637
664
|
code: z.ZodIssueCode.custom,
|
|
638
665
|
path: ["matrix"],
|
|
639
|
-
message: "
|
|
666
|
+
message: t("tool.error.onceMatrixUpdate"),
|
|
640
667
|
});
|
|
641
668
|
}
|
|
642
669
|
});
|
|
@@ -700,13 +727,13 @@ const manageWorkspacesSchema = z.object({
|
|
|
700
727
|
.nullable()
|
|
701
728
|
.optional()
|
|
702
729
|
.describe(
|
|
703
|
-
"
|
|
730
|
+
"Workspace environment variables (key → value). Override envFile values; secrets are masked in logs (add/update)."
|
|
704
731
|
),
|
|
705
732
|
envFile: z
|
|
706
733
|
.string()
|
|
707
734
|
.nullable()
|
|
708
735
|
.optional()
|
|
709
|
-
.describe("
|
|
736
|
+
.describe("Path to the workspace .env file (add/update, null clears it)."),
|
|
710
737
|
});
|
|
711
738
|
|
|
712
739
|
export const matrixControlSchema = z.object({
|
|
@@ -770,6 +797,12 @@ export const manageSettingsSchema = z.object({
|
|
|
770
797
|
.max(16)
|
|
771
798
|
.optional()
|
|
772
799
|
.describe("How many task runs may execute at the same time."),
|
|
800
|
+
locale: z
|
|
801
|
+
.enum(["ru", "en"])
|
|
802
|
+
.optional()
|
|
803
|
+
.describe(
|
|
804
|
+
"Interface language: ru (default) or en. Applies without restart."
|
|
805
|
+
),
|
|
773
806
|
winterMode: z
|
|
774
807
|
.boolean()
|
|
775
808
|
.optional()
|
|
@@ -950,6 +983,90 @@ function wrapExecute<Args>(
|
|
|
950
983
|
};
|
|
951
984
|
}
|
|
952
985
|
|
|
986
|
+
/**
|
|
987
|
+
* Спринт 27.5.2: ближайший запуск по определению задачи, без чтения ОС.
|
|
988
|
+
*
|
|
989
|
+
* - `once` → `runAt` (запланированный момент);
|
|
990
|
+
* - пауза (`paused` или будущий `pausedUntil`) → null;
|
|
991
|
+
* - `cron` → ближайшее совпадение cron с учётом окна и дней недели:
|
|
992
|
+
* * `run` — окно игнорируется;
|
|
993
|
+
* * `skip` — ищем следующее совпадение внутри окна;
|
|
994
|
+
* * `postpone` (по умолчанию) — перенос на открытие окна, как в schedule-gate;
|
|
995
|
+
* - `file`/`git`/`mcp-event` → null (расписания нет).
|
|
996
|
+
*/
|
|
997
|
+
function computeTaskNextRun(
|
|
998
|
+
def:
|
|
999
|
+
| Pick<
|
|
1000
|
+
TaskDefinition,
|
|
1001
|
+
| "schedule"
|
|
1002
|
+
| "triggerType"
|
|
1003
|
+
| "runAt"
|
|
1004
|
+
| "timezone"
|
|
1005
|
+
| "notBefore"
|
|
1006
|
+
| "notAfter"
|
|
1007
|
+
| "activeDays"
|
|
1008
|
+
| "windowPolicy"
|
|
1009
|
+
| "pausedUntil"
|
|
1010
|
+
>
|
|
1011
|
+
| undefined,
|
|
1012
|
+
options: { paused?: boolean; now?: Date } = {}
|
|
1013
|
+
): string | null {
|
|
1014
|
+
if (!def) return null;
|
|
1015
|
+
if (options.paused) return null;
|
|
1016
|
+
|
|
1017
|
+
const now = options.now ?? new Date();
|
|
1018
|
+
if (def.pausedUntil) {
|
|
1019
|
+
const until = Date.parse(def.pausedUntil);
|
|
1020
|
+
if (Number.isFinite(until) && until > now.getTime()) return null;
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
const type = def.triggerType ?? "cron";
|
|
1024
|
+
if (type === "once") {
|
|
1025
|
+
if (!def.runAt) return null;
|
|
1026
|
+
const at = Date.parse(def.runAt);
|
|
1027
|
+
return Number.isFinite(at) ? new Date(at).toISOString() : null;
|
|
1028
|
+
}
|
|
1029
|
+
if (type !== "cron") return null;
|
|
1030
|
+
|
|
1031
|
+
const schedule = (def.schedule || "").trim();
|
|
1032
|
+
if (!schedule) return null;
|
|
1033
|
+
|
|
1034
|
+
const timeZone = def.timezone?.trim() || undefined;
|
|
1035
|
+
const policy =
|
|
1036
|
+
def.windowPolicy === "skip" || def.windowPolicy === "run"
|
|
1037
|
+
? def.windowPolicy
|
|
1038
|
+
: "postpone";
|
|
1039
|
+
const windowOptions = {
|
|
1040
|
+
notBefore: def.notBefore,
|
|
1041
|
+
notAfter: def.notAfter,
|
|
1042
|
+
days: Array.isArray(def.activeDays) ? def.activeDays : undefined,
|
|
1043
|
+
timeZone,
|
|
1044
|
+
};
|
|
1045
|
+
|
|
1046
|
+
let tick: Date | null;
|
|
1047
|
+
try {
|
|
1048
|
+
tick = cronNextRun(schedule, now, timeZone);
|
|
1049
|
+
} catch {
|
|
1050
|
+
// Некорректное выражение не должно ломать ответ инструмента.
|
|
1051
|
+
return null;
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
// skip-политика может пропустить сколько угодно тиков вне окна;
|
|
1055
|
+
// ограничение защищает от бесконечного перебора (5-летнее окно cron).
|
|
1056
|
+
for (let guard = 0; tick && guard < 600; guard += 1) {
|
|
1057
|
+
if (policy === "run") return tick.toISOString();
|
|
1058
|
+
const state = activeWindowState(tick, windowOptions);
|
|
1059
|
+
if (state.active) return tick.toISOString();
|
|
1060
|
+
if (policy === "skip") {
|
|
1061
|
+
tick = cronNextRun(schedule, tick, timeZone);
|
|
1062
|
+
continue;
|
|
1063
|
+
}
|
|
1064
|
+
// postpone: gate ждёт открытия окна и запускает задачу тогда же.
|
|
1065
|
+
return state.nextOpenAt ? state.nextOpenAt.toISOString() : null;
|
|
1066
|
+
}
|
|
1067
|
+
return null;
|
|
1068
|
+
}
|
|
1069
|
+
|
|
953
1070
|
/** schedule_task — создаёт задачу в schtasks через общий schedulerCreateTask. */
|
|
954
1071
|
const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
|
|
955
1072
|
const {
|
|
@@ -990,6 +1107,7 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
|
|
|
990
1107
|
gitPaths,
|
|
991
1108
|
gitIgnore,
|
|
992
1109
|
gitPollSeconds,
|
|
1110
|
+
runWhenLoggedOff,
|
|
993
1111
|
} = args;
|
|
994
1112
|
|
|
995
1113
|
let effectiveRunAt: string | undefined;
|
|
@@ -1053,7 +1171,9 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
|
|
|
1053
1171
|
gitPaths,
|
|
1054
1172
|
gitIgnore,
|
|
1055
1173
|
gitPollSeconds,
|
|
1056
|
-
}
|
|
1174
|
+
},
|
|
1175
|
+
// Спринт 27.5.4: Windows — работать без входа (/ru SYSTEM).
|
|
1176
|
+
runWhenLoggedOff === true
|
|
1057
1177
|
);
|
|
1058
1178
|
} catch (err: any) {
|
|
1059
1179
|
return {
|
|
@@ -1071,13 +1191,31 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
|
|
|
1071
1191
|
const workspace = workspaceId ? getWorkspace(workspaceId) : undefined;
|
|
1072
1192
|
const effectiveWorkdir =
|
|
1073
1193
|
workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
|
|
1194
|
+
// Спринт 27.5.2: отдаём ближайший запуск сразу, не дожидаясь обновления
|
|
1195
|
+
// списка задач планировщика ОС (schtasks иногда отдаёт nextRunTime с задержкой).
|
|
1196
|
+
const nextRun = computeTaskNextRun({
|
|
1197
|
+
schedule: schedule ?? "",
|
|
1198
|
+
triggerType: triggerType ?? "cron",
|
|
1199
|
+
runAt: effectiveRunAt,
|
|
1200
|
+
timezone,
|
|
1201
|
+
notBefore,
|
|
1202
|
+
notAfter,
|
|
1203
|
+
activeDays,
|
|
1204
|
+
windowPolicy,
|
|
1205
|
+
});
|
|
1074
1206
|
return {
|
|
1075
1207
|
content: JSON.stringify({
|
|
1076
1208
|
success: true,
|
|
1077
|
-
|
|
1209
|
+
paused: false,
|
|
1210
|
+
nextRun,
|
|
1211
|
+
runWhenLoggedOff: runWhenLoggedOff === true,
|
|
1212
|
+
message: t("tool.task.created", { name }),
|
|
1078
1213
|
task: {
|
|
1079
1214
|
name,
|
|
1080
1215
|
schedule,
|
|
1216
|
+
nextRun,
|
|
1217
|
+
paused: false,
|
|
1218
|
+
runWhenLoggedOff: runWhenLoggedOff === true,
|
|
1081
1219
|
timeoutSeconds: timeoutSeconds ?? 3600,
|
|
1082
1220
|
model: model?.trim() || null,
|
|
1083
1221
|
priority: priority ?? 5,
|
|
@@ -1109,14 +1247,18 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
|
|
|
1109
1247
|
|
|
1110
1248
|
/** list_tasks — список задач плагина (та же логика, что и у get_tasks). */
|
|
1111
1249
|
const listTasksExecute = wrapExecute<ListArgs>(async () => {
|
|
1112
|
-
const tasks = await collectTasksView();
|
|
1250
|
+
const { tasks, osAvailable, osError } = await collectTasksView();
|
|
1113
1251
|
|
|
1114
1252
|
if (tasks.length === 0) {
|
|
1115
1253
|
return {
|
|
1116
1254
|
content: JSON.stringify({
|
|
1117
1255
|
success: true,
|
|
1118
|
-
message:
|
|
1256
|
+
message: osAvailable
|
|
1257
|
+
? t("tool.task.listEmpty")
|
|
1258
|
+
: t("tool.task.listOsUnavailable"),
|
|
1119
1259
|
tasks: [],
|
|
1260
|
+
osAvailable,
|
|
1261
|
+
...(osError ? { osError } : {}),
|
|
1120
1262
|
}),
|
|
1121
1263
|
};
|
|
1122
1264
|
}
|
|
@@ -1124,8 +1266,12 @@ const listTasksExecute = wrapExecute<ListArgs>(async () => {
|
|
|
1124
1266
|
return {
|
|
1125
1267
|
content: JSON.stringify({
|
|
1126
1268
|
success: true,
|
|
1127
|
-
message:
|
|
1269
|
+
message: osAvailable
|
|
1270
|
+
? t("tool.task.found", { count: tasks.length })
|
|
1271
|
+
: t("tool.task.foundOsUnavailable", { count: tasks.length }),
|
|
1128
1272
|
tasks,
|
|
1273
|
+
osAvailable,
|
|
1274
|
+
...(osError ? { osError } : {}),
|
|
1129
1275
|
}),
|
|
1130
1276
|
};
|
|
1131
1277
|
});
|
|
@@ -1143,7 +1289,7 @@ async function cancelMatrixRun(
|
|
|
1143
1289
|
(def) => def.name.toLowerCase() === name.trim().toLowerCase()
|
|
1144
1290
|
);
|
|
1145
1291
|
if (!definition?.matrix) {
|
|
1146
|
-
throw new Error(
|
|
1292
|
+
throw new Error(t("tool.error.matrixNotMatrix", { name }));
|
|
1147
1293
|
}
|
|
1148
1294
|
|
|
1149
1295
|
const result = await cancelPendingMatrixClones(definition.name);
|
|
@@ -1160,9 +1306,10 @@ async function cancelMatrixRun(
|
|
|
1160
1306
|
await scheduler.deleteTask(clone.name);
|
|
1161
1307
|
} catch (err: any) {
|
|
1162
1308
|
warnings.push(
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1309
|
+
t("tool.matrix.stopFailed", {
|
|
1310
|
+
clone: clone.name,
|
|
1311
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1312
|
+
})
|
|
1166
1313
|
);
|
|
1167
1314
|
continue;
|
|
1168
1315
|
}
|
|
@@ -1197,30 +1344,40 @@ async function cancelMatrixRun(
|
|
|
1197
1344
|
clone.timezone,
|
|
1198
1345
|
clone.notBefore,
|
|
1199
1346
|
clone.notAfter,
|
|
1200
|
-
clone.pausedUntil
|
|
1347
|
+
clone.pausedUntil,
|
|
1348
|
+
clone.runAt,
|
|
1349
|
+
clone.session,
|
|
1350
|
+
clone.sessionId,
|
|
1351
|
+
clone.sessionMaxRuns,
|
|
1352
|
+
undefined,
|
|
1353
|
+
clone.runWhenLoggedOff,
|
|
1354
|
+
clone.paused
|
|
1201
1355
|
);
|
|
1202
1356
|
} catch (err: any) {
|
|
1203
1357
|
warnings.push(
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1358
|
+
t("tool.matrix.recreateFailed", {
|
|
1359
|
+
clone: clone.name,
|
|
1360
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1361
|
+
})
|
|
1207
1362
|
);
|
|
1208
1363
|
}
|
|
1209
1364
|
}
|
|
1210
1365
|
|
|
1211
1366
|
const parts = [
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1367
|
+
t("tool.matrix.cancelSummary", {
|
|
1368
|
+
matrix: definition.name,
|
|
1369
|
+
cancelled: result.cancelled.length,
|
|
1370
|
+
total: result.aggregate.totalCount,
|
|
1371
|
+
}),
|
|
1215
1372
|
];
|
|
1216
1373
|
if (result.running.length > 0) {
|
|
1217
|
-
parts.push(
|
|
1374
|
+
parts.push(t("tool.matrix.cancelRunning", { count: result.running.length }));
|
|
1218
1375
|
}
|
|
1219
1376
|
if (result.alreadyFinished.length > 0) {
|
|
1220
|
-
parts.push(
|
|
1377
|
+
parts.push(t("tool.matrix.cancelFinished", { count: result.alreadyFinished.length }));
|
|
1221
1378
|
}
|
|
1222
1379
|
if (warnings.length > 0) {
|
|
1223
|
-
parts.push(
|
|
1380
|
+
parts.push(t("tool.matrix.cancelWarnings", { warnings: warnings.join("; ") }));
|
|
1224
1381
|
}
|
|
1225
1382
|
|
|
1226
1383
|
return {
|
|
@@ -1265,6 +1422,83 @@ async function cleanupOrphanedMatrixTasks(): Promise<string[]> {
|
|
|
1265
1422
|
* - удаление родителя-матрицы каскадно удаляет клоны и агрегатор;
|
|
1266
1423
|
* - удаление клона поодиночке запрещено (защита от «сирот» и вечного running).
|
|
1267
1424
|
*/
|
|
1425
|
+
/**
|
|
1426
|
+
* Удаляет файлы-артефакты задачи (wrapper, prompt, log, lock, env).
|
|
1427
|
+
* Отсутствующие файлы игнорируются — операция идемпотентна.
|
|
1428
|
+
*/
|
|
1429
|
+
async function removeTaskArtifacts(name: string): Promise<void> {
|
|
1430
|
+
const sanitized = sanitizeName(name);
|
|
1431
|
+
const candidates = [
|
|
1432
|
+
path.join(WRAPPER_DIR, `run-${sanitized}.cmd`),
|
|
1433
|
+
path.join(WRAPPER_DIR, `run-${sanitized}.sh`),
|
|
1434
|
+
path.join(PLUGIN_DIR, "prompts", `${sanitized}.txt`),
|
|
1435
|
+
path.join(LOG_DIR, `${sanitized}.log`),
|
|
1436
|
+
path.join(PLUGIN_DIR, "env", `${sanitized}.env`),
|
|
1437
|
+
path.join(LOCK_DIR, `${sanitized}.lock`),
|
|
1438
|
+
path.join(LOCK_DIR, `${sanitized}.lock.defer`),
|
|
1439
|
+
path.join(LOCK_DIR, `${sanitized}.lock.force`),
|
|
1440
|
+
];
|
|
1441
|
+
await Promise.all(candidates.map((file) => fs.unlink(file).catch(() => undefined)));
|
|
1442
|
+
}
|
|
1443
|
+
|
|
1444
|
+
/**
|
|
1445
|
+
* Сборщик мусора по wrapper-ам при старте: удаляет файлы задач, которых
|
|
1446
|
+
* больше нет ни в БД, ни в планировщике ОС. Активные (свежий lock) не трогает.
|
|
1447
|
+
*/
|
|
1448
|
+
async function garbageCollectTaskArtifacts(): Promise<void> {
|
|
1449
|
+
let entries: string[];
|
|
1450
|
+
try {
|
|
1451
|
+
entries = await fs.readdir(WRAPPER_DIR);
|
|
1452
|
+
} catch {
|
|
1453
|
+
return;
|
|
1454
|
+
}
|
|
1455
|
+
const wrappers = entries.filter((file) => /^run-.+\.(cmd|sh)$/.test(file));
|
|
1456
|
+
if (wrappers.length === 0) return;
|
|
1457
|
+
|
|
1458
|
+
const known = new Set<string>();
|
|
1459
|
+
try {
|
|
1460
|
+
for (const task of listTaskDefinitions()) known.add(sanitizeName(task.name));
|
|
1461
|
+
} catch {
|
|
1462
|
+
// БД может быть ещё не готова — тогда опираемся на ОС.
|
|
1463
|
+
}
|
|
1464
|
+
try {
|
|
1465
|
+
for (const task of await scheduler.listTasks()) {
|
|
1466
|
+
known.add(sanitizeName(task.taskName || ""));
|
|
1467
|
+
}
|
|
1468
|
+
} catch {
|
|
1469
|
+
// Планировщик недоступен — не удаляем ничего, чтобы не потерять данные.
|
|
1470
|
+
return;
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
let cleaned = 0;
|
|
1474
|
+
for (const file of wrappers) {
|
|
1475
|
+
const stem = file.replace(/^run-/, "").replace(/\.(cmd|sh)$/, "");
|
|
1476
|
+
const lockPath = path.join(LOCK_DIR, `${stem}.lock`);
|
|
1477
|
+
if (known.has(stem)) continue;
|
|
1478
|
+
try {
|
|
1479
|
+
const stat = await fs.stat(lockPath);
|
|
1480
|
+
if (Date.now() - stat.mtimeMs < STALE_LOCK_MAX_AGE_MS) continue;
|
|
1481
|
+
} catch {
|
|
1482
|
+
// lock-файла нет — можно удалять.
|
|
1483
|
+
}
|
|
1484
|
+
const candidates = [
|
|
1485
|
+
path.join(WRAPPER_DIR, `run-${stem}.cmd`),
|
|
1486
|
+
path.join(WRAPPER_DIR, `run-${stem}.sh`),
|
|
1487
|
+
path.join(PLUGIN_DIR, "prompts", `${stem}.txt`),
|
|
1488
|
+
path.join(LOG_DIR, `${stem}.log`),
|
|
1489
|
+
path.join(PLUGIN_DIR, "env", `${stem}.env`),
|
|
1490
|
+
path.join(LOCK_DIR, `${stem}.lock`),
|
|
1491
|
+
path.join(LOCK_DIR, `${stem}.lock.defer`),
|
|
1492
|
+
path.join(LOCK_DIR, `${stem}.lock.force`),
|
|
1493
|
+
];
|
|
1494
|
+
await Promise.all(candidates.map((pathToFile) => fs.unlink(pathToFile).catch(() => undefined)));
|
|
1495
|
+
cleaned += 1;
|
|
1496
|
+
}
|
|
1497
|
+
if (cleaned > 0) {
|
|
1498
|
+
console.log(`[gc] Вычищено мусорных файлов задач: ${cleaned}`);
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1268
1502
|
async function deleteTaskWithFamily(
|
|
1269
1503
|
name: string
|
|
1270
1504
|
): Promise<{ removed: string[]; existed: boolean }> {
|
|
@@ -1302,6 +1536,8 @@ async function deleteTaskWithFamily(
|
|
|
1302
1536
|
} catch {
|
|
1303
1537
|
// Не критично.
|
|
1304
1538
|
}
|
|
1539
|
+
removeTaskArtifacts(child);
|
|
1540
|
+
|
|
1305
1541
|
removed.push(child);
|
|
1306
1542
|
}
|
|
1307
1543
|
}
|
|
@@ -1312,6 +1548,7 @@ async function deleteTaskWithFamily(
|
|
|
1312
1548
|
} catch {
|
|
1313
1549
|
// Определения могло уже не быть — задача всё равно удалена из ОС.
|
|
1314
1550
|
}
|
|
1551
|
+
removeTaskArtifacts(trimmed);
|
|
1315
1552
|
|
|
1316
1553
|
return { removed, existed };
|
|
1317
1554
|
}
|
|
@@ -1327,8 +1564,8 @@ const deleteTaskExecute = wrapExecute<DeleteArgs>(async (args) => {
|
|
|
1327
1564
|
if (!existed && removed.length === 0) {
|
|
1328
1565
|
return {
|
|
1329
1566
|
content: JSON.stringify({
|
|
1330
|
-
success:
|
|
1331
|
-
|
|
1567
|
+
success: true,
|
|
1568
|
+
message: t("tool.task.alreadyAbsent", { name }),
|
|
1332
1569
|
}),
|
|
1333
1570
|
};
|
|
1334
1571
|
}
|
|
@@ -1337,8 +1574,8 @@ const deleteTaskExecute = wrapExecute<DeleteArgs>(async (args) => {
|
|
|
1337
1574
|
success: true,
|
|
1338
1575
|
message:
|
|
1339
1576
|
removed.length > 0
|
|
1340
|
-
?
|
|
1341
|
-
:
|
|
1577
|
+
? t("tool.task.matrixDeletedList", { name, list: removed.join(", ") })
|
|
1578
|
+
: t("tool.task.deleted", { name }),
|
|
1342
1579
|
}),
|
|
1343
1580
|
};
|
|
1344
1581
|
} catch (err: any) {
|
|
@@ -1372,8 +1609,8 @@ const runTaskNowExecute = wrapExecute<RunNowArgs>(async (args) => {
|
|
|
1372
1609
|
content: JSON.stringify({
|
|
1373
1610
|
success: true,
|
|
1374
1611
|
message: alreadyRunning
|
|
1375
|
-
?
|
|
1376
|
-
:
|
|
1612
|
+
? t("tool.task.alreadyRunning", { name })
|
|
1613
|
+
: t("tool.task.started", { name }),
|
|
1377
1614
|
}),
|
|
1378
1615
|
};
|
|
1379
1616
|
});
|
|
@@ -1425,15 +1662,26 @@ async function removeMatrixChildrenFromScheduler(name: string): Promise<string[]
|
|
|
1425
1662
|
*/
|
|
1426
1663
|
async function updateTaskFromInput(
|
|
1427
1664
|
input: UpdateArgs & { newSchedule?: string; newPrompt?: string }
|
|
1428
|
-
): Promise<{
|
|
1665
|
+
): Promise<{
|
|
1666
|
+
success: boolean;
|
|
1667
|
+
message: string;
|
|
1668
|
+
/** Спринт 27.5.2: состояние и ближайший запуск после обновления. */
|
|
1669
|
+
paused?: boolean;
|
|
1670
|
+
nextRun?: string | null;
|
|
1671
|
+
/**
|
|
1672
|
+
* Спринт 27.5.6: при ошибке обновления — удалось ли сохранить прежнюю
|
|
1673
|
+
* версию задачи в планировщике (true — старая версия на месте).
|
|
1674
|
+
*/
|
|
1675
|
+
restored?: boolean;
|
|
1676
|
+
}> {
|
|
1429
1677
|
const name = input.name?.trim();
|
|
1430
1678
|
if (!name) {
|
|
1431
|
-
return { success: false, message: "
|
|
1679
|
+
return { success: false, message: t("tool.error.taskNameMissing") };
|
|
1432
1680
|
}
|
|
1433
1681
|
|
|
1434
1682
|
const previous = getTask(name);
|
|
1435
1683
|
if (!previous) {
|
|
1436
|
-
return { success: false, message:
|
|
1684
|
+
return { success: false, message: t("tool.error.taskNotFound", { name }) };
|
|
1437
1685
|
}
|
|
1438
1686
|
|
|
1439
1687
|
const schedule = clearableString(input.schedule ?? input.newSchedule, previous.schedule);
|
|
@@ -1446,13 +1694,13 @@ async function updateTaskFromInput(
|
|
|
1446
1694
|
if (triggerType === "cron" && !schedule) {
|
|
1447
1695
|
return {
|
|
1448
1696
|
success: false,
|
|
1449
|
-
message:
|
|
1697
|
+
message: t("tool.error.updateCron", { name }),
|
|
1450
1698
|
};
|
|
1451
1699
|
}
|
|
1452
1700
|
if (!prompt) {
|
|
1453
1701
|
return {
|
|
1454
1702
|
success: false,
|
|
1455
|
-
message:
|
|
1703
|
+
message: t("tool.error.updatePrompt", { name }),
|
|
1456
1704
|
};
|
|
1457
1705
|
}
|
|
1458
1706
|
|
|
@@ -1473,7 +1721,7 @@ async function updateTaskFromInput(
|
|
|
1473
1721
|
if (!normalized.ok) {
|
|
1474
1722
|
return {
|
|
1475
1723
|
success: false,
|
|
1476
|
-
message:
|
|
1724
|
+
message: t("tool.error.taskReason", { name, error: normalized.error }),
|
|
1477
1725
|
};
|
|
1478
1726
|
}
|
|
1479
1727
|
runAt = normalized.runAt;
|
|
@@ -1487,7 +1735,7 @@ async function updateTaskFromInput(
|
|
|
1487
1735
|
if (!normalizedSession) {
|
|
1488
1736
|
return {
|
|
1489
1737
|
success: false,
|
|
1490
|
-
message:
|
|
1738
|
+
message: t("tool.error.sessionUnknown", { name, session: String(input.session) }),
|
|
1491
1739
|
};
|
|
1492
1740
|
}
|
|
1493
1741
|
session = normalizedSession;
|
|
@@ -1502,7 +1750,7 @@ async function updateTaskFromInput(
|
|
|
1502
1750
|
) {
|
|
1503
1751
|
return {
|
|
1504
1752
|
success: false,
|
|
1505
|
-
message:
|
|
1753
|
+
message: t("tool.error.sessionMaxRuns", { name }),
|
|
1506
1754
|
};
|
|
1507
1755
|
}
|
|
1508
1756
|
let sessionId = previous.sessionId;
|
|
@@ -1519,9 +1767,7 @@ async function updateTaskFromInput(
|
|
|
1519
1767
|
if (triggerType === "once" && matrixNext) {
|
|
1520
1768
|
return {
|
|
1521
1769
|
success: false,
|
|
1522
|
-
message:
|
|
1523
|
-
`Задача "${name}": one-shot нельзя комбинировать с matrix. ` +
|
|
1524
|
-
`Запустите матрицу вручную или используйте cron/file-триггер.`,
|
|
1770
|
+
message: t("tool.error.oneShotMatrix", { name }),
|
|
1525
1771
|
};
|
|
1526
1772
|
}
|
|
1527
1773
|
|
|
@@ -1553,9 +1799,18 @@ async function updateTaskFromInput(
|
|
|
1553
1799
|
gitPollSeconds: input.gitPollSeconds ?? previous.gitPollSeconds,
|
|
1554
1800
|
};
|
|
1555
1801
|
|
|
1802
|
+
// Спринт 27.5.8: update = пересоздание задачи, поэтому паузу нужно вернуть
|
|
1803
|
+
// после create — иначе задача молча начинает выполняться по расписанию.
|
|
1804
|
+
const wasPaused = Boolean(
|
|
1805
|
+
previous.paused === true ||
|
|
1806
|
+
(previous.pausedUntil && Date.parse(previous.pausedUntil) > Date.now())
|
|
1807
|
+
);
|
|
1808
|
+
|
|
1809
|
+
let previousDeleted = false;
|
|
1556
1810
|
try {
|
|
1557
1811
|
// Обновление = пересоздание в планировщике с сохранением старых значений.
|
|
1558
1812
|
await scheduler.deleteTask(name);
|
|
1813
|
+
previousDeleted = true;
|
|
1559
1814
|
await schedulerCreateTask(
|
|
1560
1815
|
name,
|
|
1561
1816
|
schedule ?? "",
|
|
@@ -1591,7 +1846,9 @@ async function updateTaskFromInput(
|
|
|
1591
1846
|
session,
|
|
1592
1847
|
sessionId,
|
|
1593
1848
|
sessionMaxRuns,
|
|
1594
|
-
triggerExtras
|
|
1849
|
+
triggerExtras,
|
|
1850
|
+
input.runWhenLoggedOff ?? previous.runWhenLoggedOff,
|
|
1851
|
+
wasPaused
|
|
1595
1852
|
);
|
|
1596
1853
|
|
|
1597
1854
|
// Матрица отключена при обновлении — убираем клонов и агрегатор.
|
|
@@ -1603,12 +1860,59 @@ async function updateTaskFromInput(
|
|
|
1603
1860
|
// пересобираем набор файловых watcher-ов.
|
|
1604
1861
|
await refreshTriggers();
|
|
1605
1862
|
|
|
1606
|
-
|
|
1607
|
-
|
|
1863
|
+
// Спринт 27.5.2: после пересоздания задачи сообщаем ближайший запуск,
|
|
1864
|
+
// рассчитанный из нового определения, не дожидаясь ОС.
|
|
1865
|
+
const updated = getTask(name);
|
|
1866
|
+
const paused = wasPaused;
|
|
1608
1867
|
return {
|
|
1609
|
-
success:
|
|
1610
|
-
|
|
1868
|
+
success: true,
|
|
1869
|
+
paused,
|
|
1870
|
+
nextRun: computeTaskNextRun(updated, { paused }),
|
|
1871
|
+
message: t("tool.task.updated", { name }),
|
|
1611
1872
|
};
|
|
1873
|
+
} catch (err: any) {
|
|
1874
|
+
const cause = err instanceof Error ? err.message : String(err);
|
|
1875
|
+
|
|
1876
|
+
// Спринт 27.5.6: задача удалена из ОС, но новую версию создать не удалось.
|
|
1877
|
+
if (!previousDeleted) {
|
|
1878
|
+
return {
|
|
1879
|
+
success: false,
|
|
1880
|
+
restored: true,
|
|
1881
|
+
message: t("tool.task.rollbackKept", { cause }),
|
|
1882
|
+
};
|
|
1883
|
+
}
|
|
1884
|
+
|
|
1885
|
+
// Убираем возможный частичный результат новой попытки: обёртка могла
|
|
1886
|
+
// успеть зарегистрироваться, хотя create вернул ошибку.
|
|
1887
|
+
try {
|
|
1888
|
+
await scheduler.deleteTask(name);
|
|
1889
|
+
} catch {
|
|
1890
|
+
// Задачи могло не быть — это ожидаемо.
|
|
1891
|
+
}
|
|
1892
|
+
|
|
1893
|
+
// Определение в БД ещё не перезаписано, поэтому восстанавливаем ровно
|
|
1894
|
+
// прежнюю версию: расписание, промпт, обёртку и паузу.
|
|
1895
|
+
try {
|
|
1896
|
+
await recreateTaskFromDefinition(previous);
|
|
1897
|
+
await refreshTriggers().catch(() => undefined);
|
|
1898
|
+
return {
|
|
1899
|
+
success: false,
|
|
1900
|
+
restored: true,
|
|
1901
|
+
message: t("tool.task.rollbackRestored", { cause }),
|
|
1902
|
+
};
|
|
1903
|
+
} catch (restoreErr: any) {
|
|
1904
|
+
const restoreMessage =
|
|
1905
|
+
restoreErr instanceof Error ? restoreErr.message : String(restoreErr);
|
|
1906
|
+
return {
|
|
1907
|
+
success: false,
|
|
1908
|
+
restored: false,
|
|
1909
|
+
message: t("tool.task.rollbackFailed", {
|
|
1910
|
+
cause,
|
|
1911
|
+
restore: restoreMessage,
|
|
1912
|
+
name,
|
|
1913
|
+
}),
|
|
1914
|
+
};
|
|
1915
|
+
}
|
|
1612
1916
|
}
|
|
1613
1917
|
}
|
|
1614
1918
|
|
|
@@ -1626,15 +1930,27 @@ async function pauseOrResumeTask(
|
|
|
1626
1930
|
name: string,
|
|
1627
1931
|
paused: boolean,
|
|
1628
1932
|
until?: string
|
|
1629
|
-
): Promise<{
|
|
1933
|
+
): Promise<{
|
|
1934
|
+
success: boolean;
|
|
1935
|
+
message: string;
|
|
1936
|
+
affected: string[];
|
|
1937
|
+
warnings: string[];
|
|
1938
|
+
/** Спринт 27.5.2: состояние и ближайший запуск после мутации. */
|
|
1939
|
+
paused: boolean;
|
|
1940
|
+
nextRun: string | null;
|
|
1941
|
+
pausedUntil: string | null;
|
|
1942
|
+
}> {
|
|
1630
1943
|
const trimmed = name.trim();
|
|
1631
1944
|
const definition = getTask(trimmed);
|
|
1632
1945
|
if (!definition) {
|
|
1633
1946
|
return {
|
|
1634
1947
|
success: false,
|
|
1635
|
-
message:
|
|
1948
|
+
message: t("tool.error.taskNotFound", { name: trimmed }),
|
|
1636
1949
|
affected: [],
|
|
1637
1950
|
warnings: [],
|
|
1951
|
+
paused,
|
|
1952
|
+
nextRun: null,
|
|
1953
|
+
pausedUntil: null,
|
|
1638
1954
|
};
|
|
1639
1955
|
}
|
|
1640
1956
|
|
|
@@ -1645,17 +1961,23 @@ async function pauseOrResumeTask(
|
|
|
1645
1961
|
if (Number.isNaN(parsed)) {
|
|
1646
1962
|
return {
|
|
1647
1963
|
success: false,
|
|
1648
|
-
message:
|
|
1964
|
+
message: t("tool.error.pauseDateInvalid", { name: trimmed, until }),
|
|
1649
1965
|
affected: [],
|
|
1650
1966
|
warnings: [],
|
|
1967
|
+
paused,
|
|
1968
|
+
nextRun: null,
|
|
1969
|
+
pausedUntil: definition.pausedUntil ?? null,
|
|
1651
1970
|
};
|
|
1652
1971
|
}
|
|
1653
1972
|
if (parsed <= Date.now()) {
|
|
1654
1973
|
return {
|
|
1655
1974
|
success: false,
|
|
1656
|
-
message:
|
|
1975
|
+
message: t("tool.error.pauseDatePast", { name: trimmed }),
|
|
1657
1976
|
affected: [],
|
|
1658
1977
|
warnings: [],
|
|
1978
|
+
paused,
|
|
1979
|
+
nextRun: null,
|
|
1980
|
+
pausedUntil: definition.pausedUntil ?? null,
|
|
1659
1981
|
};
|
|
1660
1982
|
}
|
|
1661
1983
|
pausedUntil = new Date(parsed).toISOString();
|
|
@@ -1667,9 +1989,12 @@ async function pauseOrResumeTask(
|
|
|
1667
1989
|
if (targets.length === 0 && definition.matrix) {
|
|
1668
1990
|
return {
|
|
1669
1991
|
success: false,
|
|
1670
|
-
message:
|
|
1992
|
+
message: t("tool.error.matrixNoClones", { name: trimmed }),
|
|
1671
1993
|
affected: [],
|
|
1672
1994
|
warnings: [],
|
|
1995
|
+
paused,
|
|
1996
|
+
nextRun: null,
|
|
1997
|
+
pausedUntil: definition.pausedUntil ?? null,
|
|
1673
1998
|
};
|
|
1674
1999
|
}
|
|
1675
2000
|
|
|
@@ -1690,42 +2015,69 @@ async function pauseOrResumeTask(
|
|
|
1690
2015
|
}
|
|
1691
2016
|
}
|
|
1692
2017
|
|
|
1693
|
-
// Фиксируем (или снимаем)
|
|
2018
|
+
// Фиксируем (или снимаем) паузу в определении задачи. У матрицы
|
|
1694
2019
|
// родитель хранит pausedUntil за всех клонов — их включает авто-resume.
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
: definition.pausedUntil
|
|
1700
|
-
? { pausedUntil: undefined }
|
|
2020
|
+
// Спринт 27.5.8: бессрочная пауза тоже сохраняется в определении, иначе
|
|
2021
|
+
// update_task пересоздаёт задачу включённой и пауза теряется.
|
|
2022
|
+
const definitionUpdates: Partial<TaskDefinition> | undefined = paused
|
|
2023
|
+
? { paused: true, ...(pausedUntil ? { pausedUntil } : {}) }
|
|
2024
|
+
: definition.paused || definition.pausedUntil
|
|
2025
|
+
? { paused: false, pausedUntil: undefined }
|
|
1701
2026
|
: undefined;
|
|
1702
2027
|
if (definitionUpdates && affected.length > 0) {
|
|
1703
2028
|
try {
|
|
1704
2029
|
saveTask({ ...definition, ...definitionUpdates });
|
|
1705
2030
|
} catch (err: any) {
|
|
1706
2031
|
warnings.push(
|
|
1707
|
-
|
|
1708
|
-
err instanceof Error ? err.message : String(err)
|
|
1709
|
-
}
|
|
2032
|
+
t("tool.task.autosave", {
|
|
2033
|
+
error: err instanceof Error ? err.message : String(err),
|
|
2034
|
+
})
|
|
1710
2035
|
);
|
|
1711
2036
|
}
|
|
1712
2037
|
}
|
|
1713
2038
|
|
|
1714
2039
|
const untilText = pausedUntil
|
|
1715
|
-
?
|
|
2040
|
+
? t("tool.task.until", { date: new Date(pausedUntil).toLocaleString() })
|
|
1716
2041
|
: "";
|
|
1717
|
-
const verb = paused ? "
|
|
2042
|
+
const verb = paused ? t("tool.task.paused") : t("tool.task.resumed");
|
|
1718
2043
|
const message = definition.matrix
|
|
1719
|
-
?
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
2044
|
+
? t("tool.task.matrixPaused", {
|
|
2045
|
+
name: trimmed,
|
|
2046
|
+
verb,
|
|
2047
|
+
until: untilText,
|
|
2048
|
+
affected: affected.length,
|
|
2049
|
+
total: targets.length,
|
|
2050
|
+
}) +
|
|
2051
|
+
(warnings.length > 0
|
|
2052
|
+
? t("tool.task.matrixPauseErrors", { warnings: warnings.join("; ") })
|
|
2053
|
+
: "")
|
|
2054
|
+
: t("tool.task.pausedText", {
|
|
2055
|
+
name: trimmed,
|
|
2056
|
+
verb,
|
|
2057
|
+
until: untilText,
|
|
2058
|
+
}) +
|
|
2059
|
+
(warnings.length > 0
|
|
2060
|
+
? t("tool.task.pauseError", { warnings: warnings.join("; ") })
|
|
2061
|
+
: "");
|
|
2062
|
+
|
|
2063
|
+
// Спринт 27.5.2: состояние и ближайший запуск считаем из определения —
|
|
2064
|
+
// schtasks после /change (особенно /enable) отдаёт nextRunTime с задержкой.
|
|
2065
|
+
const effectivePausedUntil = paused
|
|
2066
|
+
? pausedUntil ?? definition.pausedUntil ?? null
|
|
2067
|
+
: null;
|
|
2068
|
+
const after = definitionUpdates
|
|
2069
|
+
? { ...definition, ...definitionUpdates }
|
|
2070
|
+
: { ...definition, paused: false, pausedUntil: undefined };
|
|
2071
|
+
const nextRun = paused ? null : computeTaskNextRun(after);
|
|
1723
2072
|
|
|
1724
2073
|
return {
|
|
1725
2074
|
success: warnings.length === 0,
|
|
1726
2075
|
message,
|
|
1727
2076
|
affected,
|
|
1728
2077
|
warnings,
|
|
2078
|
+
paused,
|
|
2079
|
+
nextRun,
|
|
2080
|
+
pausedUntil: effectivePausedUntil,
|
|
1729
2081
|
};
|
|
1730
2082
|
}
|
|
1731
2083
|
|
|
@@ -1765,7 +2117,11 @@ async function resumeExpiredPauses(): Promise<void> {
|
|
|
1765
2117
|
for (const target of targets) {
|
|
1766
2118
|
await scheduler.resumeTask(target);
|
|
1767
2119
|
}
|
|
1768
|
-
await saveTaskDefinition({
|
|
2120
|
+
await saveTaskDefinition({
|
|
2121
|
+
...definition,
|
|
2122
|
+
pausedUntil: undefined,
|
|
2123
|
+
paused: false,
|
|
2124
|
+
});
|
|
1769
2125
|
console.log(
|
|
1770
2126
|
`[windows-scheduler] Автопродолжение: задача "${definition.name}" включена (пауза истекла).`
|
|
1771
2127
|
);
|
|
@@ -1932,7 +2288,7 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
|
|
|
1932
2288
|
return {
|
|
1933
2289
|
content: JSON.stringify({
|
|
1934
2290
|
success: false,
|
|
1935
|
-
error: "
|
|
2291
|
+
error: t("tool.workspace.needPath"),
|
|
1936
2292
|
}),
|
|
1937
2293
|
};
|
|
1938
2294
|
}
|
|
@@ -1959,7 +2315,7 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
|
|
|
1959
2315
|
return {
|
|
1960
2316
|
content: JSON.stringify({
|
|
1961
2317
|
success: false,
|
|
1962
|
-
error: "
|
|
2318
|
+
error: t("tool.workspace.needUpdateId"),
|
|
1963
2319
|
}),
|
|
1964
2320
|
};
|
|
1965
2321
|
}
|
|
@@ -1974,7 +2330,7 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
|
|
|
1974
2330
|
return {
|
|
1975
2331
|
content: JSON.stringify({
|
|
1976
2332
|
success: false,
|
|
1977
|
-
error: "
|
|
2333
|
+
error: t("tool.workspace.notFound"),
|
|
1978
2334
|
}),
|
|
1979
2335
|
};
|
|
1980
2336
|
}
|
|
@@ -1998,7 +2354,7 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
|
|
|
1998
2354
|
return {
|
|
1999
2355
|
content: JSON.stringify({
|
|
2000
2356
|
success: false,
|
|
2001
|
-
error: "
|
|
2357
|
+
error: t("tool.workspace.needDeleteId"),
|
|
2002
2358
|
}),
|
|
2003
2359
|
};
|
|
2004
2360
|
}
|
|
@@ -2007,8 +2363,8 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
|
|
|
2007
2363
|
content: JSON.stringify({
|
|
2008
2364
|
success: deleted,
|
|
2009
2365
|
message: deleted
|
|
2010
|
-
? "
|
|
2011
|
-
: "
|
|
2366
|
+
? t("tool.workspace.deleted")
|
|
2367
|
+
: t("tool.workspace.notFound"),
|
|
2012
2368
|
}),
|
|
2013
2369
|
};
|
|
2014
2370
|
}
|
|
@@ -2056,8 +2412,8 @@ const matrixControlExecute = wrapExecute<MatrixControlArgs>(async (args) => {
|
|
|
2056
2412
|
success: true,
|
|
2057
2413
|
message:
|
|
2058
2414
|
removed.length > 0
|
|
2059
|
-
?
|
|
2060
|
-
: "
|
|
2415
|
+
? t("tool.matrix.orphansRemoved", { count: removed.length })
|
|
2416
|
+
: t("tool.matrix.orphansNone"),
|
|
2061
2417
|
removed,
|
|
2062
2418
|
}),
|
|
2063
2419
|
};
|
|
@@ -2068,7 +2424,7 @@ const matrixControlExecute = wrapExecute<MatrixControlArgs>(async (args) => {
|
|
|
2068
2424
|
return {
|
|
2069
2425
|
content: JSON.stringify({
|
|
2070
2426
|
success: false,
|
|
2071
|
-
error:
|
|
2427
|
+
error: t("tool.matrix.actionName", { action: args.action }),
|
|
2072
2428
|
}),
|
|
2073
2429
|
};
|
|
2074
2430
|
}
|
|
@@ -2137,6 +2493,7 @@ const manageSettingsExecute = wrapExecute<SettingsArgs>(async (args) => {
|
|
|
2137
2493
|
|
|
2138
2494
|
if (
|
|
2139
2495
|
args.maxConcurrent === undefined &&
|
|
2496
|
+
args.locale === undefined &&
|
|
2140
2497
|
args.winterMode === undefined &&
|
|
2141
2498
|
args.notifications === undefined &&
|
|
2142
2499
|
args.history === undefined &&
|
|
@@ -2146,8 +2503,7 @@ const manageSettingsExecute = wrapExecute<SettingsArgs>(async (args) => {
|
|
|
2146
2503
|
return {
|
|
2147
2504
|
content: JSON.stringify({
|
|
2148
2505
|
success: false,
|
|
2149
|
-
error:
|
|
2150
|
-
"Для action=update передайте хотя бы одно поле: maxConcurrent, winterMode, notifications, history, integrations или audit.",
|
|
2506
|
+
error: t("tool.settings.updateFields"),
|
|
2151
2507
|
settings: current,
|
|
2152
2508
|
}),
|
|
2153
2509
|
};
|
|
@@ -2155,12 +2511,15 @@ const manageSettingsExecute = wrapExecute<SettingsArgs>(async (args) => {
|
|
|
2155
2511
|
|
|
2156
2512
|
const settings = await saveSettings({
|
|
2157
2513
|
maxConcurrent: args.maxConcurrent,
|
|
2514
|
+
locale: args.locale,
|
|
2158
2515
|
winterMode: args.winterMode,
|
|
2159
2516
|
notifications: args.notifications as NotificationSettings | undefined,
|
|
2160
2517
|
history: args.history as HistorySettings | undefined,
|
|
2161
2518
|
integrations: args.integrations as IntegrationSettings | undefined,
|
|
2162
2519
|
audit: args.audit as AuditSettings | undefined,
|
|
2163
2520
|
});
|
|
2521
|
+
// Локаль процесса меняется сразу — перезапуск плагина не нужен.
|
|
2522
|
+
setLocale(settings.locale);
|
|
2164
2523
|
return { content: JSON.stringify({ success: true, settings }) };
|
|
2165
2524
|
});
|
|
2166
2525
|
|
|
@@ -2173,7 +2532,7 @@ const manageTemplatesExecute = wrapExecute<TemplatesArgs>(async (args) => {
|
|
|
2173
2532
|
if (args.action === "delete") {
|
|
2174
2533
|
const id = args.id?.trim();
|
|
2175
2534
|
if (!id) {
|
|
2176
|
-
return { content: JSON.stringify({ success: false, error: "
|
|
2535
|
+
return { content: JSON.stringify({ success: false, error: t("tool.template.needDeleteId") }) };
|
|
2177
2536
|
}
|
|
2178
2537
|
const before = await loadTemplates();
|
|
2179
2538
|
const existed = before.some((template) => template.id === id);
|
|
@@ -2181,7 +2540,9 @@ const manageTemplatesExecute = wrapExecute<TemplatesArgs>(async (args) => {
|
|
|
2181
2540
|
return {
|
|
2182
2541
|
content: JSON.stringify({
|
|
2183
2542
|
success: existed,
|
|
2184
|
-
message: existed
|
|
2543
|
+
message: existed
|
|
2544
|
+
? t("tool.template.deleted", { id })
|
|
2545
|
+
: t("tool.template.notFound", { id }),
|
|
2185
2546
|
}),
|
|
2186
2547
|
};
|
|
2187
2548
|
}
|
|
@@ -2191,7 +2552,7 @@ const manageTemplatesExecute = wrapExecute<TemplatesArgs>(async (args) => {
|
|
|
2191
2552
|
return {
|
|
2192
2553
|
content: JSON.stringify({
|
|
2193
2554
|
success: false,
|
|
2194
|
-
error: "
|
|
2555
|
+
error: t("tool.template.saveRequired"),
|
|
2195
2556
|
}),
|
|
2196
2557
|
};
|
|
2197
2558
|
}
|
|
@@ -2217,7 +2578,7 @@ const manageProfilesExecute = wrapExecute<ProfilesArgs>(async (args) => {
|
|
|
2217
2578
|
return {
|
|
2218
2579
|
content: JSON.stringify({
|
|
2219
2580
|
success: false,
|
|
2220
|
-
error:
|
|
2581
|
+
error: t("tool.profile.nameRequired", { action: args.action }),
|
|
2221
2582
|
}),
|
|
2222
2583
|
};
|
|
2223
2584
|
}
|
|
@@ -2228,7 +2589,7 @@ const manageProfilesExecute = wrapExecute<ProfilesArgs>(async (args) => {
|
|
|
2228
2589
|
return {
|
|
2229
2590
|
content: JSON.stringify({
|
|
2230
2591
|
success: true,
|
|
2231
|
-
message:
|
|
2592
|
+
message: t("tool.profile.created", { name: meta.name, port: meta.port }),
|
|
2232
2593
|
profile: profile ?? {
|
|
2233
2594
|
name: meta.name,
|
|
2234
2595
|
dir: getProfileDir(meta.name),
|
|
@@ -2249,8 +2610,8 @@ const manageProfilesExecute = wrapExecute<ProfilesArgs>(async (args) => {
|
|
|
2249
2610
|
current,
|
|
2250
2611
|
restartRequired: true,
|
|
2251
2612
|
message: isProfilePinnedByEnv()
|
|
2252
|
-
?
|
|
2253
|
-
:
|
|
2613
|
+
? t("tool.profile.envVar", { name: current })
|
|
2614
|
+
: t("tool.profile.active", { name: sanitizeProfileName(name) }),
|
|
2254
2615
|
}),
|
|
2255
2616
|
};
|
|
2256
2617
|
}
|
|
@@ -2260,8 +2621,8 @@ const manageProfilesExecute = wrapExecute<ProfilesArgs>(async (args) => {
|
|
|
2260
2621
|
content: JSON.stringify({
|
|
2261
2622
|
success: removed,
|
|
2262
2623
|
message: removed
|
|
2263
|
-
?
|
|
2264
|
-
: "
|
|
2624
|
+
? t("tool.profile.deleted", { name: sanitizeProfileName(name) })
|
|
2625
|
+
: t("tool.profile.notFound"),
|
|
2265
2626
|
}),
|
|
2266
2627
|
};
|
|
2267
2628
|
});
|
|
@@ -2277,14 +2638,14 @@ const transferTasksExecute = wrapExecute<TransferArgs>(async (args) => {
|
|
|
2277
2638
|
}
|
|
2278
2639
|
|
|
2279
2640
|
if (!args.data) {
|
|
2280
|
-
return { content: JSON.stringify({ success: false, error: "
|
|
2641
|
+
return { content: JSON.stringify({ success: false, error: t("tool.transfer.importData") }) };
|
|
2281
2642
|
}
|
|
2282
2643
|
const parsed = parseImportJson(args.data);
|
|
2283
2644
|
if (parsed.tasks.length === 0) {
|
|
2284
2645
|
return {
|
|
2285
2646
|
content: JSON.stringify({
|
|
2286
2647
|
success: false,
|
|
2287
|
-
error: "
|
|
2648
|
+
error: t("tool.transfer.noTasks"),
|
|
2288
2649
|
errors: parsed.errors,
|
|
2289
2650
|
}),
|
|
2290
2651
|
};
|
|
@@ -2372,7 +2733,12 @@ const cleanupHistoryExecute = wrapExecute<CleanupHistoryArgs>(async (args) => {
|
|
|
2372
2733
|
success: true,
|
|
2373
2734
|
message: report.skipped
|
|
2374
2735
|
? report.skipped
|
|
2375
|
-
:
|
|
2736
|
+
: t("tool.history.cleaned", {
|
|
2737
|
+
deleted: report.deleted,
|
|
2738
|
+
byAge: report.deletedByAge,
|
|
2739
|
+
byCount: report.deletedByCount,
|
|
2740
|
+
kept: report.kept,
|
|
2741
|
+
}),
|
|
2376
2742
|
report,
|
|
2377
2743
|
}),
|
|
2378
2744
|
};
|
|
@@ -2382,7 +2748,7 @@ const cleanupHistoryExecute = wrapExecute<CleanupHistoryArgs>(async (args) => {
|
|
|
2382
2748
|
const emitEventExecute = wrapExecute<EmitEventArgs>(async (args) => {
|
|
2383
2749
|
const eventName = args.eventName?.trim();
|
|
2384
2750
|
if (!eventName) {
|
|
2385
|
-
return { content: JSON.stringify({ success: false, error: "
|
|
2751
|
+
return { content: JSON.stringify({ success: false, error: t("tool.event.nameRequired") }) };
|
|
2386
2752
|
}
|
|
2387
2753
|
const payload = args.payload ?? {};
|
|
2388
2754
|
const definitions = await loadTaskDefinitions();
|
|
@@ -2412,8 +2778,8 @@ const emitEventExecute = wrapExecute<EmitEventArgs>(async (args) => {
|
|
|
2412
2778
|
success: true,
|
|
2413
2779
|
message:
|
|
2414
2780
|
triggered.length > 0
|
|
2415
|
-
?
|
|
2416
|
-
:
|
|
2781
|
+
? t("tool.event.triggered", { count: triggered.length })
|
|
2782
|
+
: t("tool.event.none", { event: eventName }),
|
|
2417
2783
|
triggered,
|
|
2418
2784
|
}),
|
|
2419
2785
|
};
|
|
@@ -2430,7 +2796,7 @@ const manageSecretsExecute = wrapExecute<SecretsArgs>(async (args) => {
|
|
|
2430
2796
|
return {
|
|
2431
2797
|
content: JSON.stringify({
|
|
2432
2798
|
success: false,
|
|
2433
|
-
error: "
|
|
2799
|
+
error: t("tool.secret.nameRequired"),
|
|
2434
2800
|
}),
|
|
2435
2801
|
};
|
|
2436
2802
|
}
|
|
@@ -2442,8 +2808,8 @@ const manageSecretsExecute = wrapExecute<SecretsArgs>(async (args) => {
|
|
|
2442
2808
|
content: JSON.stringify({
|
|
2443
2809
|
success: existed,
|
|
2444
2810
|
message: existed
|
|
2445
|
-
?
|
|
2446
|
-
:
|
|
2811
|
+
? t("tool.secret.deleted", { name })
|
|
2812
|
+
: t("tool.secret.notFound", { name }),
|
|
2447
2813
|
}),
|
|
2448
2814
|
};
|
|
2449
2815
|
}
|
|
@@ -2453,7 +2819,7 @@ const manageSecretsExecute = wrapExecute<SecretsArgs>(async (args) => {
|
|
|
2453
2819
|
return {
|
|
2454
2820
|
content: JSON.stringify({
|
|
2455
2821
|
success: false,
|
|
2456
|
-
error: "
|
|
2822
|
+
error: t("tool.secret.valueRequired"),
|
|
2457
2823
|
}),
|
|
2458
2824
|
};
|
|
2459
2825
|
}
|
|
@@ -2462,7 +2828,7 @@ const manageSecretsExecute = wrapExecute<SecretsArgs>(async (args) => {
|
|
|
2462
2828
|
return {
|
|
2463
2829
|
content: JSON.stringify({
|
|
2464
2830
|
success: true,
|
|
2465
|
-
message:
|
|
2831
|
+
message: t("tool.secret.saved", { name: item.name }),
|
|
2466
2832
|
secret: item,
|
|
2467
2833
|
}),
|
|
2468
2834
|
};
|
|
@@ -2726,6 +3092,14 @@ export default Plugin.define({
|
|
|
2726
3092
|
// `opencode run` подхватывает opencode.json с MCP-серверами проекта.
|
|
2727
3093
|
projectDirectory = ctx.location?.directory || process.cwd();
|
|
2728
3094
|
|
|
3095
|
+
// Спринт 28: язык интерфейса берём из настроек. Ошибка чтения не должна
|
|
3096
|
+
// мешать старту — в этом случае остаётся локаль по умолчанию (ru).
|
|
3097
|
+
try {
|
|
3098
|
+
setLocale((await loadSettings()).locale);
|
|
3099
|
+
} catch {
|
|
3100
|
+
// Локаль по умолчанию уже активна.
|
|
3101
|
+
}
|
|
3102
|
+
|
|
2729
3103
|
// Спринт 12: SQLite — основное хранилище. Открываем БД, при первом запуске
|
|
2730
3104
|
// автоматически переносим данные из JSON, затем восстанавливаем прерванные
|
|
2731
3105
|
// запуски. Ошибки миграции не должны мешать плагину стартовать.
|
|
@@ -2749,6 +3123,9 @@ export default Plugin.define({
|
|
|
2749
3123
|
);
|
|
2750
3124
|
}
|
|
2751
3125
|
checkJsonBackups();
|
|
3126
|
+
void garbageCollectTaskArtifacts().catch((err) => {
|
|
3127
|
+
console.log(`[gc] Не удалось вычистить мусорные файлы: ${err instanceof Error ? err.message : String(err)}`);
|
|
3128
|
+
});
|
|
2752
3129
|
|
|
2753
3130
|
// Спринт 18: ежедневная очистка истории. Ошибка ретеншна не должна мешать
|
|
2754
3131
|
// плагину стартовать — пишем в лог и продолжаем.
|
|
@@ -3253,7 +3630,12 @@ export default Plugin.define({
|
|
|
3253
3630
|
// schedule_task и create_task использовали один и тот же путь.
|
|
3254
3631
|
const rpcHandlers = {
|
|
3255
3632
|
get_tasks: async () => {
|
|
3256
|
-
|
|
3633
|
+
const view = await collectTasksView();
|
|
3634
|
+
return {
|
|
3635
|
+
tasks: view.tasks,
|
|
3636
|
+
osAvailable: view.osAvailable,
|
|
3637
|
+
...(view.osError ? { osError: view.osError } : {}),
|
|
3638
|
+
};
|
|
3257
3639
|
},
|
|
3258
3640
|
create_task: async (input: unknown) => {
|
|
3259
3641
|
console.log("[windows-scheduler] create_task input:", input);
|
|
@@ -3286,6 +3668,7 @@ export default Plugin.define({
|
|
|
3286
3668
|
delaySeconds,
|
|
3287
3669
|
session,
|
|
3288
3670
|
sessionMaxRuns,
|
|
3671
|
+
runWhenLoggedOff,
|
|
3289
3672
|
} = input as {
|
|
3290
3673
|
name: string;
|
|
3291
3674
|
schedule?: string;
|
|
@@ -3315,12 +3698,13 @@ export default Plugin.define({
|
|
|
3315
3698
|
delaySeconds?: number;
|
|
3316
3699
|
session?: "new" | "reuse" | "last";
|
|
3317
3700
|
sessionMaxRuns?: number;
|
|
3701
|
+
runWhenLoggedOff?: boolean;
|
|
3318
3702
|
};
|
|
3319
3703
|
let effectiveRunAt: string | undefined;
|
|
3320
3704
|
if (triggerType === "once") {
|
|
3321
3705
|
const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
|
|
3322
3706
|
if (!normalized.ok) {
|
|
3323
|
-
return { success: false, message:
|
|
3707
|
+
return { success: false, message: t("tool.error.taskReason", { name, error: normalized.error }) };
|
|
3324
3708
|
}
|
|
3325
3709
|
effectiveRunAt = normalized.runAt;
|
|
3326
3710
|
}
|
|
@@ -3328,7 +3712,7 @@ export default Plugin.define({
|
|
|
3328
3712
|
if (session !== undefined) {
|
|
3329
3713
|
const normalizedSession = normalizeSessionMode(session);
|
|
3330
3714
|
if (!normalizedSession) {
|
|
3331
|
-
return { success: false, message:
|
|
3715
|
+
return { success: false, message: t("tool.error.sessionUnknown", { name, session: String(session) }) };
|
|
3332
3716
|
}
|
|
3333
3717
|
effectiveSession = normalizedSession;
|
|
3334
3718
|
}
|
|
@@ -3336,7 +3720,7 @@ export default Plugin.define({
|
|
|
3336
3720
|
sessionMaxRuns !== undefined &&
|
|
3337
3721
|
(!Number.isInteger(sessionMaxRuns) || sessionMaxRuns < 1)
|
|
3338
3722
|
) {
|
|
3339
|
-
return { success: false, message:
|
|
3723
|
+
return { success: false, message: t("tool.error.sessionMaxRuns", { name }) };
|
|
3340
3724
|
}
|
|
3341
3725
|
const effectiveSessionId =
|
|
3342
3726
|
effectiveSession === "reuse" ? generateSessionId() : undefined;
|
|
@@ -3373,9 +3757,24 @@ export default Plugin.define({
|
|
|
3373
3757
|
effectiveRunAt,
|
|
3374
3758
|
effectiveSession,
|
|
3375
3759
|
effectiveSessionId,
|
|
3376
|
-
sessionMaxRuns
|
|
3760
|
+
sessionMaxRuns,
|
|
3761
|
+
undefined,
|
|
3762
|
+
runWhenLoggedOff === true
|
|
3377
3763
|
);
|
|
3378
|
-
|
|
3764
|
+
const nextRun = computeTaskNextRun({
|
|
3765
|
+
schedule: schedule ?? "",
|
|
3766
|
+
triggerType: triggerType ?? "cron",
|
|
3767
|
+
runAt: effectiveRunAt,
|
|
3768
|
+
timezone,
|
|
3769
|
+
notBefore,
|
|
3770
|
+
notAfter,
|
|
3771
|
+
});
|
|
3772
|
+
return {
|
|
3773
|
+
success: true,
|
|
3774
|
+
paused: false,
|
|
3775
|
+
nextRun,
|
|
3776
|
+
message: t("tool.task.created", { name }),
|
|
3777
|
+
};
|
|
3379
3778
|
} catch (err: any) {
|
|
3380
3779
|
const message = err instanceof Error ? err.message : String(err);
|
|
3381
3780
|
return { success: false, message };
|
|
@@ -3389,8 +3788,11 @@ export default Plugin.define({
|
|
|
3389
3788
|
success: true,
|
|
3390
3789
|
message:
|
|
3391
3790
|
removed.length > 0
|
|
3392
|
-
?
|
|
3393
|
-
|
|
3791
|
+
? t("tool.task.matrixDeletedCount", {
|
|
3792
|
+
name,
|
|
3793
|
+
count: removed.length,
|
|
3794
|
+
})
|
|
3795
|
+
: t("tool.task.deleted", { name }),
|
|
3394
3796
|
};
|
|
3395
3797
|
} catch (err: any) {
|
|
3396
3798
|
return { success: false, message: err instanceof Error ? err.message : String(err) };
|
|
@@ -3420,8 +3822,8 @@ export default Plugin.define({
|
|
|
3420
3822
|
success: true,
|
|
3421
3823
|
message:
|
|
3422
3824
|
removed.length > 0
|
|
3423
|
-
?
|
|
3424
|
-
: "
|
|
3825
|
+
? t("tool.matrix.orphansRemoved", { count: removed.length })
|
|
3826
|
+
: t("tool.matrix.orphansNone"),
|
|
3425
3827
|
removed,
|
|
3426
3828
|
};
|
|
3427
3829
|
} catch (err: any) {
|
|
@@ -3443,9 +3845,21 @@ export default Plugin.define({
|
|
|
3443
3845
|
const matrixResult = await runMatrix(definition);
|
|
3444
3846
|
const total = definition.matrix.workspaceIds.length;
|
|
3445
3847
|
const message =
|
|
3446
|
-
|
|
3447
|
-
|
|
3448
|
-
|
|
3848
|
+
t("tool.matrix.started", {
|
|
3849
|
+
name,
|
|
3850
|
+
started: matrixResult.started.length,
|
|
3851
|
+
total,
|
|
3852
|
+
}) +
|
|
3853
|
+
(matrixResult.skipped.length
|
|
3854
|
+
? t("tool.matrix.startedSkipped", {
|
|
3855
|
+
count: matrixResult.skipped.length,
|
|
3856
|
+
})
|
|
3857
|
+
: "") +
|
|
3858
|
+
(matrixResult.errors.length
|
|
3859
|
+
? t("tool.matrix.startedErrors", {
|
|
3860
|
+
errors: matrixResult.errors.join("; "),
|
|
3861
|
+
})
|
|
3862
|
+
: ".");
|
|
3449
3863
|
return { success: matrixResult.success, message };
|
|
3450
3864
|
}
|
|
3451
3865
|
// Контроль параллелизма: не позволяем запускать новую задачу,
|
|
@@ -3460,7 +3874,7 @@ export default Plugin.define({
|
|
|
3460
3874
|
return {
|
|
3461
3875
|
success: false,
|
|
3462
3876
|
message:
|
|
3463
|
-
"
|
|
3877
|
+
t("tool.matrix.limit"),
|
|
3464
3878
|
};
|
|
3465
3879
|
}
|
|
3466
3880
|
}
|
|
@@ -3470,9 +3884,9 @@ export default Plugin.define({
|
|
|
3470
3884
|
// в том числе инициированном из GUI, — дублировать запись здесь не нужно.
|
|
3471
3885
|
if (result.alreadyRunning) {
|
|
3472
3886
|
// Мягкое предупреждение: задача уже идёт, это не ошибка запуска.
|
|
3473
|
-
return { success: true, message:
|
|
3887
|
+
return { success: true, message: t("tool.task.alreadyRunning", { name }) };
|
|
3474
3888
|
}
|
|
3475
|
-
return { success: true, message:
|
|
3889
|
+
return { success: true, message: t("tool.task.started", { name }) };
|
|
3476
3890
|
} catch (err: any) {
|
|
3477
3891
|
return { success: false, message: `schtasks error: ${err instanceof Error ? err.message : String(err)}` };
|
|
3478
3892
|
}
|
|
@@ -3484,7 +3898,7 @@ export default Plugin.define({
|
|
|
3484
3898
|
};
|
|
3485
3899
|
const normalized = eventName?.trim();
|
|
3486
3900
|
if (!normalized) {
|
|
3487
|
-
return { success: false, message: "
|
|
3901
|
+
return { success: false, message: t("tool.event.nameRequiredShort"), triggered: [] };
|
|
3488
3902
|
}
|
|
3489
3903
|
|
|
3490
3904
|
// Ищем задачи с MCP-триггером, совпадающим по имени события и фильтру.
|
|
@@ -3521,18 +3935,18 @@ export default Plugin.define({
|
|
|
3521
3935
|
return {
|
|
3522
3936
|
success: true,
|
|
3523
3937
|
triggered,
|
|
3524
|
-
message:
|
|
3938
|
+
message: t("tool.event.processed", { event: normalized, count: triggered.length }),
|
|
3525
3939
|
};
|
|
3526
3940
|
},
|
|
3527
3941
|
pause_task: async (input: unknown) => {
|
|
3528
3942
|
const { name, until } = input as { name: string; until?: string };
|
|
3529
3943
|
const result = await pauseOrResumeTask(name, true, until);
|
|
3530
|
-
return
|
|
3944
|
+
return result;
|
|
3531
3945
|
},
|
|
3532
3946
|
resume_task: async (input: unknown) => {
|
|
3533
3947
|
const { name } = input as { name: string };
|
|
3534
3948
|
const result = await pauseOrResumeTask(name, false);
|
|
3535
|
-
return
|
|
3949
|
+
return result;
|
|
3536
3950
|
},
|
|
3537
3951
|
update_task: async (input: unknown) => {
|
|
3538
3952
|
return await updateTaskFromInput(input as UpdateArgs);
|
|
@@ -3575,8 +3989,12 @@ export default Plugin.define({
|
|
|
3575
3989
|
const report = await runHistoryRetention({ retentionDays, maxRecords });
|
|
3576
3990
|
const message = report.skipped
|
|
3577
3991
|
? report.skipped
|
|
3578
|
-
:
|
|
3579
|
-
|
|
3992
|
+
: t("tool.history.cleaned", {
|
|
3993
|
+
deleted: report.deleted,
|
|
3994
|
+
byAge: report.deletedByAge,
|
|
3995
|
+
byCount: report.deletedByCount,
|
|
3996
|
+
kept: report.kept,
|
|
3997
|
+
});
|
|
3580
3998
|
return {
|
|
3581
3999
|
success: true,
|
|
3582
4000
|
message,
|
|
@@ -3591,9 +4009,9 @@ export default Plugin.define({
|
|
|
3591
4009
|
} catch (err: any) {
|
|
3592
4010
|
return {
|
|
3593
4011
|
success: false,
|
|
3594
|
-
message:
|
|
3595
|
-
err instanceof Error ? err.message : String(err)
|
|
3596
|
-
}
|
|
4012
|
+
message: t("tool.history.cleanFailed", {
|
|
4013
|
+
error: err instanceof Error ? err.message : String(err),
|
|
4014
|
+
}),
|
|
3597
4015
|
deleted: 0,
|
|
3598
4016
|
deletedByAge: 0,
|
|
3599
4017
|
deletedByCount: 0,
|
|
@@ -3677,7 +4095,7 @@ export default Plugin.define({
|
|
|
3677
4095
|
const { parentId } = input as { parentId?: string; name?: string };
|
|
3678
4096
|
const target = (parentId ?? "").trim();
|
|
3679
4097
|
if (!target) {
|
|
3680
|
-
return { success: false, error: "
|
|
4098
|
+
return { success: false, error: t("tool.matrix.parentMissing") };
|
|
3681
4099
|
}
|
|
3682
4100
|
try {
|
|
3683
4101
|
const report = aggregateMatrixResults(target);
|
|
@@ -3770,7 +4188,7 @@ export default Plugin.define({
|
|
|
3770
4188
|
};
|
|
3771
4189
|
const workspace = updateWorkspace(id, { name, path: workspacePath, color, env, envFile });
|
|
3772
4190
|
if (!workspace) {
|
|
3773
|
-
return { success: false, error: "
|
|
4191
|
+
return { success: false, error: t("tool.workspace.notFound") };
|
|
3774
4192
|
}
|
|
3775
4193
|
// env-файлы существующих задач перегенерируются сразу (Спринт 21).
|
|
3776
4194
|
await refreshWorkspaceEnvFiles(workspace.id);
|
|
@@ -3793,8 +4211,8 @@ export default Plugin.define({
|
|
|
3793
4211
|
return {
|
|
3794
4212
|
success: deleted,
|
|
3795
4213
|
message: deleted
|
|
3796
|
-
? "
|
|
3797
|
-
: "
|
|
4214
|
+
? t("tool.workspace.deleted")
|
|
4215
|
+
: t("tool.workspace.notFound"),
|
|
3798
4216
|
};
|
|
3799
4217
|
} catch (err: any) {
|
|
3800
4218
|
return { success: false, message: err instanceof Error ? err.message : String(err) };
|
|
@@ -3817,8 +4235,8 @@ export default Plugin.define({
|
|
|
3817
4235
|
current,
|
|
3818
4236
|
restartRequired: true,
|
|
3819
4237
|
message: isProfilePinnedByEnv()
|
|
3820
|
-
?
|
|
3821
|
-
:
|
|
4238
|
+
? t("tool.profile.envVarLong", { name: current })
|
|
4239
|
+
: t("tool.profile.active", { name: sanitizeProfileName(name) }),
|
|
3822
4240
|
};
|
|
3823
4241
|
} catch (err: any) {
|
|
3824
4242
|
return {
|
|
@@ -3836,7 +4254,7 @@ export default Plugin.define({
|
|
|
3836
4254
|
const profile = listProfiles().find((item) => item.name === meta.name);
|
|
3837
4255
|
return {
|
|
3838
4256
|
success: true,
|
|
3839
|
-
message:
|
|
4257
|
+
message: t("tool.profile.created", { name: meta.name, port: meta.port }),
|
|
3840
4258
|
profile: profile ?? {
|
|
3841
4259
|
name: meta.name,
|
|
3842
4260
|
dir: getProfileDir(meta.name),
|
|
@@ -3859,8 +4277,8 @@ export default Plugin.define({
|
|
|
3859
4277
|
return {
|
|
3860
4278
|
success: removed,
|
|
3861
4279
|
message: removed
|
|
3862
|
-
?
|
|
3863
|
-
: "
|
|
4280
|
+
? t("tool.profile.deleted", { name: sanitizeProfileName(name) })
|
|
4281
|
+
: t("tool.profile.notFound"),
|
|
3864
4282
|
};
|
|
3865
4283
|
} catch (err: any) {
|
|
3866
4284
|
return { success: false, message: err instanceof Error ? err.message : String(err) };
|
|
@@ -3870,8 +4288,9 @@ export default Plugin.define({
|
|
|
3870
4288
|
return await loadSettings();
|
|
3871
4289
|
},
|
|
3872
4290
|
save_settings: async (input: unknown) => {
|
|
3873
|
-
const { maxConcurrent, winterMode, notifications, history, integrations, audit } = input as {
|
|
4291
|
+
const { maxConcurrent, locale, winterMode, notifications, history, integrations, audit } = input as {
|
|
3874
4292
|
maxConcurrent?: number;
|
|
4293
|
+
locale?: Locale;
|
|
3875
4294
|
winterMode?: boolean;
|
|
3876
4295
|
notifications?: NotificationSettings;
|
|
3877
4296
|
history?: HistorySettings;
|
|
@@ -3881,6 +4300,7 @@ export default Plugin.define({
|
|
|
3881
4300
|
const current = await loadSettings();
|
|
3882
4301
|
if (
|
|
3883
4302
|
maxConcurrent === undefined &&
|
|
4303
|
+
locale === undefined &&
|
|
3884
4304
|
winterMode === undefined &&
|
|
3885
4305
|
notifications === undefined &&
|
|
3886
4306
|
history === undefined &&
|
|
@@ -3890,6 +4310,7 @@ export default Plugin.define({
|
|
|
3890
4310
|
return {
|
|
3891
4311
|
success: false,
|
|
3892
4312
|
maxConcurrent: current.maxConcurrent,
|
|
4313
|
+
locale: current.locale,
|
|
3893
4314
|
winterMode: current.winterMode,
|
|
3894
4315
|
notifications: current.notifications,
|
|
3895
4316
|
history: current.history,
|
|
@@ -3899,15 +4320,19 @@ export default Plugin.define({
|
|
|
3899
4320
|
}
|
|
3900
4321
|
const settings = await saveSettings({
|
|
3901
4322
|
maxConcurrent,
|
|
4323
|
+
locale,
|
|
3902
4324
|
winterMode,
|
|
3903
4325
|
notifications,
|
|
3904
4326
|
history,
|
|
3905
4327
|
integrations,
|
|
3906
4328
|
audit,
|
|
3907
4329
|
});
|
|
4330
|
+
// Локаль процесса меняется сразу — перезапуск не нужен.
|
|
4331
|
+
setLocale(settings.locale);
|
|
3908
4332
|
return {
|
|
3909
4333
|
success: true,
|
|
3910
4334
|
maxConcurrent: settings.maxConcurrent,
|
|
4335
|
+
locale: settings.locale,
|
|
3911
4336
|
winterMode: settings.winterMode,
|
|
3912
4337
|
notifications: settings.notifications,
|
|
3913
4338
|
history: settings.history,
|
|
@@ -3932,15 +4357,15 @@ export default Plugin.define({
|
|
|
3932
4357
|
const source = (input ?? {}) as { name?: string; value?: string };
|
|
3933
4358
|
const name = (source.name ?? "").trim();
|
|
3934
4359
|
if (!name) {
|
|
3935
|
-
return { success: false, message: "
|
|
4360
|
+
return { success: false, message: t("tool.secret.needName") };
|
|
3936
4361
|
}
|
|
3937
4362
|
if (typeof source.value !== "string" || source.value.length === 0) {
|
|
3938
|
-
return { success: false, message: "
|
|
4363
|
+
return { success: false, message: t("tool.secret.needValue") };
|
|
3939
4364
|
}
|
|
3940
4365
|
const secret = setSecret(name, source.value);
|
|
3941
4366
|
return {
|
|
3942
4367
|
success: true,
|
|
3943
|
-
message:
|
|
4368
|
+
message: t("tool.secret.saved", { name: secret.name }),
|
|
3944
4369
|
secret,
|
|
3945
4370
|
};
|
|
3946
4371
|
} catch (err: any) {
|
|
@@ -3954,15 +4379,15 @@ export default Plugin.define({
|
|
|
3954
4379
|
try {
|
|
3955
4380
|
const name = (((input ?? {}) as { name?: string }).name ?? "").trim();
|
|
3956
4381
|
if (!name) {
|
|
3957
|
-
return { success: false, message: "
|
|
4382
|
+
return { success: false, message: t("tool.secret.needName") };
|
|
3958
4383
|
}
|
|
3959
4384
|
const existed = hasSecret(name);
|
|
3960
4385
|
deleteSecret(name);
|
|
3961
4386
|
return {
|
|
3962
4387
|
success: existed,
|
|
3963
4388
|
message: existed
|
|
3964
|
-
?
|
|
3965
|
-
:
|
|
4389
|
+
? t("tool.secret.deleted", { name })
|
|
4390
|
+
: t("tool.secret.notFound", { name }),
|
|
3966
4391
|
};
|
|
3967
4392
|
} catch (err: any) {
|
|
3968
4393
|
return {
|
|
@@ -4007,7 +4432,7 @@ export default Plugin.define({
|
|
|
4007
4432
|
if (!source?.name?.trim() || !source?.prompt?.trim()) {
|
|
4008
4433
|
return {
|
|
4009
4434
|
success: false,
|
|
4010
|
-
error: "
|
|
4435
|
+
error: t("tool.template.namePromptRequired"),
|
|
4011
4436
|
};
|
|
4012
4437
|
}
|
|
4013
4438
|
const template = await saveTemplate({
|
|
@@ -4034,7 +4459,7 @@ export default Plugin.define({
|
|
|
4034
4459
|
delete_template: async (input: unknown) => {
|
|
4035
4460
|
const { id } = input as { id?: string };
|
|
4036
4461
|
if (!id) {
|
|
4037
|
-
return { success: false, error: "
|
|
4462
|
+
return { success: false, error: t("tool.template.needId") };
|
|
4038
4463
|
}
|
|
4039
4464
|
try {
|
|
4040
4465
|
await deleteTemplate(id);
|
|
@@ -4062,14 +4487,14 @@ export default Plugin.define({
|
|
|
4062
4487
|
import_tasks: async (input: unknown) => {
|
|
4063
4488
|
const { data } = input as { data?: string };
|
|
4064
4489
|
if (!data) {
|
|
4065
|
-
return { success: false, error: "
|
|
4490
|
+
return { success: false, error: t("tool.transfer.noData") };
|
|
4066
4491
|
}
|
|
4067
4492
|
try {
|
|
4068
4493
|
const parsed = parseImportJson(data);
|
|
4069
4494
|
if (parsed.tasks.length === 0) {
|
|
4070
4495
|
return {
|
|
4071
4496
|
success: false,
|
|
4072
|
-
error: "
|
|
4497
|
+
error: t("tool.transfer.noTasksInFile"),
|
|
4073
4498
|
errors: parsed.errors,
|
|
4074
4499
|
};
|
|
4075
4500
|
}
|
|
@@ -4108,7 +4533,22 @@ export default Plugin.define({
|
|
|
4108
4533
|
def.notBefore,
|
|
4109
4534
|
def.notAfter,
|
|
4110
4535
|
def.pausedUntil,
|
|
4111
|
-
def.runAt
|
|
4536
|
+
def.runAt,
|
|
4537
|
+
def.session ?? "new",
|
|
4538
|
+
def.sessionId,
|
|
4539
|
+
def.sessionMaxRuns,
|
|
4540
|
+
{
|
|
4541
|
+
activeDays: def.activeDays,
|
|
4542
|
+
windowPolicy: def.windowPolicy,
|
|
4543
|
+
watchGlobs: def.watchGlobs,
|
|
4544
|
+
watchIgnore: def.watchIgnore,
|
|
4545
|
+
gitBranch: def.gitBranch,
|
|
4546
|
+
gitPaths: def.gitPaths,
|
|
4547
|
+
gitIgnore: def.gitIgnore,
|
|
4548
|
+
gitPollSeconds: def.gitPollSeconds,
|
|
4549
|
+
},
|
|
4550
|
+
def.runWhenLoggedOff === true,
|
|
4551
|
+
def.paused === true
|
|
4112
4552
|
);
|
|
4113
4553
|
await saveTaskDefinition(def);
|
|
4114
4554
|
imported.push(def.name);
|
|
@@ -4147,7 +4587,7 @@ export default Plugin.define({
|
|
|
4147
4587
|
// Повторный вызов не создаёт второй сервер — защита от двойного запуска
|
|
4148
4588
|
// реализована внутри startDashboardServer.
|
|
4149
4589
|
const dashboard = await startDashboardServer({
|
|
4150
|
-
getTasks: collectTasksView,
|
|
4590
|
+
getTasks: async () => (await collectTasksView()).tasks,
|
|
4151
4591
|
runTask: (name) => runTaskEntry(name),
|
|
4152
4592
|
deleteTask: async (name) => {
|
|
4153
4593
|
await deleteTaskWithFamily(name);
|
|
@@ -4196,7 +4636,7 @@ function resolveMatrixExtraConfig(
|
|
|
4196
4636
|
matrix.concurrency < 1
|
|
4197
4637
|
) {
|
|
4198
4638
|
throw new Error(
|
|
4199
|
-
|
|
4639
|
+
t("tool.error.matrixConcurrency", { task: name })
|
|
4200
4640
|
);
|
|
4201
4641
|
}
|
|
4202
4642
|
extra.concurrency = Math.floor(matrix.concurrency);
|
|
@@ -4209,8 +4649,10 @@ function resolveMatrixExtraConfig(
|
|
|
4209
4649
|
const workspaceKey = key.trim();
|
|
4210
4650
|
if (!allowed.has(workspaceKey)) {
|
|
4211
4651
|
throw new Error(
|
|
4212
|
-
|
|
4213
|
-
|
|
4652
|
+
t("tool.error.matrixOverride", {
|
|
4653
|
+
task: name,
|
|
4654
|
+
workspace: workspaceKey,
|
|
4655
|
+
})
|
|
4214
4656
|
);
|
|
4215
4657
|
}
|
|
4216
4658
|
if (!value || typeof value !== "object") continue;
|
|
@@ -4295,8 +4737,28 @@ async function schedulerCreateTask(
|
|
|
4295
4737
|
/** Сколько запусков переживает reuse-сессия до ротации (0/undefined — без ограничения). */
|
|
4296
4738
|
sessionMaxRuns?: number,
|
|
4297
4739
|
/** Спринт 27: дни недели, политика окна, glob- и git-фильтры. */
|
|
4298
|
-
triggerExtras?: TriggerExtras
|
|
4740
|
+
triggerExtras?: TriggerExtras,
|
|
4741
|
+
/** Спринт 27.5.4: Windows — запускать без входа пользователя (/ru SYSTEM). */
|
|
4742
|
+
runWhenLoggedOff?: boolean,
|
|
4743
|
+
/**
|
|
4744
|
+
* Спринт 27.5.8: пересоздать задачу сразу отключённой (пауза переживает
|
|
4745
|
+
* update). Для матрицы пауза применяется к клонам.
|
|
4746
|
+
*/
|
|
4747
|
+
paused?: boolean
|
|
4299
4748
|
): Promise<void> {
|
|
4749
|
+
// Спринт 27.5 (hotfix 1.5.1): проверяем имя до создания wrapper/prompt и записи
|
|
4750
|
+
// в БД. Недопустимые символы отклоняются с понятным сообщением, а не ошибкой
|
|
4751
|
+
// schtasks; имя нормализуется (trim) для всех путей: MCP, RPC и импорт.
|
|
4752
|
+
const normalizedName = name.trim();
|
|
4753
|
+
const nameError = validateTaskName(normalizedName);
|
|
4754
|
+
if (nameError) {
|
|
4755
|
+
throw new Error(nameError);
|
|
4756
|
+
}
|
|
4757
|
+
name = normalizedName;
|
|
4758
|
+
// Для отката файлов: при обновлении существующей задачи файлы переиспользуются,
|
|
4759
|
+
// удалять их при сбое нельзя — в БД остаётся прежнее определение.
|
|
4760
|
+
const definitionExisted = Boolean(getTask(normalizedName));
|
|
4761
|
+
|
|
4300
4762
|
const normalizedModel = model?.trim() || undefined;
|
|
4301
4763
|
const normalizedPriority = normalizePriority(priority);
|
|
4302
4764
|
const normalizedBefore = beforeScript?.trim() || undefined;
|
|
@@ -4305,6 +4767,10 @@ async function schedulerCreateTask(
|
|
|
4305
4767
|
const normalizedNotBefore = notBefore?.trim() || undefined;
|
|
4306
4768
|
const normalizedNotAfter = notAfter?.trim() || undefined;
|
|
4307
4769
|
const normalizedPausedUntil = pausedUntil?.trim() || undefined;
|
|
4770
|
+
// Спринт 27.5.4: true → задача работает без входа (Windows /ru SYSTEM).
|
|
4771
|
+
const normalizedRunWhenLoggedOff = runWhenLoggedOff === true ? true : undefined;
|
|
4772
|
+
// Спринт 27.5.8: пауза сохраняется при пересоздании задачи.
|
|
4773
|
+
const normalizedPaused = paused === true ? true : undefined;
|
|
4308
4774
|
// Спринт 27: дни недели, политика окна и glob/git-фильтры.
|
|
4309
4775
|
const normalizeGlobList = (raw?: string[]): string[] | undefined => {
|
|
4310
4776
|
if (!Array.isArray(raw)) return undefined;
|
|
@@ -4349,7 +4815,7 @@ async function schedulerCreateTask(
|
|
|
4349
4815
|
if (effectiveTriggerType === "once") {
|
|
4350
4816
|
const normalized = normalizeOneShotRunAt({ runAt });
|
|
4351
4817
|
if (!normalized.ok) {
|
|
4352
|
-
throw new Error(
|
|
4818
|
+
throw new Error(t("tool.error.taskReason", { name, error: normalized.error }));
|
|
4353
4819
|
}
|
|
4354
4820
|
effectiveRunAt = normalized.runAt;
|
|
4355
4821
|
}
|
|
@@ -4360,7 +4826,12 @@ async function schedulerCreateTask(
|
|
|
4360
4826
|
if (session !== undefined) {
|
|
4361
4827
|
const normalizedSession = normalizeSessionMode(session);
|
|
4362
4828
|
if (!normalizedSession) {
|
|
4363
|
-
throw new Error(
|
|
4829
|
+
throw new Error(
|
|
4830
|
+
t("tool.error.sessionUnknown", {
|
|
4831
|
+
name,
|
|
4832
|
+
session: String(session),
|
|
4833
|
+
})
|
|
4834
|
+
);
|
|
4364
4835
|
}
|
|
4365
4836
|
effectiveSession = normalizedSession;
|
|
4366
4837
|
}
|
|
@@ -4385,7 +4856,7 @@ async function schedulerCreateTask(
|
|
|
4385
4856
|
};
|
|
4386
4857
|
if (Array.isArray(allowedTools) && allowedTools.filter((t) => typeof t === "string" && t.trim()).length === 0) {
|
|
4387
4858
|
throw new Error(
|
|
4388
|
-
|
|
4859
|
+
t("tool.error.allowedToolsEmpty", { task: name })
|
|
4389
4860
|
);
|
|
4390
4861
|
}
|
|
4391
4862
|
const normalizedAllowedTools = normalizeToolList(allowedTools);
|
|
@@ -4397,7 +4868,7 @@ async function schedulerCreateTask(
|
|
|
4397
4868
|
if (matrix) {
|
|
4398
4869
|
if (workspaceId?.trim()) {
|
|
4399
4870
|
throw new Error(
|
|
4400
|
-
|
|
4871
|
+
t("tool.error.workspaceIdConflict", { task: name })
|
|
4401
4872
|
);
|
|
4402
4873
|
}
|
|
4403
4874
|
const ids = Array.from(
|
|
@@ -4409,18 +4880,26 @@ async function schedulerCreateTask(
|
|
|
4409
4880
|
)
|
|
4410
4881
|
);
|
|
4411
4882
|
if (ids.length === 0) {
|
|
4412
|
-
throw new Error(
|
|
4883
|
+
throw new Error(
|
|
4884
|
+
t("tool.error.workspaceIdsEmpty", { task: name })
|
|
4885
|
+
);
|
|
4413
4886
|
}
|
|
4414
4887
|
for (const id of ids) {
|
|
4415
4888
|
const ws = getWorkspace(id);
|
|
4416
4889
|
if (!ws) {
|
|
4417
|
-
throw new Error(
|
|
4890
|
+
throw new Error(
|
|
4891
|
+
t("tool.error.workspaceMissing", { task: name, id })
|
|
4892
|
+
);
|
|
4418
4893
|
}
|
|
4419
4894
|
try {
|
|
4420
4895
|
validateWorkspacePath(ws.path);
|
|
4421
4896
|
} catch {
|
|
4422
4897
|
throw new Error(
|
|
4423
|
-
|
|
4898
|
+
t("tool.error.workspaceUnavailable", {
|
|
4899
|
+
task: name,
|
|
4900
|
+
workspace: ws.name,
|
|
4901
|
+
path: ws.path,
|
|
4902
|
+
})
|
|
4424
4903
|
);
|
|
4425
4904
|
}
|
|
4426
4905
|
}
|
|
@@ -4442,7 +4921,7 @@ async function schedulerCreateTask(
|
|
|
4442
4921
|
|
|
4443
4922
|
// MCP-триггер без имени события бессмыслен — валидируем до создания файлов.
|
|
4444
4923
|
if (effectiveTriggerType === "mcp-event" && !normalizedMcpEvent) {
|
|
4445
|
-
throw new Error("
|
|
4924
|
+
throw new Error(t("tool.error.mcpEventRequired"));
|
|
4446
4925
|
}
|
|
4447
4926
|
// Спринт 27: git-триггеру нужен git-репозиторий в рабочей директории.
|
|
4448
4927
|
if (effectiveTriggerType === "git") {
|
|
@@ -4451,12 +4930,12 @@ async function schedulerCreateTask(
|
|
|
4451
4930
|
: workingDirectory?.trim() || projectDirectory || process.cwd();
|
|
4452
4931
|
if (!gitCwd) {
|
|
4453
4932
|
throw new Error(
|
|
4454
|
-
|
|
4933
|
+
t("tool.error.gitCwdRequired", { task: name })
|
|
4455
4934
|
);
|
|
4456
4935
|
}
|
|
4457
4936
|
if (!readGitBranch(gitCwd)) {
|
|
4458
4937
|
throw new Error(
|
|
4459
|
-
|
|
4938
|
+
t("tool.error.gitNoRepo", { task: name, path: gitCwd })
|
|
4460
4939
|
);
|
|
4461
4940
|
}
|
|
4462
4941
|
}
|
|
@@ -4472,8 +4951,10 @@ async function schedulerCreateTask(
|
|
|
4472
4951
|
}
|
|
4473
4952
|
if (normalizedTz && !isValidIanaTimeZone(normalizedTz)) {
|
|
4474
4953
|
throw new Error(
|
|
4475
|
-
|
|
4476
|
-
|
|
4954
|
+
t("tool.error.timezone", {
|
|
4955
|
+
task: name,
|
|
4956
|
+
timezone: normalizedTz,
|
|
4957
|
+
})
|
|
4477
4958
|
);
|
|
4478
4959
|
}
|
|
4479
4960
|
const windowError = validateLaunchWindow(
|
|
@@ -4481,7 +4962,7 @@ async function schedulerCreateTask(
|
|
|
4481
4962
|
normalizedNotAfter
|
|
4482
4963
|
);
|
|
4483
4964
|
if (windowError) {
|
|
4484
|
-
throw new Error(
|
|
4965
|
+
throw new Error(t("tool.error.window", { task: name, error: windowError }));
|
|
4485
4966
|
}
|
|
4486
4967
|
}
|
|
4487
4968
|
// Спринт 27: окно и дни недели применимы и к событийным триггерам
|
|
@@ -4489,7 +4970,7 @@ async function schedulerCreateTask(
|
|
|
4489
4970
|
if (effectiveTriggerType !== "cron") {
|
|
4490
4971
|
const windowError = validateLaunchWindow(normalizedNotBefore, normalizedNotAfter);
|
|
4491
4972
|
if (windowError) {
|
|
4492
|
-
throw new Error(
|
|
4973
|
+
throw new Error(t("tool.error.window", { task: name, error: windowError }));
|
|
4493
4974
|
}
|
|
4494
4975
|
}
|
|
4495
4976
|
|
|
@@ -4522,13 +5003,22 @@ async function schedulerCreateTask(
|
|
|
4522
5003
|
const normalizedWorkspaceId = workspaceId?.trim() || undefined;
|
|
4523
5004
|
const workspace = normalizedWorkspaceId ? getWorkspace(normalizedWorkspaceId) : undefined;
|
|
4524
5005
|
if (normalizedWorkspaceId && !workspace) {
|
|
4525
|
-
throw new Error(
|
|
5006
|
+
throw new Error(
|
|
5007
|
+
t("tool.error.workspaceIdMissing", {
|
|
5008
|
+
id: normalizedWorkspaceId,
|
|
5009
|
+
})
|
|
5010
|
+
);
|
|
4526
5011
|
}
|
|
4527
5012
|
if (workspace) {
|
|
4528
5013
|
try {
|
|
4529
5014
|
validateWorkspacePath(workspace.path);
|
|
4530
5015
|
} catch {
|
|
4531
|
-
throw new Error(
|
|
5016
|
+
throw new Error(
|
|
5017
|
+
t("tool.error.workspacePathMissing", {
|
|
5018
|
+
name: workspace.name,
|
|
5019
|
+
path: workspace.path,
|
|
5020
|
+
})
|
|
5021
|
+
);
|
|
4532
5022
|
}
|
|
4533
5023
|
if (workingDirectory?.trim() && workingDirectory.trim() !== workspace.path) {
|
|
4534
5024
|
console.warn(
|
|
@@ -4541,8 +5031,19 @@ async function schedulerCreateTask(
|
|
|
4541
5031
|
workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
|
|
4542
5032
|
|
|
4543
5033
|
// Спринт 21: env-переменные workspace → отдельный файл, который читает обёртка.
|
|
4544
|
-
//
|
|
4545
|
-
const
|
|
5034
|
+
// Спринт 29.3: инжектит в env только реально используемые секреты (scoped-инъекция).
|
|
5035
|
+
const usedSecretNames = collectSecretNames(
|
|
5036
|
+
prompt,
|
|
5037
|
+
beforeScript,
|
|
5038
|
+
afterScript,
|
|
5039
|
+
qualityGate
|
|
5040
|
+
);
|
|
5041
|
+
const taskEnvFile = writeWorkspaceEnvFile(
|
|
5042
|
+
workspace,
|
|
5043
|
+
PLUGIN_DIR,
|
|
5044
|
+
sanitized,
|
|
5045
|
+
usedSecretNames
|
|
5046
|
+
);
|
|
4546
5047
|
if (taskEnvFile) {
|
|
4547
5048
|
console.log(`[workspace] Задача "${name}": env-переменные workspace подключены.`);
|
|
4548
5049
|
}
|
|
@@ -4553,7 +5054,11 @@ async function schedulerCreateTask(
|
|
|
4553
5054
|
await fs.mkdir(LOG_DIR, { recursive: true });
|
|
4554
5055
|
await fs.writeFile(logFile, "", "utf8");
|
|
4555
5056
|
} catch (err: any) {
|
|
4556
|
-
throw new Error(
|
|
5057
|
+
throw new Error(
|
|
5058
|
+
t("tool.error.prepareFiles", {
|
|
5059
|
+
error: err.message || String(err),
|
|
5060
|
+
})
|
|
5061
|
+
);
|
|
4557
5062
|
}
|
|
4558
5063
|
|
|
4559
5064
|
// Обёртка зависит от платформы:
|
|
@@ -4611,9 +5116,24 @@ async function schedulerCreateTask(
|
|
|
4611
5116
|
});
|
|
4612
5117
|
}
|
|
4613
5118
|
} catch (err: any) {
|
|
4614
|
-
throw new Error(
|
|
5119
|
+
throw new Error(
|
|
5120
|
+
t("tool.error.wrapper", {
|
|
5121
|
+
error: err.message || String(err),
|
|
5122
|
+
})
|
|
5123
|
+
);
|
|
4615
5124
|
}
|
|
4616
5125
|
|
|
5126
|
+
// 27.5.5.3: при сбое создания новой задачи убираем подготовленные файлы.
|
|
5127
|
+
// При обновлении файлы переиспользуются существующей задачей — не удаляем.
|
|
5128
|
+
const rollbackArtifacts = async (): Promise<void> => {
|
|
5129
|
+
if (definitionExisted) return;
|
|
5130
|
+
await Promise.all(
|
|
5131
|
+
[wrapperPath, promptFile, logFile, taskEnvFile].map((file) =>
|
|
5132
|
+
file ? fs.unlink(file).catch(() => undefined) : Promise.resolve()
|
|
5133
|
+
)
|
|
5134
|
+
);
|
|
5135
|
+
};
|
|
5136
|
+
|
|
4617
5137
|
try {
|
|
4618
5138
|
// Бэкенд сам преобразует cron в родное расписание ОС.
|
|
4619
5139
|
await scheduler.createTask({
|
|
@@ -4630,11 +5150,55 @@ async function schedulerCreateTask(
|
|
|
4630
5150
|
timezone: normalizedTz,
|
|
4631
5151
|
notBefore: normalizedNotBefore,
|
|
4632
5152
|
notAfter: normalizedNotAfter,
|
|
5153
|
+
runWhenLoggedOff: normalizedRunWhenLoggedOff,
|
|
4633
5154
|
});
|
|
4634
5155
|
} catch (err: any) {
|
|
5156
|
+
await rollbackArtifacts();
|
|
4635
5157
|
throw new Error(err instanceof Error ? err.message : String(err));
|
|
4636
5158
|
}
|
|
4637
5159
|
|
|
5160
|
+
// Проверяем фактическое наличие задачи в планировщике: до 3 попыток с паузой
|
|
5161
|
+
// 200 мс. Это ловит случай, когда ОС/обёртка вернула код 0, но задачи нет.
|
|
5162
|
+
const isListed = (tasks: Awaited<ReturnType<typeof scheduler.listTasks>>): boolean =>
|
|
5163
|
+
tasks.some(
|
|
5164
|
+
(task) => (task.taskName || "").trim().toLowerCase() === name.toLowerCase()
|
|
5165
|
+
);
|
|
5166
|
+
let listedTasks: Awaited<ReturnType<typeof scheduler.listTasks>> | undefined;
|
|
5167
|
+
let verifyQueryError: unknown;
|
|
5168
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
5169
|
+
try {
|
|
5170
|
+
listedTasks = await scheduler.listTasks();
|
|
5171
|
+
if (isListed(listedTasks)) break;
|
|
5172
|
+
} catch (err) {
|
|
5173
|
+
verifyQueryError = err;
|
|
5174
|
+
}
|
|
5175
|
+
if (attempt < 2) {
|
|
5176
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
5177
|
+
}
|
|
5178
|
+
}
|
|
5179
|
+
if (listedTasks && !isListed(listedTasks)) {
|
|
5180
|
+
await rollbackArtifacts();
|
|
5181
|
+
throw new Error(
|
|
5182
|
+
t("tool.error.schedulerNotConfirmed", {
|
|
5183
|
+
task: name,
|
|
5184
|
+
scheduler: scheduler.title,
|
|
5185
|
+
}) +
|
|
5186
|
+
" " +
|
|
5187
|
+
(definitionExisted
|
|
5188
|
+
? t("tool.error.schedulerKeptFiles")
|
|
5189
|
+
: t("tool.error.schedulerRemovedFiles"))
|
|
5190
|
+
);
|
|
5191
|
+
}
|
|
5192
|
+
if (!listedTasks && verifyQueryError) {
|
|
5193
|
+
// Список получить не удалось — не удаляем возможно созданную задачу,
|
|
5194
|
+
// но явно предупреждаем: проверка наличия не выполнена.
|
|
5195
|
+
console.warn(
|
|
5196
|
+
`[windows-scheduler] Задача "${name}" создана, но проверить её в планировщике не удалось: ${
|
|
5197
|
+
verifyQueryError instanceof Error ? verifyQueryError.message : String(verifyQueryError)
|
|
5198
|
+
}`
|
|
5199
|
+
);
|
|
5200
|
+
}
|
|
5201
|
+
|
|
4638
5202
|
// Сохраняем определение задачи для последующего экспорта/импорта.
|
|
4639
5203
|
// Определение до перезаписи: нужно и для очереди матрицы, и для счётчика сессии.
|
|
4640
5204
|
const previousDefinition = getTask(name);
|
|
@@ -4675,6 +5239,10 @@ async function schedulerCreateTask(
|
|
|
4675
5239
|
timezone: normalizedTz,
|
|
4676
5240
|
notBefore: normalizedNotBefore,
|
|
4677
5241
|
notAfter: normalizedNotAfter,
|
|
5242
|
+
// Спринт 27.5.4: режим входа (Windows: /ru SYSTEM при true).
|
|
5243
|
+
runWhenLoggedOff: normalizedRunWhenLoggedOff,
|
|
5244
|
+
// Спринт 27.5.8: бессрочная пауза переживает пересоздание.
|
|
5245
|
+
paused: normalizedPaused,
|
|
4678
5246
|
// Спринт 27: дни недели, политика окна, glob- и git-фильтры.
|
|
4679
5247
|
activeDays: normalizedActiveDays,
|
|
4680
5248
|
windowPolicy: normalizedWindowPolicy,
|
|
@@ -4708,6 +5276,8 @@ async function schedulerCreateTask(
|
|
|
4708
5276
|
};
|
|
4709
5277
|
try {
|
|
4710
5278
|
await saveTaskDefinition(taskDefinition);
|
|
5279
|
+
// Аудит политики прав: фиксируем, какие инструменты задача блокирует.
|
|
5280
|
+
recordTaskToolBlocks(name, normalizedAllowedTools, normalizedDeniedTools);
|
|
4711
5281
|
} catch {
|
|
4712
5282
|
// Не критично — основная задача уже создана.
|
|
4713
5283
|
}
|
|
@@ -4746,7 +5316,14 @@ async function schedulerCreateTask(
|
|
|
4746
5316
|
clone.timezone,
|
|
4747
5317
|
clone.notBefore,
|
|
4748
5318
|
clone.notAfter,
|
|
4749
|
-
clone.pausedUntil
|
|
5319
|
+
clone.pausedUntil,
|
|
5320
|
+
clone.runAt,
|
|
5321
|
+
clone.session,
|
|
5322
|
+
clone.sessionId,
|
|
5323
|
+
clone.sessionMaxRuns,
|
|
5324
|
+
undefined,
|
|
5325
|
+
clone.runWhenLoggedOff,
|
|
5326
|
+
clone.paused
|
|
4750
5327
|
);
|
|
4751
5328
|
};
|
|
4752
5329
|
|
|
@@ -4761,6 +5338,8 @@ async function schedulerCreateTask(
|
|
|
4761
5338
|
} catch {
|
|
4762
5339
|
// Не критично.
|
|
4763
5340
|
}
|
|
5341
|
+
// Спринт 27.5.7: при откате прогона не оставляем и файлы клона.
|
|
5342
|
+
await removeTaskArtifacts(child);
|
|
4764
5343
|
};
|
|
4765
5344
|
|
|
4766
5345
|
// Создаёт/обновляет/удаляет matrix-complete по текущему определению.
|
|
@@ -4775,8 +5354,10 @@ async function schedulerCreateTask(
|
|
|
4775
5354
|
await schedulerCreateTask(
|
|
4776
5355
|
aggregatorName,
|
|
4777
5356
|
schedule,
|
|
4778
|
-
|
|
4779
|
-
|
|
5357
|
+
t("tool.matrix.completed", {
|
|
5358
|
+
name,
|
|
5359
|
+
clones: cloneNames.join(", "),
|
|
5360
|
+
}),
|
|
4780
5361
|
timeoutSeconds,
|
|
4781
5362
|
undefined,
|
|
4782
5363
|
undefined,
|
|
@@ -4818,13 +5399,144 @@ async function schedulerCreateTask(
|
|
|
4818
5399
|
for (const child of removeMatrixChildren(name)) {
|
|
4819
5400
|
await removeChild(child);
|
|
4820
5401
|
}
|
|
4821
|
-
|
|
4822
|
-
|
|
4823
|
-
|
|
5402
|
+
// Спринт 27.5.7: если клон не создался, откатываем весь прогон. Иначе
|
|
5403
|
+
// остаётся родитель с половиной клонов — он выглядит рабочим, но часть
|
|
5404
|
+
// workspace никогда не запускается. Ошибку expandMatrixTask (неизвестный
|
|
5405
|
+
// workspace) обрабатываем там же: родитель уже записан в БД.
|
|
5406
|
+
const createdInRun: string[] = [];
|
|
5407
|
+
try {
|
|
5408
|
+
const clones = expandMatrixTask(taskDefinition);
|
|
5409
|
+
for (const clone of clones) {
|
|
5410
|
+
try {
|
|
5411
|
+
await createClone(clone);
|
|
5412
|
+
createdInRun.push(clone.name);
|
|
5413
|
+
} catch (err: any) {
|
|
5414
|
+
const workspaceLabel = clone.workspaceId
|
|
5415
|
+
? getWorkspace(clone.workspaceId)?.name ?? clone.workspaceId
|
|
5416
|
+
: "без workspace";
|
|
5417
|
+
throw new Error(
|
|
5418
|
+
t("tool.error.matrixCloneFailed", {
|
|
5419
|
+
clone: clone.name,
|
|
5420
|
+
workspace: workspaceLabel,
|
|
5421
|
+
error: err instanceof Error ? err.message : String(err),
|
|
5422
|
+
})
|
|
5423
|
+
);
|
|
5424
|
+
}
|
|
5425
|
+
}
|
|
5426
|
+
await syncAggregator();
|
|
5427
|
+
} catch (err: any) {
|
|
5428
|
+
for (const child of [...createdInRun].reverse()) {
|
|
5429
|
+
await removeChild(child);
|
|
5430
|
+
}
|
|
5431
|
+
const aggregatorName = matrixCompleteName(name);
|
|
5432
|
+
if (getTask(aggregatorName)) {
|
|
5433
|
+
await removeChild(aggregatorName);
|
|
5434
|
+
}
|
|
5435
|
+
// Новая матрица: без клонов родитель бесполезен — убираем и его,
|
|
5436
|
+
// вместе с подготовленными файлами обёртки.
|
|
5437
|
+
if (!definitionExisted) {
|
|
5438
|
+
try {
|
|
5439
|
+
await scheduler.deleteTask(name);
|
|
5440
|
+
} catch {
|
|
5441
|
+
// Задачи могло не быть: бэкенд уже вернул ошибку.
|
|
5442
|
+
}
|
|
5443
|
+
try {
|
|
5444
|
+
await removeTaskDefinition(name);
|
|
5445
|
+
} catch {
|
|
5446
|
+
// Не критично: запись могла не сохраниться.
|
|
5447
|
+
}
|
|
5448
|
+
await rollbackArtifacts();
|
|
5449
|
+
}
|
|
5450
|
+
throw new Error(
|
|
5451
|
+
t("tool.error.matrixExpandRuntime", {
|
|
5452
|
+
name,
|
|
5453
|
+
error: err instanceof Error ? err.message : String(err),
|
|
5454
|
+
})
|
|
5455
|
+
);
|
|
4824
5456
|
}
|
|
4825
|
-
await syncAggregator();
|
|
4826
5457
|
}
|
|
4827
5458
|
}
|
|
5459
|
+
|
|
5460
|
+
// Спринт 27.5.8: пересозданная задача должна остаться на паузе. У матрицы
|
|
5461
|
+
// пауза применяется к клонам — родитель сам никогда не выполняется.
|
|
5462
|
+
if (normalizedPaused) {
|
|
5463
|
+
const pauseTargets = normalizedMatrix
|
|
5464
|
+
? listMatrixClones(name).map((clone) => clone.name)
|
|
5465
|
+
: [name];
|
|
5466
|
+
for (const target of pauseTargets) {
|
|
5467
|
+
try {
|
|
5468
|
+
await scheduler.pauseTask(target);
|
|
5469
|
+
} catch (err: any) {
|
|
5470
|
+
console.warn(
|
|
5471
|
+
`[windows-scheduler] Задача "${target}": пауза не восстановлена после пересоздания: ${
|
|
5472
|
+
err instanceof Error ? err.message : String(err)
|
|
5473
|
+
}`
|
|
5474
|
+
);
|
|
5475
|
+
}
|
|
5476
|
+
}
|
|
5477
|
+
}
|
|
5478
|
+
}
|
|
5479
|
+
|
|
5480
|
+
/**
|
|
5481
|
+
* Спринт 27.5.6: восстановление задачи из определения в БД.
|
|
5482
|
+
*
|
|
5483
|
+
* update_task пересоздаёт задачу в планировщике (delete + create). Раньше при
|
|
5484
|
+
* сбое create после успешного delete старая версия терялась навсегда: в ОС её
|
|
5485
|
+
* уже нет, а в БД лежит новое (не применённое) определение. Здесь мы заново
|
|
5486
|
+
* создаём задачу из прежнего определения — обёртка, промпт, расписание и
|
|
5487
|
+
* пауза восстанавливаются тем же путём, что и при обычном create.
|
|
5488
|
+
*/
|
|
5489
|
+
async function recreateTaskFromDefinition(definition: TaskDefinition): Promise<void> {
|
|
5490
|
+
const paused = Boolean(
|
|
5491
|
+
definition.paused === true ||
|
|
5492
|
+
(definition.pausedUntil && Date.parse(definition.pausedUntil) > Date.now())
|
|
5493
|
+
);
|
|
5494
|
+
await schedulerCreateTask(
|
|
5495
|
+
definition.name,
|
|
5496
|
+
definition.schedule ?? "",
|
|
5497
|
+
definition.prompt,
|
|
5498
|
+
definition.timeoutSeconds,
|
|
5499
|
+
definition.workingDirectory,
|
|
5500
|
+
definition.retryCount,
|
|
5501
|
+
definition.retryDelay,
|
|
5502
|
+
definition.qualityGate,
|
|
5503
|
+
definition.nextTaskOnSuccess,
|
|
5504
|
+
definition.nextTaskOnError,
|
|
5505
|
+
definition.triggerType ?? "cron",
|
|
5506
|
+
definition.watchPath,
|
|
5507
|
+
Array.isArray(definition.dependsOn) ? definition.dependsOn : undefined,
|
|
5508
|
+
definition.model,
|
|
5509
|
+
definition.priority,
|
|
5510
|
+
definition.beforeScript,
|
|
5511
|
+
definition.afterScript,
|
|
5512
|
+
definition.mcpEvent,
|
|
5513
|
+
definition.workspaceId,
|
|
5514
|
+
definition.allowedTools,
|
|
5515
|
+
definition.deniedTools,
|
|
5516
|
+
definition.matrix,
|
|
5517
|
+
definition.matrixParentId,
|
|
5518
|
+
"create",
|
|
5519
|
+
definition.timezone,
|
|
5520
|
+
definition.notBefore,
|
|
5521
|
+
definition.notAfter,
|
|
5522
|
+
definition.pausedUntil,
|
|
5523
|
+
definition.runAt,
|
|
5524
|
+
definition.session ?? "new",
|
|
5525
|
+
definition.sessionId,
|
|
5526
|
+
definition.sessionMaxRuns,
|
|
5527
|
+
{
|
|
5528
|
+
activeDays: definition.activeDays,
|
|
5529
|
+
windowPolicy: definition.windowPolicy,
|
|
5530
|
+
watchGlobs: definition.watchGlobs,
|
|
5531
|
+
watchIgnore: definition.watchIgnore,
|
|
5532
|
+
gitBranch: definition.gitBranch,
|
|
5533
|
+
gitPaths: definition.gitPaths,
|
|
5534
|
+
gitIgnore: definition.gitIgnore,
|
|
5535
|
+
gitPollSeconds: definition.gitPollSeconds,
|
|
5536
|
+
},
|
|
5537
|
+
definition.runWhenLoggedOff,
|
|
5538
|
+
paused
|
|
5539
|
+
);
|
|
4828
5540
|
}
|
|
4829
5541
|
|
|
4830
5542
|
/**
|
|
@@ -4857,20 +5569,60 @@ async function runTaskEntry(name: string): Promise<{ alreadyRunning: boolean }>
|
|
|
4857
5569
|
}
|
|
4858
5570
|
}
|
|
4859
5571
|
|
|
5572
|
+
/**
|
|
5573
|
+
* Спринт 27.5.3: чтение задач ОС с одним повтором.
|
|
5574
|
+
*
|
|
5575
|
+
* Сразу после мутации (create/delete/pause/resume) `schtasks /query` иногда
|
|
5576
|
+
* отдаёт пустой список, хотя в БД задачи уже есть, или падает. Один короткий
|
|
5577
|
+
* retry убирает ложный «задач нет»; если ОС так и не ответила осмысленно —
|
|
5578
|
+
* возвращаем `osAvailable: false`, и вызывающий код показывает состояние БД.
|
|
5579
|
+
*/
|
|
5580
|
+
async function readOsTasksWithRetry(
|
|
5581
|
+
expectNonEmpty: boolean,
|
|
5582
|
+
delayMs = 300
|
|
5583
|
+
): Promise<{
|
|
5584
|
+
tasks: Awaited<ReturnType<typeof scheduler.listTasks>>;
|
|
5585
|
+
osAvailable: boolean;
|
|
5586
|
+
osError?: string;
|
|
5587
|
+
}> {
|
|
5588
|
+
let lastError: string | undefined;
|
|
5589
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
5590
|
+
if (attempt > 0) {
|
|
5591
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
5592
|
+
}
|
|
5593
|
+
try {
|
|
5594
|
+
const tasks = await scheduler.listTasks();
|
|
5595
|
+
if (tasks.length > 0 || !expectNonEmpty) {
|
|
5596
|
+
return { tasks, osAvailable: true };
|
|
5597
|
+
}
|
|
5598
|
+
lastError = "планировщик ОС вернул пустой список, хотя в БД есть задачи";
|
|
5599
|
+
} catch (err) {
|
|
5600
|
+
lastError = err instanceof Error ? err.message : String(err);
|
|
5601
|
+
}
|
|
5602
|
+
}
|
|
5603
|
+
return { tasks: [], osAvailable: false, osError: lastError };
|
|
5604
|
+
}
|
|
5605
|
+
|
|
4860
5606
|
/**
|
|
4861
5607
|
* Собирает задачи плагина в формате, который отдают оба потребителя:
|
|
4862
5608
|
* RPC get_tasks (GUI) и инструмент list_tasks (агент).
|
|
5609
|
+
*
|
|
5610
|
+
* Спринт 27.5.3: возвращает также состояние чтения ОС. Если ОС недоступна,
|
|
5611
|
+
* `tasks` — состояние из БД (задачи помечены `orphaned: true`), а не пустой
|
|
5612
|
+
* массив: иначе GUI и агент решали бы, что задач нет.
|
|
4863
5613
|
*/
|
|
4864
5614
|
async function collectTasksView() {
|
|
4865
|
-
const
|
|
5615
|
+
const defs = await loadTaskDefinitions();
|
|
5616
|
+
const osRead = await readOsTasksWithRetry(defs.length > 0);
|
|
5617
|
+
const tasks = osRead.tasks;
|
|
4866
5618
|
|
|
4867
5619
|
// Читаем историю один раз, чтобы определить финальный статус по последней записи.
|
|
4868
5620
|
const history = await loadHistory();
|
|
4869
5621
|
// loadHistory() отдаёт записи от новых к старым; helper оставляет самую свежую.
|
|
4870
5622
|
const lastByTask = latestHistoryByTask(history);
|
|
4871
5623
|
|
|
4872
|
-
//
|
|
4873
|
-
|
|
5624
|
+
// Определения задач читаются один раз заранее (см. выше) — расписание,
|
|
5625
|
+
// повторы, цепочки, директория.
|
|
4874
5626
|
const workspaces = listWorkspaces();
|
|
4875
5627
|
const workspaceById = new Map(workspaces.map((workspace) => [workspace.id, workspace]));
|
|
4876
5628
|
|
|
@@ -4915,7 +5667,7 @@ async function collectTasksView() {
|
|
|
4915
5667
|
})),
|
|
4916
5668
|
];
|
|
4917
5669
|
|
|
4918
|
-
|
|
5670
|
+
const view = sources.map(({ task: t, orphaned }) => {
|
|
4919
5671
|
// Все бэкенды возвращают короткие имена (без папки планировщика).
|
|
4920
5672
|
const name = t.taskName || "";
|
|
4921
5673
|
|
|
@@ -4958,6 +5710,15 @@ async function collectTasksView() {
|
|
|
4958
5710
|
partial: 0,
|
|
4959
5711
|
};
|
|
4960
5712
|
|
|
5713
|
+
// Спринт 27.5.2: пауза учитывает и флаг ОС, и активный pausedUntil.
|
|
5714
|
+
// nextRun считаем из определения — schtasks после мутации отдаёт
|
|
5715
|
+
// nextRunTime с задержкой, из-за чего API показывал null после resume.
|
|
5716
|
+
const pausedUntil = def?.pausedUntil ?? null;
|
|
5717
|
+
const paused =
|
|
5718
|
+
Boolean(t.paused) ||
|
|
5719
|
+
def?.paused === true ||
|
|
5720
|
+
Boolean(pausedUntil && Date.parse(pausedUntil) > Date.now());
|
|
5721
|
+
|
|
4961
5722
|
return {
|
|
4962
5723
|
name,
|
|
4963
5724
|
schedule: def?.schedule ?? "",
|
|
@@ -4966,15 +5727,15 @@ async function collectTasksView() {
|
|
|
4966
5727
|
// Спринт 24 (фикс): явный признак паузы. Раньше GUI пытался вывести его
|
|
4967
5728
|
// из текстового статуса, но mapStatus() превращает "disabled" в "unknown",
|
|
4968
5729
|
// поэтому кнопка «возобновить» была недоступна.
|
|
4969
|
-
paused
|
|
5730
|
+
paused,
|
|
4970
5731
|
runsTotal: counts.total,
|
|
4971
5732
|
runsSuccess: counts.success,
|
|
4972
5733
|
runsError: counts.error,
|
|
4973
5734
|
runsPartial: counts.partial,
|
|
4974
|
-
|
|
4975
|
-
|
|
4976
|
-
|
|
4977
|
-
|
|
5735
|
+
nextRun: paused
|
|
5736
|
+
? null
|
|
5737
|
+
: computeTaskNextRun(def) ??
|
|
5738
|
+
(t.nextRunTime ? String(t.nextRunTime) : null),
|
|
4978
5739
|
runAt: def?.runAt ?? null,
|
|
4979
5740
|
session: def?.session ?? "new",
|
|
4980
5741
|
sessionId: def?.sessionId ?? null,
|
|
@@ -4997,6 +5758,10 @@ async function collectTasksView() {
|
|
|
4997
5758
|
notBefore: def?.notBefore ?? null,
|
|
4998
5759
|
notAfter: def?.notAfter ?? null,
|
|
4999
5760
|
pausedUntil: def?.pausedUntil ?? null,
|
|
5761
|
+
// Спринт 27.5.4: режим входа — из ОС (Interactive/Background) и из
|
|
5762
|
+
// определения (запуск без входа через /ru SYSTEM).
|
|
5763
|
+
logonMode: t.logonMode ?? null,
|
|
5764
|
+
runWhenLoggedOff: Boolean(def?.runWhenLoggedOff),
|
|
5000
5765
|
workingDirectory: workspace?.path ?? def?.workingDirectory ?? def?.workdir ?? null,
|
|
5001
5766
|
workspaceId: workspace?.id ?? def?.workspaceId ?? null,
|
|
5002
5767
|
workspaceName: workspace?.name ?? null,
|
|
@@ -5019,6 +5784,8 @@ async function collectTasksView() {
|
|
|
5019
5784
|
prompt: def?.prompt ?? "",
|
|
5020
5785
|
};
|
|
5021
5786
|
});
|
|
5787
|
+
|
|
5788
|
+
return { tasks: view, osAvailable: osRead.osAvailable, osError: osRead.osError };
|
|
5022
5789
|
}
|
|
5023
5790
|
|
|
5024
5791
|
/**
|