opencode-windows-scheduler 1.4.0 → 1.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +61 -1
- package/LICENSE +21 -21
- package/README.md +26 -4
- package/ROADMAP-STRATEGY.md +43 -24
- package/ROADMAP.md +549 -31
- package/dist/core/dry-run.d.ts +41 -0
- package/dist/core/dry-run.d.ts.map +1 -1
- package/dist/core/dry-run.js +165 -16
- package/dist/core/file-watcher.d.ts.map +1 -1
- package/dist/core/file-watcher.js +53 -10
- package/dist/core/git-trigger.d.ts +80 -0
- package/dist/core/git-trigger.d.ts.map +1 -0
- package/dist/core/git-trigger.js +294 -0
- package/dist/core/glob.d.ts +38 -0
- package/dist/core/glob.d.ts.map +1 -0
- package/dist/core/glob.js +233 -0
- package/dist/core/matrix.d.ts.map +1 -1
- package/dist/core/matrix.js +48 -22
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +7 -0
- package/dist/core/schedule-gate.js +55 -30
- package/dist/core/schedule-v2.d.ts +29 -1
- package/dist/core/schedule-v2.d.ts.map +1 -1
- package/dist/core/schedule-v2.js +107 -17
- package/dist/core/scheduler/types.d.ts +7 -1
- 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/telegram.d.ts.map +1 -1
- package/dist/core/telegram.js +13 -10
- package/dist/core/wrappers/bash.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +4 -0
- package/dist/db/git-state-repo.d.ts +16 -0
- package/dist/db/git-state-repo.d.ts.map +1 -0
- package/dist/db/git-state-repo.js +38 -0
- package/dist/db/schema.d.ts +1 -1
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +8 -0
- 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 +50 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1020 -197
- package/dist/notifications.d.ts.map +1 -1
- package/dist/notifications.js +74 -40
- package/dist/rpc.d.ts +238 -2
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +79 -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 +43 -3
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +94 -6
- package/dist/templates.d.ts +1 -1
- package/dist/templates.d.ts.map +1 -1
- package/dist/types.d.ts +11 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +32 -0
- package/docs/ARCHITECTURE.md +37 -1
- package/docs/FEATURES.md +70 -0
- package/docs/README.ru.md +19 -3
- package/gui-experimental.cjs +9 -4
- package/locales/en.json +695 -0
- package/locales/ru.json +695 -0
- package/package.json +9 -3
- package/scripts/test-locale.mjs +44 -0
- package/src/core/dry-run.ts +244 -19
- package/src/core/file-watcher.ts +65 -10
- package/src/core/git-trigger.ts +373 -0
- package/src/core/glob.ts +226 -0
- package/src/core/matrix.ts +52 -26
- package/src/core/ps-wrapper.ts +7 -0
- package/src/core/schedule-gate.ts +67 -33
- package/src/core/schedule-v2.ts +152 -17
- package/src/core/scheduler/types.ts +7 -1
- package/src/core/scheduler/windows.ts +25 -10
- package/src/core/telegram.ts +16 -10
- package/src/core/wrappers/bash.ts +4 -0
- package/src/db/git-state-repo.ts +62 -0
- package/src/db/schema.ts +8 -0
- package/src/gui.tsx +772 -456
- package/src/i18n.ts +339 -0
- package/src/index.ts +1274 -212
- package/src/notifications.ts +83 -42
- package/src/rpc.ts +79 -2
- package/src/server.ts +89 -48
- package/src/settings.ts +38 -10
- package/src/task-transfer.ts +148 -5
- package/src/templates.ts +1 -1
- package/src/types.ts +37 -0
package/dist/index.js
CHANGED
|
@@ -5,8 +5,8 @@ import { existsSync } from "node:fs";
|
|
|
5
5
|
import fs from "node:fs/promises";
|
|
6
6
|
import path from "node:path";
|
|
7
7
|
import { LockManager } from "./core/lock.js";
|
|
8
|
-
import { LOCK_DIR, LOG_DIR, PLUGIN_DIR, sanitizeName } from "./types.js";
|
|
9
|
-
import { parseCron, buildScheduleGate, isValidIanaTimeZone, validateLaunchWindow, prevRun } from "./core/schedule-v2.js";
|
|
8
|
+
import { LOCK_DIR, LOG_DIR, PLUGIN_DIR, STALE_LOCK_MAX_AGE_MS, WRAPPER_DIR, sanitizeName, validateTaskName, } from "./types.js";
|
|
9
|
+
import { parseCron, buildScheduleGate, isValidIanaTimeZone, validateLaunchWindow, prevRun, nextRun as cronNextRun, normalizeActiveDays, activeWindowState, nextWindowOpenDelayMs } from "./core/schedule-v2.js";
|
|
10
10
|
import { buildLaunchdOneShotCleanup, normalizeOneShotRunAt, } from "./core/one-shot.js";
|
|
11
11
|
import { generateSessionId, normalizeSessionMode, preservedSessionRunCount, } from "./core/session.js";
|
|
12
12
|
import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath, requestImmediateRun } from "./core/ps-wrapper.js";
|
|
@@ -19,6 +19,7 @@ import { aggregateMatrixResults, cancelPendingMatrixClones, expandMatrixTask, fi
|
|
|
19
19
|
import { SchedulerRpc } from "./rpc.js";
|
|
20
20
|
import { latestHistoryByTask, loadHistory, loadMetrics } from "./history.js";
|
|
21
21
|
import { loadSettings, saveSettings } from "./settings.js";
|
|
22
|
+
import { setLocale, t } from "./i18n.js";
|
|
22
23
|
import { runHistoryRetention, maybeRunHistoryRetention } from "./core/retention.js";
|
|
23
24
|
import { buildAnalytics } from "./core/analytics.js";
|
|
24
25
|
import { getHistory, listRunningRecords } from "./db/history-repo.js";
|
|
@@ -26,13 +27,14 @@ import { getAllMetrics } from "./db/metrics-repo.js";
|
|
|
26
27
|
import { findStuckMatrixClones, maybeSendDigest, notifyStuckMatrix, sendDigestNow, sendTestNotification, } from "./notifications.js";
|
|
27
28
|
import { loadTaskDefinitions, saveTaskDefinition, removeTaskDefinition, buildExportJson, parseImportJson, normalizePriority, } from "./task-transfer.js";
|
|
28
29
|
import { FileWatchManager } from "./core/file-watcher.js";
|
|
30
|
+
import { GitTriggerManager } from "./core/git-trigger.js";
|
|
29
31
|
import { loadTemplates, saveTemplate, deleteTemplate } from "./templates.js";
|
|
30
32
|
import { startDashboardServer, closeDashboardServer, getDashboardPort } from "./server.js";
|
|
31
33
|
import { DEFAULT_PROFILE, createProfile, deleteProfile, getProfileDir, getProfileName, isProfilePinnedByEnv, listProfiles, sanitizeProfileName, setActiveProfile, } from "./profiles.js";
|
|
32
34
|
import { closeDb, initDb } from "./db/index.js";
|
|
33
35
|
import { migrateJsonToDb } from "./db/migrate.js";
|
|
34
36
|
import { checkJsonBackups, recoverInterruptedRuns } from "./db/recovery.js";
|
|
35
|
-
import { getTask, listMatrixClones, saveTask } from "./db/tasks-repo.js";
|
|
37
|
+
import { getTask, listMatrixClones, listTasks as listTaskDefinitions, saveTask } from "./db/tasks-repo.js";
|
|
36
38
|
import { addWorkspace, deleteWorkspace, getWorkspace, listWorkspaces, updateWorkspace, validateWorkspacePath, readGitBranch, writeWorkspaceEnvFile, maskEnvForLog, } from "./workspaces.js";
|
|
37
39
|
import { deleteSecret, hasSecret, listSecrets, setSecret, } from "./core/secrets.js";
|
|
38
40
|
import { readAuditLog, recordAudit, } from "./core/audit.js";
|
|
@@ -115,7 +117,9 @@ export const matrixSchema = z.object({
|
|
|
115
117
|
});
|
|
116
118
|
/** Zod-схема аргументов schedule_task */
|
|
117
119
|
export const scheduleTaskSchema = z.object({
|
|
118
|
-
name: z
|
|
120
|
+
name: z
|
|
121
|
+
.string()
|
|
122
|
+
.describe("Unique task name (the plugin prefix is applied automatically). Allowed: letters (including Cyrillic), digits, space, dot, underscore and hyphen."),
|
|
119
123
|
schedule: z
|
|
120
124
|
.string()
|
|
121
125
|
.optional()
|
|
@@ -201,9 +205,9 @@ export const scheduleTaskSchema = z.object({
|
|
|
201
205
|
.optional()
|
|
202
206
|
.describe("Compensation/rollback task started after a failed run."),
|
|
203
207
|
triggerType: z
|
|
204
|
-
.enum(["cron", "file", "mcp-event", "once"])
|
|
208
|
+
.enum(["cron", "file", "git", "mcp-event", "once"])
|
|
205
209
|
.optional()
|
|
206
|
-
.describe("Trigger type: cron (default), file, mcp-event or once (single run at runAt/delaySeconds)."),
|
|
210
|
+
.describe("Trigger type: cron (default), file, git (new commits in the task working directory), mcp-event or once (single run at runAt/delaySeconds)."),
|
|
207
211
|
mcpEvent: z
|
|
208
212
|
.object({
|
|
209
213
|
server: z.string(),
|
|
@@ -216,6 +220,40 @@ export const scheduleTaskSchema = z.object({
|
|
|
216
220
|
.string()
|
|
217
221
|
.optional()
|
|
218
222
|
.describe("File or directory to watch when triggerType is \"file\". Can be set here or later via update_task."),
|
|
223
|
+
watchGlobs: z
|
|
224
|
+
.array(z.string())
|
|
225
|
+
.optional()
|
|
226
|
+
.describe("Glob masks that limit a file trigger, e.g. [\"**/*.md\", \"src/**\"]. Empty means any change under watchPath."),
|
|
227
|
+
watchIgnore: z
|
|
228
|
+
.array(z.string())
|
|
229
|
+
.optional()
|
|
230
|
+
.describe("Glob masks excluded from a file trigger, e.g. [\"node_modules/**\", \"*.log\"]. Supports leading ! to re-include."),
|
|
231
|
+
gitBranch: z
|
|
232
|
+
.string()
|
|
233
|
+
.optional()
|
|
234
|
+
.describe("Only for triggerType=git: branch name or glob (main, release/*, comma-separated). Empty means any branch."),
|
|
235
|
+
gitPaths: z
|
|
236
|
+
.array(z.string())
|
|
237
|
+
.optional()
|
|
238
|
+
.describe("Only for triggerType=git: glob masks of changed files that must match to start the task (git diff --name-only)."),
|
|
239
|
+
gitIgnore: z
|
|
240
|
+
.array(z.string())
|
|
241
|
+
.optional()
|
|
242
|
+
.describe("Only for triggerType=git: glob masks of changed files to ignore."),
|
|
243
|
+
gitPollSeconds: z
|
|
244
|
+
.number()
|
|
245
|
+
.int()
|
|
246
|
+
.min(5)
|
|
247
|
+
.optional()
|
|
248
|
+
.describe("Only for triggerType=git: polling interval in seconds (default 60, minimum 5)."),
|
|
249
|
+
activeDays: z
|
|
250
|
+
.array(z.number().int().min(0).max(6))
|
|
251
|
+
.optional()
|
|
252
|
+
.describe("Allowed weekdays 0=Sunday..6=Saturday for cron and event triggers. Empty or all seven means every day."),
|
|
253
|
+
windowPolicy: z
|
|
254
|
+
.enum(["skip", "postpone", "run"])
|
|
255
|
+
.optional()
|
|
256
|
+
.describe("Behaviour outside the launch window / active days: postpone (default, wait for the next opening), skip or run anyway."),
|
|
219
257
|
workingDirectory: z
|
|
220
258
|
.string()
|
|
221
259
|
.optional()
|
|
@@ -232,6 +270,10 @@ export const scheduleTaskSchema = z.object({
|
|
|
232
270
|
.array(z.string())
|
|
233
271
|
.optional()
|
|
234
272
|
.describe("Role-scoped tool deny-list (takes precedence over allowedTools). Metadata-only."),
|
|
273
|
+
runWhenLoggedOff: z
|
|
274
|
+
.boolean()
|
|
275
|
+
.optional()
|
|
276
|
+
.describe("Windows only: run the task even when no user is logged on (/ru SYSTEM). The task runs in session 0 without the user's profile, mapped drives or saved credentials, so tasks that need the user's environment may fail. Creating such a task usually requires an elevated shell. Default false: interactive only — the task runs only while the user is logged on."),
|
|
235
277
|
matrix: matrixSchema
|
|
236
278
|
.optional()
|
|
237
279
|
.describe("Matrix fan-out: the task becomes a template that is expanded into clones, one per workspace. The parent never runs itself. Cannot be combined with workspaceId."),
|
|
@@ -241,7 +283,7 @@ export const scheduleTaskSchema = z.object({
|
|
|
241
283
|
ctx.addIssue({
|
|
242
284
|
code: z.ZodIssueCode.custom,
|
|
243
285
|
path: ["schedule"],
|
|
244
|
-
message: "
|
|
286
|
+
message: t("tool.error.cronSchedule"),
|
|
245
287
|
});
|
|
246
288
|
}
|
|
247
289
|
if (trigger === "once" &&
|
|
@@ -250,21 +292,21 @@ export const scheduleTaskSchema = z.object({
|
|
|
250
292
|
ctx.addIssue({
|
|
251
293
|
code: z.ZodIssueCode.custom,
|
|
252
294
|
path: ["runAt"],
|
|
253
|
-
message: "
|
|
295
|
+
message: t("tool.error.onceSchedule"),
|
|
254
296
|
});
|
|
255
297
|
}
|
|
256
298
|
if (trigger === "once" && value.matrix) {
|
|
257
299
|
ctx.addIssue({
|
|
258
300
|
code: z.ZodIssueCode.custom,
|
|
259
301
|
path: ["matrix"],
|
|
260
|
-
message: "
|
|
302
|
+
message: t("tool.error.onceMatrixSchema"),
|
|
261
303
|
});
|
|
262
304
|
}
|
|
263
305
|
if (trigger !== "once" && (value.runAt || value.delaySeconds !== undefined)) {
|
|
264
306
|
ctx.addIssue({
|
|
265
307
|
code: z.ZodIssueCode.custom,
|
|
266
308
|
path: ["runAt"],
|
|
267
|
-
message: "
|
|
309
|
+
message: t("tool.error.onceFields"),
|
|
268
310
|
});
|
|
269
311
|
}
|
|
270
312
|
});
|
|
@@ -314,6 +356,44 @@ export const updateTaskSchema = z.object({
|
|
|
314
356
|
.string()
|
|
315
357
|
.optional()
|
|
316
358
|
.describe("New launch window end HH:MM. Empty string clears the window."),
|
|
359
|
+
activeDays: z
|
|
360
|
+
.array(z.number().int().min(0).max(6))
|
|
361
|
+
.optional()
|
|
362
|
+
.describe("New allowed weekdays 0=Sunday..6=Saturday. Empty array clears the restriction."),
|
|
363
|
+
windowPolicy: z
|
|
364
|
+
.enum(["skip", "postpone", "run"])
|
|
365
|
+
.optional()
|
|
366
|
+
.describe("New behaviour outside the window: postpone (default), skip or run."),
|
|
367
|
+
runWhenLoggedOff: z
|
|
368
|
+
.boolean()
|
|
369
|
+
.optional()
|
|
370
|
+
.describe("Windows only: true runs the task without a logged-on user (/ru SYSTEM, session 0 without the user profile, mapped drives or saved credentials; usually requires an elevated shell). false/omitted keeps the task interactive-only."),
|
|
371
|
+
watchGlobs: z
|
|
372
|
+
.array(z.string())
|
|
373
|
+
.optional()
|
|
374
|
+
.describe("New glob masks for a file trigger. Empty array clears them."),
|
|
375
|
+
watchIgnore: z
|
|
376
|
+
.array(z.string())
|
|
377
|
+
.optional()
|
|
378
|
+
.describe("New ignore masks for a file trigger. Empty array clears them."),
|
|
379
|
+
gitBranch: z
|
|
380
|
+
.string()
|
|
381
|
+
.optional()
|
|
382
|
+
.describe("New git branch filter (glob, comma-separated). Empty string clears it."),
|
|
383
|
+
gitPaths: z
|
|
384
|
+
.array(z.string())
|
|
385
|
+
.optional()
|
|
386
|
+
.describe("New changed-file masks for a git trigger. Empty array clears them."),
|
|
387
|
+
gitIgnore: z
|
|
388
|
+
.array(z.string())
|
|
389
|
+
.optional()
|
|
390
|
+
.describe("New ignored changed-file masks for a git trigger. Empty array clears them."),
|
|
391
|
+
gitPollSeconds: z
|
|
392
|
+
.number()
|
|
393
|
+
.int()
|
|
394
|
+
.min(5)
|
|
395
|
+
.optional()
|
|
396
|
+
.describe("New git polling interval in seconds."),
|
|
317
397
|
prompt: z
|
|
318
398
|
.string()
|
|
319
399
|
.optional()
|
|
@@ -351,7 +431,7 @@ export const updateTaskSchema = z.object({
|
|
|
351
431
|
.optional()
|
|
352
432
|
.describe("New error-chain task. Empty string clears it."),
|
|
353
433
|
triggerType: z
|
|
354
|
-
.enum(["cron", "file", "mcp-event", "once"])
|
|
434
|
+
.enum(["cron", "file", "git", "mcp-event", "once"])
|
|
355
435
|
.optional()
|
|
356
436
|
.describe("New trigger type."),
|
|
357
437
|
mcpEvent: z
|
|
@@ -393,14 +473,14 @@ export const updateTaskSchema = z.object({
|
|
|
393
473
|
ctx.addIssue({
|
|
394
474
|
code: z.ZodIssueCode.custom,
|
|
395
475
|
path: ["runAt"],
|
|
396
|
-
message: "
|
|
476
|
+
message: t("tool.error.onceFields"),
|
|
397
477
|
});
|
|
398
478
|
}
|
|
399
479
|
if (value.triggerType === "once" && value.matrix) {
|
|
400
480
|
ctx.addIssue({
|
|
401
481
|
code: z.ZodIssueCode.custom,
|
|
402
482
|
path: ["matrix"],
|
|
403
|
-
message: "
|
|
483
|
+
message: t("tool.error.onceMatrixUpdate"),
|
|
404
484
|
});
|
|
405
485
|
}
|
|
406
486
|
});
|
|
@@ -453,12 +533,12 @@ const manageWorkspacesSchema = z.object({
|
|
|
453
533
|
.record(z.string(), z.string())
|
|
454
534
|
.nullable()
|
|
455
535
|
.optional()
|
|
456
|
-
.describe("
|
|
536
|
+
.describe("Workspace environment variables (key → value). Override envFile values; secrets are masked in logs (add/update)."),
|
|
457
537
|
envFile: z
|
|
458
538
|
.string()
|
|
459
539
|
.nullable()
|
|
460
540
|
.optional()
|
|
461
|
-
.describe("
|
|
541
|
+
.describe("Path to the workspace .env file (add/update, null clears it)."),
|
|
462
542
|
});
|
|
463
543
|
export const matrixControlSchema = z.object({
|
|
464
544
|
action: z
|
|
@@ -516,6 +596,10 @@ export const manageSettingsSchema = z.object({
|
|
|
516
596
|
.max(16)
|
|
517
597
|
.optional()
|
|
518
598
|
.describe("How many task runs may execute at the same time."),
|
|
599
|
+
locale: z
|
|
600
|
+
.enum(["ru", "en"])
|
|
601
|
+
.optional()
|
|
602
|
+
.describe("Interface language: ru (default) or en. Applies without restart."),
|
|
519
603
|
winterMode: z
|
|
520
604
|
.boolean()
|
|
521
605
|
.optional()
|
|
@@ -656,9 +740,78 @@ function wrapExecute(fn) {
|
|
|
656
740
|
}
|
|
657
741
|
};
|
|
658
742
|
}
|
|
743
|
+
/**
|
|
744
|
+
* Спринт 27.5.2: ближайший запуск по определению задачи, без чтения ОС.
|
|
745
|
+
*
|
|
746
|
+
* - `once` → `runAt` (запланированный момент);
|
|
747
|
+
* - пауза (`paused` или будущий `pausedUntil`) → null;
|
|
748
|
+
* - `cron` → ближайшее совпадение cron с учётом окна и дней недели:
|
|
749
|
+
* * `run` — окно игнорируется;
|
|
750
|
+
* * `skip` — ищем следующее совпадение внутри окна;
|
|
751
|
+
* * `postpone` (по умолчанию) — перенос на открытие окна, как в schedule-gate;
|
|
752
|
+
* - `file`/`git`/`mcp-event` → null (расписания нет).
|
|
753
|
+
*/
|
|
754
|
+
function computeTaskNextRun(def, options = {}) {
|
|
755
|
+
if (!def)
|
|
756
|
+
return null;
|
|
757
|
+
if (options.paused)
|
|
758
|
+
return null;
|
|
759
|
+
const now = options.now ?? new Date();
|
|
760
|
+
if (def.pausedUntil) {
|
|
761
|
+
const until = Date.parse(def.pausedUntil);
|
|
762
|
+
if (Number.isFinite(until) && until > now.getTime())
|
|
763
|
+
return null;
|
|
764
|
+
}
|
|
765
|
+
const type = def.triggerType ?? "cron";
|
|
766
|
+
if (type === "once") {
|
|
767
|
+
if (!def.runAt)
|
|
768
|
+
return null;
|
|
769
|
+
const at = Date.parse(def.runAt);
|
|
770
|
+
return Number.isFinite(at) ? new Date(at).toISOString() : null;
|
|
771
|
+
}
|
|
772
|
+
if (type !== "cron")
|
|
773
|
+
return null;
|
|
774
|
+
const schedule = (def.schedule || "").trim();
|
|
775
|
+
if (!schedule)
|
|
776
|
+
return null;
|
|
777
|
+
const timeZone = def.timezone?.trim() || undefined;
|
|
778
|
+
const policy = def.windowPolicy === "skip" || def.windowPolicy === "run"
|
|
779
|
+
? def.windowPolicy
|
|
780
|
+
: "postpone";
|
|
781
|
+
const windowOptions = {
|
|
782
|
+
notBefore: def.notBefore,
|
|
783
|
+
notAfter: def.notAfter,
|
|
784
|
+
days: Array.isArray(def.activeDays) ? def.activeDays : undefined,
|
|
785
|
+
timeZone,
|
|
786
|
+
};
|
|
787
|
+
let tick;
|
|
788
|
+
try {
|
|
789
|
+
tick = cronNextRun(schedule, now, timeZone);
|
|
790
|
+
}
|
|
791
|
+
catch {
|
|
792
|
+
// Некорректное выражение не должно ломать ответ инструмента.
|
|
793
|
+
return null;
|
|
794
|
+
}
|
|
795
|
+
// skip-политика может пропустить сколько угодно тиков вне окна;
|
|
796
|
+
// ограничение защищает от бесконечного перебора (5-летнее окно cron).
|
|
797
|
+
for (let guard = 0; tick && guard < 600; guard += 1) {
|
|
798
|
+
if (policy === "run")
|
|
799
|
+
return tick.toISOString();
|
|
800
|
+
const state = activeWindowState(tick, windowOptions);
|
|
801
|
+
if (state.active)
|
|
802
|
+
return tick.toISOString();
|
|
803
|
+
if (policy === "skip") {
|
|
804
|
+
tick = cronNextRun(schedule, tick, timeZone);
|
|
805
|
+
continue;
|
|
806
|
+
}
|
|
807
|
+
// postpone: gate ждёт открытия окна и запускает задачу тогда же.
|
|
808
|
+
return state.nextOpenAt ? state.nextOpenAt.toISOString() : null;
|
|
809
|
+
}
|
|
810
|
+
return null;
|
|
811
|
+
}
|
|
659
812
|
/** schedule_task — создаёт задачу в schtasks через общий schedulerCreateTask. */
|
|
660
813
|
const scheduleTaskExecute = wrapExecute(async (args) => {
|
|
661
|
-
const { name, schedule, runAt, delaySeconds, prompt, timeoutSeconds, model, priority, beforeScript, afterScript, qualityGate, dependsOn, retryCount, retryDelay, nextTaskOnSuccess, nextTaskOnError, triggerType, mcpEvent, watchPath, workingDirectory, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, session, sessionMaxRuns, } = args;
|
|
814
|
+
const { name, schedule, runAt, delaySeconds, prompt, timeoutSeconds, model, priority, beforeScript, afterScript, qualityGate, dependsOn, retryCount, retryDelay, nextTaskOnSuccess, nextTaskOnError, triggerType, mcpEvent, watchPath, workingDirectory, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, session, sessionMaxRuns, activeDays, windowPolicy, watchGlobs, watchIgnore, gitBranch, gitPaths, gitIgnore, gitPollSeconds, runWhenLoggedOff, } = args;
|
|
662
815
|
let effectiveRunAt;
|
|
663
816
|
if ((triggerType ?? "cron") === "once") {
|
|
664
817
|
const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
|
|
@@ -674,7 +827,18 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
|
|
|
674
827
|
const effectiveSession = normalizeSessionMode(session) ?? "new";
|
|
675
828
|
const effectiveSessionId = effectiveSession === "reuse" ? generateSessionId() : undefined;
|
|
676
829
|
try {
|
|
677
|
-
await schedulerCreateTask(name, schedule ?? "", prompt, timeoutSeconds, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, undefined, "create", timezone, notBefore, notAfter, undefined, effectiveRunAt, effectiveSession, effectiveSessionId, sessionMaxRuns
|
|
830
|
+
await schedulerCreateTask(name, schedule ?? "", prompt, timeoutSeconds, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, undefined, "create", timezone, notBefore, notAfter, undefined, effectiveRunAt, effectiveSession, effectiveSessionId, sessionMaxRuns, {
|
|
831
|
+
activeDays,
|
|
832
|
+
windowPolicy,
|
|
833
|
+
watchGlobs,
|
|
834
|
+
watchIgnore,
|
|
835
|
+
gitBranch,
|
|
836
|
+
gitPaths,
|
|
837
|
+
gitIgnore,
|
|
838
|
+
gitPollSeconds,
|
|
839
|
+
},
|
|
840
|
+
// Спринт 27.5.4: Windows — работать без входа (/ru SYSTEM).
|
|
841
|
+
runWhenLoggedOff === true);
|
|
678
842
|
}
|
|
679
843
|
catch (err) {
|
|
680
844
|
return {
|
|
@@ -686,16 +850,34 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
|
|
|
686
850
|
}
|
|
687
851
|
// Новый файловый триггер должен начать работать сразу, без перезапуска
|
|
688
852
|
// OpenCode: пересобираем набор watcher-ов после создания задачи.
|
|
689
|
-
await
|
|
853
|
+
await refreshTriggers();
|
|
690
854
|
const workspace = workspaceId ? getWorkspace(workspaceId) : undefined;
|
|
691
855
|
const effectiveWorkdir = workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
|
|
856
|
+
// Спринт 27.5.2: отдаём ближайший запуск сразу, не дожидаясь обновления
|
|
857
|
+
// списка задач планировщика ОС (schtasks иногда отдаёт nextRunTime с задержкой).
|
|
858
|
+
const nextRun = computeTaskNextRun({
|
|
859
|
+
schedule: schedule ?? "",
|
|
860
|
+
triggerType: triggerType ?? "cron",
|
|
861
|
+
runAt: effectiveRunAt,
|
|
862
|
+
timezone,
|
|
863
|
+
notBefore,
|
|
864
|
+
notAfter,
|
|
865
|
+
activeDays,
|
|
866
|
+
windowPolicy,
|
|
867
|
+
});
|
|
692
868
|
return {
|
|
693
869
|
content: JSON.stringify({
|
|
694
870
|
success: true,
|
|
695
|
-
|
|
871
|
+
paused: false,
|
|
872
|
+
nextRun,
|
|
873
|
+
runWhenLoggedOff: runWhenLoggedOff === true,
|
|
874
|
+
message: t("tool.task.created", { name }),
|
|
696
875
|
task: {
|
|
697
876
|
name,
|
|
698
877
|
schedule,
|
|
878
|
+
nextRun,
|
|
879
|
+
paused: false,
|
|
880
|
+
runWhenLoggedOff: runWhenLoggedOff === true,
|
|
699
881
|
timeoutSeconds: timeoutSeconds ?? 3600,
|
|
700
882
|
model: model?.trim() || null,
|
|
701
883
|
priority: priority ?? 5,
|
|
@@ -726,21 +908,29 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
|
|
|
726
908
|
});
|
|
727
909
|
/** list_tasks — список задач плагина (та же логика, что и у get_tasks). */
|
|
728
910
|
const listTasksExecute = wrapExecute(async () => {
|
|
729
|
-
const tasks = await collectTasksView();
|
|
911
|
+
const { tasks, osAvailable, osError } = await collectTasksView();
|
|
730
912
|
if (tasks.length === 0) {
|
|
731
913
|
return {
|
|
732
914
|
content: JSON.stringify({
|
|
733
915
|
success: true,
|
|
734
|
-
message:
|
|
916
|
+
message: osAvailable
|
|
917
|
+
? t("tool.task.listEmpty")
|
|
918
|
+
: t("tool.task.listOsUnavailable"),
|
|
735
919
|
tasks: [],
|
|
920
|
+
osAvailable,
|
|
921
|
+
...(osError ? { osError } : {}),
|
|
736
922
|
}),
|
|
737
923
|
};
|
|
738
924
|
}
|
|
739
925
|
return {
|
|
740
926
|
content: JSON.stringify({
|
|
741
927
|
success: true,
|
|
742
|
-
message:
|
|
928
|
+
message: osAvailable
|
|
929
|
+
? t("tool.task.found", { count: tasks.length })
|
|
930
|
+
: t("tool.task.foundOsUnavailable", { count: tasks.length }),
|
|
743
931
|
tasks,
|
|
932
|
+
osAvailable,
|
|
933
|
+
...(osError ? { osError } : {}),
|
|
744
934
|
}),
|
|
745
935
|
};
|
|
746
936
|
});
|
|
@@ -753,7 +943,7 @@ const listTasksExecute = wrapExecute(async () => {
|
|
|
753
943
|
async function cancelMatrixRun(name) {
|
|
754
944
|
const definition = (await loadTaskDefinitions()).find((def) => def.name.toLowerCase() === name.trim().toLowerCase());
|
|
755
945
|
if (!definition?.matrix) {
|
|
756
|
-
throw new Error(
|
|
946
|
+
throw new Error(t("tool.error.matrixNotMatrix", { name }));
|
|
757
947
|
}
|
|
758
948
|
const result = await cancelPendingMatrixClones(definition.name);
|
|
759
949
|
const warnings = [];
|
|
@@ -766,28 +956,38 @@ async function cancelMatrixRun(name) {
|
|
|
766
956
|
await scheduler.deleteTask(clone.name);
|
|
767
957
|
}
|
|
768
958
|
catch (err) {
|
|
769
|
-
warnings.push(
|
|
959
|
+
warnings.push(t("tool.matrix.stopFailed", {
|
|
960
|
+
clone: clone.name,
|
|
961
|
+
error: err instanceof Error ? err.message : String(err),
|
|
962
|
+
}));
|
|
770
963
|
continue;
|
|
771
964
|
}
|
|
772
965
|
// Возвращаем placeholder-задачу, чтобы следующая fan-out-волна работала.
|
|
773
966
|
try {
|
|
774
|
-
await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, definition.name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil);
|
|
967
|
+
await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, definition.name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil, clone.runAt, clone.session, clone.sessionId, clone.sessionMaxRuns, undefined, clone.runWhenLoggedOff, clone.paused);
|
|
775
968
|
}
|
|
776
969
|
catch (err) {
|
|
777
|
-
warnings.push(
|
|
970
|
+
warnings.push(t("tool.matrix.recreateFailed", {
|
|
971
|
+
clone: clone.name,
|
|
972
|
+
error: err instanceof Error ? err.message : String(err),
|
|
973
|
+
}));
|
|
778
974
|
}
|
|
779
975
|
}
|
|
780
976
|
const parts = [
|
|
781
|
-
|
|
977
|
+
t("tool.matrix.cancelSummary", {
|
|
978
|
+
matrix: definition.name,
|
|
979
|
+
cancelled: result.cancelled.length,
|
|
980
|
+
total: result.aggregate.totalCount,
|
|
981
|
+
}),
|
|
782
982
|
];
|
|
783
983
|
if (result.running.length > 0) {
|
|
784
|
-
parts.push(
|
|
984
|
+
parts.push(t("tool.matrix.cancelRunning", { count: result.running.length }));
|
|
785
985
|
}
|
|
786
986
|
if (result.alreadyFinished.length > 0) {
|
|
787
|
-
parts.push(
|
|
987
|
+
parts.push(t("tool.matrix.cancelFinished", { count: result.alreadyFinished.length }));
|
|
788
988
|
}
|
|
789
989
|
if (warnings.length > 0) {
|
|
790
|
-
parts.push(
|
|
990
|
+
parts.push(t("tool.matrix.cancelWarnings", { warnings: warnings.join("; ") }));
|
|
791
991
|
}
|
|
792
992
|
return {
|
|
793
993
|
cancelled: result.cancelled,
|
|
@@ -827,6 +1027,87 @@ async function cleanupOrphanedMatrixTasks() {
|
|
|
827
1027
|
* - удаление родителя-матрицы каскадно удаляет клоны и агрегатор;
|
|
828
1028
|
* - удаление клона поодиночке запрещено (защита от «сирот» и вечного running).
|
|
829
1029
|
*/
|
|
1030
|
+
/**
|
|
1031
|
+
* Удаляет файлы-артефакты задачи (wrapper, prompt, log, lock, env).
|
|
1032
|
+
* Отсутствующие файлы игнорируются — операция идемпотентна.
|
|
1033
|
+
*/
|
|
1034
|
+
async function removeTaskArtifacts(name) {
|
|
1035
|
+
const sanitized = sanitizeName(name);
|
|
1036
|
+
const candidates = [
|
|
1037
|
+
path.join(WRAPPER_DIR, `run-${sanitized}.cmd`),
|
|
1038
|
+
path.join(WRAPPER_DIR, `run-${sanitized}.sh`),
|
|
1039
|
+
path.join(PLUGIN_DIR, "prompts", `${sanitized}.txt`),
|
|
1040
|
+
path.join(LOG_DIR, `${sanitized}.log`),
|
|
1041
|
+
path.join(PLUGIN_DIR, "env", `${sanitized}.env`),
|
|
1042
|
+
path.join(LOCK_DIR, `${sanitized}.lock`),
|
|
1043
|
+
path.join(LOCK_DIR, `${sanitized}.lock.defer`),
|
|
1044
|
+
path.join(LOCK_DIR, `${sanitized}.lock.force`),
|
|
1045
|
+
];
|
|
1046
|
+
await Promise.all(candidates.map((file) => fs.unlink(file).catch(() => undefined)));
|
|
1047
|
+
}
|
|
1048
|
+
/**
|
|
1049
|
+
* Сборщик мусора по wrapper-ам при старте: удаляет файлы задач, которых
|
|
1050
|
+
* больше нет ни в БД, ни в планировщике ОС. Активные (свежий lock) не трогает.
|
|
1051
|
+
*/
|
|
1052
|
+
async function garbageCollectTaskArtifacts() {
|
|
1053
|
+
let entries;
|
|
1054
|
+
try {
|
|
1055
|
+
entries = await fs.readdir(WRAPPER_DIR);
|
|
1056
|
+
}
|
|
1057
|
+
catch {
|
|
1058
|
+
return;
|
|
1059
|
+
}
|
|
1060
|
+
const wrappers = entries.filter((file) => /^run-.+\.(cmd|sh)$/.test(file));
|
|
1061
|
+
if (wrappers.length === 0)
|
|
1062
|
+
return;
|
|
1063
|
+
const known = new Set();
|
|
1064
|
+
try {
|
|
1065
|
+
for (const task of listTaskDefinitions())
|
|
1066
|
+
known.add(sanitizeName(task.name));
|
|
1067
|
+
}
|
|
1068
|
+
catch {
|
|
1069
|
+
// БД может быть ещё не готова — тогда опираемся на ОС.
|
|
1070
|
+
}
|
|
1071
|
+
try {
|
|
1072
|
+
for (const task of await scheduler.listTasks()) {
|
|
1073
|
+
known.add(sanitizeName(task.taskName || ""));
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
catch {
|
|
1077
|
+
// Планировщик недоступен — не удаляем ничего, чтобы не потерять данные.
|
|
1078
|
+
return;
|
|
1079
|
+
}
|
|
1080
|
+
let cleaned = 0;
|
|
1081
|
+
for (const file of wrappers) {
|
|
1082
|
+
const stem = file.replace(/^run-/, "").replace(/\.(cmd|sh)$/, "");
|
|
1083
|
+
const lockPath = path.join(LOCK_DIR, `${stem}.lock`);
|
|
1084
|
+
if (known.has(stem))
|
|
1085
|
+
continue;
|
|
1086
|
+
try {
|
|
1087
|
+
const stat = await fs.stat(lockPath);
|
|
1088
|
+
if (Date.now() - stat.mtimeMs < STALE_LOCK_MAX_AGE_MS)
|
|
1089
|
+
continue;
|
|
1090
|
+
}
|
|
1091
|
+
catch {
|
|
1092
|
+
// lock-файла нет — можно удалять.
|
|
1093
|
+
}
|
|
1094
|
+
const candidates = [
|
|
1095
|
+
path.join(WRAPPER_DIR, `run-${stem}.cmd`),
|
|
1096
|
+
path.join(WRAPPER_DIR, `run-${stem}.sh`),
|
|
1097
|
+
path.join(PLUGIN_DIR, "prompts", `${stem}.txt`),
|
|
1098
|
+
path.join(LOG_DIR, `${stem}.log`),
|
|
1099
|
+
path.join(PLUGIN_DIR, "env", `${stem}.env`),
|
|
1100
|
+
path.join(LOCK_DIR, `${stem}.lock`),
|
|
1101
|
+
path.join(LOCK_DIR, `${stem}.lock.defer`),
|
|
1102
|
+
path.join(LOCK_DIR, `${stem}.lock.force`),
|
|
1103
|
+
];
|
|
1104
|
+
await Promise.all(candidates.map((pathToFile) => fs.unlink(pathToFile).catch(() => undefined)));
|
|
1105
|
+
cleaned += 1;
|
|
1106
|
+
}
|
|
1107
|
+
if (cleaned > 0) {
|
|
1108
|
+
console.log(`[gc] Вычищено мусорных файлов задач: ${cleaned}`);
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
830
1111
|
async function deleteTaskWithFamily(name) {
|
|
831
1112
|
const trimmed = name.trim();
|
|
832
1113
|
const guard = getMatrixDeletionGuard(trimmed);
|
|
@@ -862,6 +1143,7 @@ async function deleteTaskWithFamily(name) {
|
|
|
862
1143
|
catch {
|
|
863
1144
|
// Не критично.
|
|
864
1145
|
}
|
|
1146
|
+
removeTaskArtifacts(child);
|
|
865
1147
|
removed.push(child);
|
|
866
1148
|
}
|
|
867
1149
|
}
|
|
@@ -872,6 +1154,7 @@ async function deleteTaskWithFamily(name) {
|
|
|
872
1154
|
catch {
|
|
873
1155
|
// Определения могло уже не быть — задача всё равно удалена из ОС.
|
|
874
1156
|
}
|
|
1157
|
+
removeTaskArtifacts(trimmed);
|
|
875
1158
|
return { removed, existed };
|
|
876
1159
|
}
|
|
877
1160
|
/** delete_task — удаление задачи по имени (/f) */
|
|
@@ -880,12 +1163,12 @@ const deleteTaskExecute = wrapExecute(async (args) => {
|
|
|
880
1163
|
try {
|
|
881
1164
|
const { removed, existed } = await deleteTaskWithFamily(name);
|
|
882
1165
|
// Убираем watcher удалённой задачи, не дожидаясь перезапуска плагина.
|
|
883
|
-
await
|
|
1166
|
+
await refreshTriggers();
|
|
884
1167
|
if (!existed && removed.length === 0) {
|
|
885
1168
|
return {
|
|
886
1169
|
content: JSON.stringify({
|
|
887
|
-
success:
|
|
888
|
-
|
|
1170
|
+
success: true,
|
|
1171
|
+
message: t("tool.task.alreadyAbsent", { name }),
|
|
889
1172
|
}),
|
|
890
1173
|
};
|
|
891
1174
|
}
|
|
@@ -893,8 +1176,8 @@ const deleteTaskExecute = wrapExecute(async (args) => {
|
|
|
893
1176
|
content: JSON.stringify({
|
|
894
1177
|
success: true,
|
|
895
1178
|
message: removed.length > 0
|
|
896
|
-
?
|
|
897
|
-
:
|
|
1179
|
+
? t("tool.task.matrixDeletedList", { name, list: removed.join(", ") })
|
|
1180
|
+
: t("tool.task.deleted", { name }),
|
|
898
1181
|
}),
|
|
899
1182
|
};
|
|
900
1183
|
}
|
|
@@ -927,8 +1210,8 @@ const runTaskNowExecute = wrapExecute(async (args) => {
|
|
|
927
1210
|
content: JSON.stringify({
|
|
928
1211
|
success: true,
|
|
929
1212
|
message: alreadyRunning
|
|
930
|
-
?
|
|
931
|
-
:
|
|
1213
|
+
? t("tool.task.alreadyRunning", { name })
|
|
1214
|
+
: t("tool.task.started", { name }),
|
|
932
1215
|
}),
|
|
933
1216
|
};
|
|
934
1217
|
});
|
|
@@ -975,11 +1258,11 @@ async function removeMatrixChildrenFromScheduler(name) {
|
|
|
975
1258
|
async function updateTaskFromInput(input) {
|
|
976
1259
|
const name = input.name?.trim();
|
|
977
1260
|
if (!name) {
|
|
978
|
-
return { success: false, message: "
|
|
1261
|
+
return { success: false, message: t("tool.error.taskNameMissing") };
|
|
979
1262
|
}
|
|
980
1263
|
const previous = getTask(name);
|
|
981
1264
|
if (!previous) {
|
|
982
|
-
return { success: false, message:
|
|
1265
|
+
return { success: false, message: t("tool.error.taskNotFound", { name }) };
|
|
983
1266
|
}
|
|
984
1267
|
const schedule = clearableString(input.schedule ?? input.newSchedule, previous.schedule);
|
|
985
1268
|
const prompt = clearableString(input.prompt ?? input.newPrompt, previous.prompt);
|
|
@@ -990,13 +1273,13 @@ async function updateTaskFromInput(input) {
|
|
|
990
1273
|
if (triggerType === "cron" && !schedule) {
|
|
991
1274
|
return {
|
|
992
1275
|
success: false,
|
|
993
|
-
message:
|
|
1276
|
+
message: t("tool.error.updateCron", { name }),
|
|
994
1277
|
};
|
|
995
1278
|
}
|
|
996
1279
|
if (!prompt) {
|
|
997
1280
|
return {
|
|
998
1281
|
success: false,
|
|
999
|
-
message:
|
|
1282
|
+
message: t("tool.error.updatePrompt", { name }),
|
|
1000
1283
|
};
|
|
1001
1284
|
}
|
|
1002
1285
|
// One-shot: без нового runAt/delaySeconds сохраняем прежнее время.
|
|
@@ -1015,7 +1298,7 @@ async function updateTaskFromInput(input) {
|
|
|
1015
1298
|
if (!normalized.ok) {
|
|
1016
1299
|
return {
|
|
1017
1300
|
success: false,
|
|
1018
|
-
message:
|
|
1301
|
+
message: t("tool.error.taskReason", { name, error: normalized.error }),
|
|
1019
1302
|
};
|
|
1020
1303
|
}
|
|
1021
1304
|
runAt = normalized.runAt;
|
|
@@ -1028,7 +1311,7 @@ async function updateTaskFromInput(input) {
|
|
|
1028
1311
|
if (!normalizedSession) {
|
|
1029
1312
|
return {
|
|
1030
1313
|
success: false,
|
|
1031
|
-
message:
|
|
1314
|
+
message: t("tool.error.sessionUnknown", { name, session: String(input.session) }),
|
|
1032
1315
|
};
|
|
1033
1316
|
}
|
|
1034
1317
|
session = normalizedSession;
|
|
@@ -1041,7 +1324,7 @@ async function updateTaskFromInput(input) {
|
|
|
1041
1324
|
(!Number.isInteger(sessionMaxRuns) || sessionMaxRuns < 1)) {
|
|
1042
1325
|
return {
|
|
1043
1326
|
success: false,
|
|
1044
|
-
message:
|
|
1327
|
+
message: t("tool.error.sessionMaxRuns", { name }),
|
|
1045
1328
|
};
|
|
1046
1329
|
}
|
|
1047
1330
|
let sessionId = previous.sessionId;
|
|
@@ -1056,32 +1339,106 @@ async function updateTaskFromInput(input) {
|
|
|
1056
1339
|
if (triggerType === "once" && matrixNext) {
|
|
1057
1340
|
return {
|
|
1058
1341
|
success: false,
|
|
1059
|
-
message:
|
|
1060
|
-
`Запустите матрицу вручную или используйте cron/file-триггер.`,
|
|
1342
|
+
message: t("tool.error.oneShotMatrix", { name }),
|
|
1061
1343
|
};
|
|
1062
1344
|
}
|
|
1345
|
+
// Спринт 27: параметры триггеров сохраняются, если поле не передано.
|
|
1346
|
+
const mergeStringList = (next, prev) => {
|
|
1347
|
+
if (next === undefined)
|
|
1348
|
+
return prev;
|
|
1349
|
+
const cleaned = next
|
|
1350
|
+
.filter((item) => typeof item === "string")
|
|
1351
|
+
.map((item) => item.trim())
|
|
1352
|
+
.filter(Boolean);
|
|
1353
|
+
return cleaned.length > 0 ? cleaned : undefined;
|
|
1354
|
+
};
|
|
1355
|
+
const triggerExtras = {
|
|
1356
|
+
activeDays: input.activeDays === undefined
|
|
1357
|
+
? previous.activeDays
|
|
1358
|
+
: input.activeDays.length > 0
|
|
1359
|
+
? input.activeDays
|
|
1360
|
+
: undefined,
|
|
1361
|
+
windowPolicy: input.windowPolicy ?? previous.windowPolicy,
|
|
1362
|
+
watchGlobs: mergeStringList(input.watchGlobs, previous.watchGlobs),
|
|
1363
|
+
watchIgnore: mergeStringList(input.watchIgnore, previous.watchIgnore),
|
|
1364
|
+
gitBranch: clearableString(input.gitBranch, previous.gitBranch),
|
|
1365
|
+
gitPaths: mergeStringList(input.gitPaths, previous.gitPaths),
|
|
1366
|
+
gitIgnore: mergeStringList(input.gitIgnore, previous.gitIgnore),
|
|
1367
|
+
gitPollSeconds: input.gitPollSeconds ?? previous.gitPollSeconds,
|
|
1368
|
+
};
|
|
1369
|
+
// Спринт 27.5.8: update = пересоздание задачи, поэтому паузу нужно вернуть
|
|
1370
|
+
// после create — иначе задача молча начинает выполняться по расписанию.
|
|
1371
|
+
const wasPaused = Boolean(previous.paused === true ||
|
|
1372
|
+
(previous.pausedUntil && Date.parse(previous.pausedUntil) > Date.now()));
|
|
1373
|
+
let previousDeleted = false;
|
|
1063
1374
|
try {
|
|
1064
1375
|
// Обновление = пересоздание в планировщике с сохранением старых значений.
|
|
1065
1376
|
await scheduler.deleteTask(name);
|
|
1377
|
+
previousDeleted = true;
|
|
1066
1378
|
await schedulerCreateTask(name, schedule ?? "", prompt, input.timeoutSeconds ?? previous.timeoutSeconds, clearableString(input.workingDirectory, previous.workingDirectory), input.retryCount ?? previous.retryCount, input.retryDelay ?? previous.retryDelay, clearableString(input.qualityGate, previous.qualityGate), clearableString(input.nextTaskOnSuccess, previous.nextTaskOnSuccess), clearableString(input.nextTaskOnError, previous.nextTaskOnError), triggerType, clearableString(input.watchPath, previous.watchPath), clearableList(input.dependsOn, previous.dependsOn), clearableString(input.model, previous.model), input.priority ?? previous.priority, clearableString(input.beforeScript, previous.beforeScript), clearableString(input.afterScript, previous.afterScript), input.mcpEvent ?? previous.mcpEvent, clearableString(input.workspaceId, previous.workspaceId), clearableList(input.allowedTools, previous.allowedTools), clearableList(input.deniedTools, previous.deniedTools), matrixNext, undefined,
|
|
1067
1379
|
// Если задача была матрицей — синхронизируем клонов, а не
|
|
1068
1380
|
// пересоздаём их с нуля (Спринт 17).
|
|
1069
|
-
matrixWas && matrixNext ? "sync" : "create", timezone, notBefore, notAfter, previous.pausedUntil, runAt, session, sessionId, sessionMaxRuns);
|
|
1381
|
+
matrixWas && matrixNext ? "sync" : "create", timezone, notBefore, notAfter, previous.pausedUntil, runAt, session, sessionId, sessionMaxRuns, triggerExtras, input.runWhenLoggedOff ?? previous.runWhenLoggedOff, wasPaused);
|
|
1070
1382
|
// Матрица отключена при обновлении — убираем клонов и агрегатор.
|
|
1071
1383
|
if (matrixWas && !matrixNext) {
|
|
1072
1384
|
await removeMatrixChildrenFromScheduler(name);
|
|
1073
1385
|
}
|
|
1074
1386
|
// Пересоздание могло изменить triggerType/watchPath — сразу
|
|
1075
1387
|
// пересобираем набор файловых watcher-ов.
|
|
1076
|
-
await
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1388
|
+
await refreshTriggers();
|
|
1389
|
+
// Спринт 27.5.2: после пересоздания задачи сообщаем ближайший запуск,
|
|
1390
|
+
// рассчитанный из нового определения, не дожидаясь ОС.
|
|
1391
|
+
const updated = getTask(name);
|
|
1392
|
+
const paused = wasPaused;
|
|
1080
1393
|
return {
|
|
1081
|
-
success:
|
|
1082
|
-
|
|
1394
|
+
success: true,
|
|
1395
|
+
paused,
|
|
1396
|
+
nextRun: computeTaskNextRun(updated, { paused }),
|
|
1397
|
+
message: t("tool.task.updated", { name }),
|
|
1083
1398
|
};
|
|
1084
1399
|
}
|
|
1400
|
+
catch (err) {
|
|
1401
|
+
const cause = err instanceof Error ? err.message : String(err);
|
|
1402
|
+
// Спринт 27.5.6: задача удалена из ОС, но новую версию создать не удалось.
|
|
1403
|
+
if (!previousDeleted) {
|
|
1404
|
+
return {
|
|
1405
|
+
success: false,
|
|
1406
|
+
restored: true,
|
|
1407
|
+
message: t("tool.task.rollbackKept", { cause }),
|
|
1408
|
+
};
|
|
1409
|
+
}
|
|
1410
|
+
// Убираем возможный частичный результат новой попытки: обёртка могла
|
|
1411
|
+
// успеть зарегистрироваться, хотя create вернул ошибку.
|
|
1412
|
+
try {
|
|
1413
|
+
await scheduler.deleteTask(name);
|
|
1414
|
+
}
|
|
1415
|
+
catch {
|
|
1416
|
+
// Задачи могло не быть — это ожидаемо.
|
|
1417
|
+
}
|
|
1418
|
+
// Определение в БД ещё не перезаписано, поэтому восстанавливаем ровно
|
|
1419
|
+
// прежнюю версию: расписание, промпт, обёртку и паузу.
|
|
1420
|
+
try {
|
|
1421
|
+
await recreateTaskFromDefinition(previous);
|
|
1422
|
+
await refreshTriggers().catch(() => undefined);
|
|
1423
|
+
return {
|
|
1424
|
+
success: false,
|
|
1425
|
+
restored: true,
|
|
1426
|
+
message: t("tool.task.rollbackRestored", { cause }),
|
|
1427
|
+
};
|
|
1428
|
+
}
|
|
1429
|
+
catch (restoreErr) {
|
|
1430
|
+
const restoreMessage = restoreErr instanceof Error ? restoreErr.message : String(restoreErr);
|
|
1431
|
+
return {
|
|
1432
|
+
success: false,
|
|
1433
|
+
restored: false,
|
|
1434
|
+
message: t("tool.task.rollbackFailed", {
|
|
1435
|
+
cause,
|
|
1436
|
+
restore: restoreMessage,
|
|
1437
|
+
name,
|
|
1438
|
+
}),
|
|
1439
|
+
};
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1085
1442
|
}
|
|
1086
1443
|
/** update_task — частичное обновление существующей задачи. */
|
|
1087
1444
|
const updateTaskExecute = wrapExecute(async (args) => {
|
|
@@ -1098,9 +1455,12 @@ async function pauseOrResumeTask(name, paused, until) {
|
|
|
1098
1455
|
if (!definition) {
|
|
1099
1456
|
return {
|
|
1100
1457
|
success: false,
|
|
1101
|
-
message:
|
|
1458
|
+
message: t("tool.error.taskNotFound", { name: trimmed }),
|
|
1102
1459
|
affected: [],
|
|
1103
1460
|
warnings: [],
|
|
1461
|
+
paused,
|
|
1462
|
+
nextRun: null,
|
|
1463
|
+
pausedUntil: null,
|
|
1104
1464
|
};
|
|
1105
1465
|
}
|
|
1106
1466
|
// Пауза до даты (Спринт 19): проверяем ISO-момент до каких-либо изменений.
|
|
@@ -1110,17 +1470,23 @@ async function pauseOrResumeTask(name, paused, until) {
|
|
|
1110
1470
|
if (Number.isNaN(parsed)) {
|
|
1111
1471
|
return {
|
|
1112
1472
|
success: false,
|
|
1113
|
-
message:
|
|
1473
|
+
message: t("tool.error.pauseDateInvalid", { name: trimmed, until }),
|
|
1114
1474
|
affected: [],
|
|
1115
1475
|
warnings: [],
|
|
1476
|
+
paused,
|
|
1477
|
+
nextRun: null,
|
|
1478
|
+
pausedUntil: definition.pausedUntil ?? null,
|
|
1116
1479
|
};
|
|
1117
1480
|
}
|
|
1118
1481
|
if (parsed <= Date.now()) {
|
|
1119
1482
|
return {
|
|
1120
1483
|
success: false,
|
|
1121
|
-
message:
|
|
1484
|
+
message: t("tool.error.pauseDatePast", { name: trimmed }),
|
|
1122
1485
|
affected: [],
|
|
1123
1486
|
warnings: [],
|
|
1487
|
+
paused,
|
|
1488
|
+
nextRun: null,
|
|
1489
|
+
pausedUntil: definition.pausedUntil ?? null,
|
|
1124
1490
|
};
|
|
1125
1491
|
}
|
|
1126
1492
|
pausedUntil = new Date(parsed).toISOString();
|
|
@@ -1131,9 +1497,12 @@ async function pauseOrResumeTask(name, paused, until) {
|
|
|
1131
1497
|
if (targets.length === 0 && definition.matrix) {
|
|
1132
1498
|
return {
|
|
1133
1499
|
success: false,
|
|
1134
|
-
message:
|
|
1500
|
+
message: t("tool.error.matrixNoClones", { name: trimmed }),
|
|
1135
1501
|
affected: [],
|
|
1136
1502
|
warnings: [],
|
|
1503
|
+
paused,
|
|
1504
|
+
nextRun: null,
|
|
1505
|
+
pausedUntil: definition.pausedUntil ?? null,
|
|
1137
1506
|
};
|
|
1138
1507
|
}
|
|
1139
1508
|
const affected = [];
|
|
@@ -1152,37 +1521,65 @@ async function pauseOrResumeTask(name, paused, until) {
|
|
|
1152
1521
|
warnings.push(`${target}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1153
1522
|
}
|
|
1154
1523
|
}
|
|
1155
|
-
// Фиксируем (или снимаем)
|
|
1524
|
+
// Фиксируем (или снимаем) паузу в определении задачи. У матрицы
|
|
1156
1525
|
// родитель хранит pausedUntil за всех клонов — их включает авто-resume.
|
|
1526
|
+
// Спринт 27.5.8: бессрочная пауза тоже сохраняется в определении, иначе
|
|
1527
|
+
// update_task пересоздаёт задачу включённой и пауза теряется.
|
|
1157
1528
|
const definitionUpdates = paused
|
|
1158
|
-
? pausedUntil
|
|
1159
|
-
|
|
1160
|
-
: undefined
|
|
1161
|
-
: definition.pausedUntil
|
|
1162
|
-
? { pausedUntil: undefined }
|
|
1529
|
+
? { paused: true, ...(pausedUntil ? { pausedUntil } : {}) }
|
|
1530
|
+
: definition.paused || definition.pausedUntil
|
|
1531
|
+
? { paused: false, pausedUntil: undefined }
|
|
1163
1532
|
: undefined;
|
|
1164
1533
|
if (definitionUpdates && affected.length > 0) {
|
|
1165
1534
|
try {
|
|
1166
1535
|
saveTask({ ...definition, ...definitionUpdates });
|
|
1167
1536
|
}
|
|
1168
1537
|
catch (err) {
|
|
1169
|
-
warnings.push(
|
|
1538
|
+
warnings.push(t("tool.task.autosave", {
|
|
1539
|
+
error: err instanceof Error ? err.message : String(err),
|
|
1540
|
+
}));
|
|
1170
1541
|
}
|
|
1171
1542
|
}
|
|
1172
1543
|
const untilText = pausedUntil
|
|
1173
|
-
?
|
|
1544
|
+
? t("tool.task.until", { date: new Date(pausedUntil).toLocaleString() })
|
|
1174
1545
|
: "";
|
|
1175
|
-
const verb = paused ? "
|
|
1546
|
+
const verb = paused ? t("tool.task.paused") : t("tool.task.resumed");
|
|
1176
1547
|
const message = definition.matrix
|
|
1177
|
-
?
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1548
|
+
? t("tool.task.matrixPaused", {
|
|
1549
|
+
name: trimmed,
|
|
1550
|
+
verb,
|
|
1551
|
+
until: untilText,
|
|
1552
|
+
affected: affected.length,
|
|
1553
|
+
total: targets.length,
|
|
1554
|
+
}) +
|
|
1555
|
+
(warnings.length > 0
|
|
1556
|
+
? t("tool.task.matrixPauseErrors", { warnings: warnings.join("; ") })
|
|
1557
|
+
: "")
|
|
1558
|
+
: t("tool.task.pausedText", {
|
|
1559
|
+
name: trimmed,
|
|
1560
|
+
verb,
|
|
1561
|
+
until: untilText,
|
|
1562
|
+
}) +
|
|
1563
|
+
(warnings.length > 0
|
|
1564
|
+
? t("tool.task.pauseError", { warnings: warnings.join("; ") })
|
|
1565
|
+
: "");
|
|
1566
|
+
// Спринт 27.5.2: состояние и ближайший запуск считаем из определения —
|
|
1567
|
+
// schtasks после /change (особенно /enable) отдаёт nextRunTime с задержкой.
|
|
1568
|
+
const effectivePausedUntil = paused
|
|
1569
|
+
? pausedUntil ?? definition.pausedUntil ?? null
|
|
1570
|
+
: null;
|
|
1571
|
+
const after = definitionUpdates
|
|
1572
|
+
? { ...definition, ...definitionUpdates }
|
|
1573
|
+
: { ...definition, paused: false, pausedUntil: undefined };
|
|
1574
|
+
const nextRun = paused ? null : computeTaskNextRun(after);
|
|
1181
1575
|
return {
|
|
1182
1576
|
success: warnings.length === 0,
|
|
1183
1577
|
message,
|
|
1184
1578
|
affected,
|
|
1185
1579
|
warnings,
|
|
1580
|
+
paused,
|
|
1581
|
+
nextRun,
|
|
1582
|
+
pausedUntil: effectivePausedUntil,
|
|
1186
1583
|
};
|
|
1187
1584
|
}
|
|
1188
1585
|
const pauseTaskExecute = wrapExecute(async (args) => {
|
|
@@ -1220,7 +1617,11 @@ async function resumeExpiredPauses() {
|
|
|
1220
1617
|
for (const target of targets) {
|
|
1221
1618
|
await scheduler.resumeTask(target);
|
|
1222
1619
|
}
|
|
1223
|
-
await saveTaskDefinition({
|
|
1620
|
+
await saveTaskDefinition({
|
|
1621
|
+
...definition,
|
|
1622
|
+
pausedUntil: undefined,
|
|
1623
|
+
paused: false,
|
|
1624
|
+
});
|
|
1224
1625
|
console.log(`[windows-scheduler] Автопродолжение: задача "${definition.name}" включена (пауза истекла).`);
|
|
1225
1626
|
}
|
|
1226
1627
|
catch (err) {
|
|
@@ -1374,7 +1775,7 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
|
|
|
1374
1775
|
return {
|
|
1375
1776
|
content: JSON.stringify({
|
|
1376
1777
|
success: false,
|
|
1377
|
-
error: "
|
|
1778
|
+
error: t("tool.workspace.needPath"),
|
|
1378
1779
|
}),
|
|
1379
1780
|
};
|
|
1380
1781
|
}
|
|
@@ -1401,7 +1802,7 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
|
|
|
1401
1802
|
return {
|
|
1402
1803
|
content: JSON.stringify({
|
|
1403
1804
|
success: false,
|
|
1404
|
-
error: "
|
|
1805
|
+
error: t("tool.workspace.needUpdateId"),
|
|
1405
1806
|
}),
|
|
1406
1807
|
};
|
|
1407
1808
|
}
|
|
@@ -1416,7 +1817,7 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
|
|
|
1416
1817
|
return {
|
|
1417
1818
|
content: JSON.stringify({
|
|
1418
1819
|
success: false,
|
|
1419
|
-
error: "
|
|
1820
|
+
error: t("tool.workspace.notFound"),
|
|
1420
1821
|
}),
|
|
1421
1822
|
};
|
|
1422
1823
|
}
|
|
@@ -1440,7 +1841,7 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
|
|
|
1440
1841
|
return {
|
|
1441
1842
|
content: JSON.stringify({
|
|
1442
1843
|
success: false,
|
|
1443
|
-
error: "
|
|
1844
|
+
error: t("tool.workspace.needDeleteId"),
|
|
1444
1845
|
}),
|
|
1445
1846
|
};
|
|
1446
1847
|
}
|
|
@@ -1449,8 +1850,8 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
|
|
|
1449
1850
|
content: JSON.stringify({
|
|
1450
1851
|
success: deleted,
|
|
1451
1852
|
message: deleted
|
|
1452
|
-
? "
|
|
1453
|
-
: "
|
|
1853
|
+
? t("tool.workspace.deleted")
|
|
1854
|
+
: t("tool.workspace.notFound"),
|
|
1454
1855
|
}),
|
|
1455
1856
|
};
|
|
1456
1857
|
}
|
|
@@ -1496,8 +1897,8 @@ const matrixControlExecute = wrapExecute(async (args) => {
|
|
|
1496
1897
|
content: JSON.stringify({
|
|
1497
1898
|
success: true,
|
|
1498
1899
|
message: removed.length > 0
|
|
1499
|
-
?
|
|
1500
|
-
: "
|
|
1900
|
+
? t("tool.matrix.orphansRemoved", { count: removed.length })
|
|
1901
|
+
: t("tool.matrix.orphansNone"),
|
|
1501
1902
|
removed,
|
|
1502
1903
|
}),
|
|
1503
1904
|
};
|
|
@@ -1507,7 +1908,7 @@ const matrixControlExecute = wrapExecute(async (args) => {
|
|
|
1507
1908
|
return {
|
|
1508
1909
|
content: JSON.stringify({
|
|
1509
1910
|
success: false,
|
|
1510
|
-
error:
|
|
1911
|
+
error: t("tool.matrix.actionName", { action: args.action }),
|
|
1511
1912
|
}),
|
|
1512
1913
|
};
|
|
1513
1914
|
}
|
|
@@ -1571,6 +1972,7 @@ const manageSettingsExecute = wrapExecute(async (args) => {
|
|
|
1571
1972
|
return { content: JSON.stringify({ success: true, settings: current }) };
|
|
1572
1973
|
}
|
|
1573
1974
|
if (args.maxConcurrent === undefined &&
|
|
1975
|
+
args.locale === undefined &&
|
|
1574
1976
|
args.winterMode === undefined &&
|
|
1575
1977
|
args.notifications === undefined &&
|
|
1576
1978
|
args.history === undefined &&
|
|
@@ -1579,19 +1981,22 @@ const manageSettingsExecute = wrapExecute(async (args) => {
|
|
|
1579
1981
|
return {
|
|
1580
1982
|
content: JSON.stringify({
|
|
1581
1983
|
success: false,
|
|
1582
|
-
error: "
|
|
1984
|
+
error: t("tool.settings.updateFields"),
|
|
1583
1985
|
settings: current,
|
|
1584
1986
|
}),
|
|
1585
1987
|
};
|
|
1586
1988
|
}
|
|
1587
1989
|
const settings = await saveSettings({
|
|
1588
1990
|
maxConcurrent: args.maxConcurrent,
|
|
1991
|
+
locale: args.locale,
|
|
1589
1992
|
winterMode: args.winterMode,
|
|
1590
1993
|
notifications: args.notifications,
|
|
1591
1994
|
history: args.history,
|
|
1592
1995
|
integrations: args.integrations,
|
|
1593
1996
|
audit: args.audit,
|
|
1594
1997
|
});
|
|
1998
|
+
// Локаль процесса меняется сразу — перезапуск плагина не нужен.
|
|
1999
|
+
setLocale(settings.locale);
|
|
1595
2000
|
return { content: JSON.stringify({ success: true, settings }) };
|
|
1596
2001
|
});
|
|
1597
2002
|
/** manage_templates — список, сохранение и удаление шаблонов задач. */
|
|
@@ -1602,7 +2007,7 @@ const manageTemplatesExecute = wrapExecute(async (args) => {
|
|
|
1602
2007
|
if (args.action === "delete") {
|
|
1603
2008
|
const id = args.id?.trim();
|
|
1604
2009
|
if (!id) {
|
|
1605
|
-
return { content: JSON.stringify({ success: false, error: "
|
|
2010
|
+
return { content: JSON.stringify({ success: false, error: t("tool.template.needDeleteId") }) };
|
|
1606
2011
|
}
|
|
1607
2012
|
const before = await loadTemplates();
|
|
1608
2013
|
const existed = before.some((template) => template.id === id);
|
|
@@ -1610,7 +2015,9 @@ const manageTemplatesExecute = wrapExecute(async (args) => {
|
|
|
1610
2015
|
return {
|
|
1611
2016
|
content: JSON.stringify({
|
|
1612
2017
|
success: existed,
|
|
1613
|
-
message: existed
|
|
2018
|
+
message: existed
|
|
2019
|
+
? t("tool.template.deleted", { id })
|
|
2020
|
+
: t("tool.template.notFound", { id }),
|
|
1614
2021
|
}),
|
|
1615
2022
|
};
|
|
1616
2023
|
}
|
|
@@ -1619,7 +2026,7 @@ const manageTemplatesExecute = wrapExecute(async (args) => {
|
|
|
1619
2026
|
return {
|
|
1620
2027
|
content: JSON.stringify({
|
|
1621
2028
|
success: false,
|
|
1622
|
-
error: "
|
|
2029
|
+
error: t("tool.template.saveRequired"),
|
|
1623
2030
|
}),
|
|
1624
2031
|
};
|
|
1625
2032
|
}
|
|
@@ -1643,7 +2050,7 @@ const manageProfilesExecute = wrapExecute(async (args) => {
|
|
|
1643
2050
|
return {
|
|
1644
2051
|
content: JSON.stringify({
|
|
1645
2052
|
success: false,
|
|
1646
|
-
error:
|
|
2053
|
+
error: t("tool.profile.nameRequired", { action: args.action }),
|
|
1647
2054
|
}),
|
|
1648
2055
|
};
|
|
1649
2056
|
}
|
|
@@ -1653,7 +2060,7 @@ const manageProfilesExecute = wrapExecute(async (args) => {
|
|
|
1653
2060
|
return {
|
|
1654
2061
|
content: JSON.stringify({
|
|
1655
2062
|
success: true,
|
|
1656
|
-
message:
|
|
2063
|
+
message: t("tool.profile.created", { name: meta.name, port: meta.port }),
|
|
1657
2064
|
profile: profile ?? {
|
|
1658
2065
|
name: meta.name,
|
|
1659
2066
|
dir: getProfileDir(meta.name),
|
|
@@ -1673,8 +2080,8 @@ const manageProfilesExecute = wrapExecute(async (args) => {
|
|
|
1673
2080
|
current,
|
|
1674
2081
|
restartRequired: true,
|
|
1675
2082
|
message: isProfilePinnedByEnv()
|
|
1676
|
-
?
|
|
1677
|
-
:
|
|
2083
|
+
? t("tool.profile.envVar", { name: current })
|
|
2084
|
+
: t("tool.profile.active", { name: sanitizeProfileName(name) }),
|
|
1678
2085
|
}),
|
|
1679
2086
|
};
|
|
1680
2087
|
}
|
|
@@ -1683,8 +2090,8 @@ const manageProfilesExecute = wrapExecute(async (args) => {
|
|
|
1683
2090
|
content: JSON.stringify({
|
|
1684
2091
|
success: removed,
|
|
1685
2092
|
message: removed
|
|
1686
|
-
?
|
|
1687
|
-
: "
|
|
2093
|
+
? t("tool.profile.deleted", { name: sanitizeProfileName(name) })
|
|
2094
|
+
: t("tool.profile.notFound"),
|
|
1688
2095
|
}),
|
|
1689
2096
|
};
|
|
1690
2097
|
});
|
|
@@ -1696,14 +2103,14 @@ const transferTasksExecute = wrapExecute(async (args) => {
|
|
|
1696
2103
|
return { content: JSON.stringify({ success: true, data, count }) };
|
|
1697
2104
|
}
|
|
1698
2105
|
if (!args.data) {
|
|
1699
|
-
return { content: JSON.stringify({ success: false, error: "
|
|
2106
|
+
return { content: JSON.stringify({ success: false, error: t("tool.transfer.importData") }) };
|
|
1700
2107
|
}
|
|
1701
2108
|
const parsed = parseImportJson(args.data);
|
|
1702
2109
|
if (parsed.tasks.length === 0) {
|
|
1703
2110
|
return {
|
|
1704
2111
|
content: JSON.stringify({
|
|
1705
2112
|
success: false,
|
|
1706
|
-
error: "
|
|
2113
|
+
error: t("tool.transfer.noTasks"),
|
|
1707
2114
|
errors: parsed.errors,
|
|
1708
2115
|
}),
|
|
1709
2116
|
};
|
|
@@ -1720,7 +2127,7 @@ const transferTasksExecute = wrapExecute(async (args) => {
|
|
|
1720
2127
|
errors.push(`${def.name}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1721
2128
|
}
|
|
1722
2129
|
}
|
|
1723
|
-
await
|
|
2130
|
+
await refreshTriggers();
|
|
1724
2131
|
return {
|
|
1725
2132
|
content: JSON.stringify({ success: errors.length === 0, imported, errors }),
|
|
1726
2133
|
};
|
|
@@ -1757,7 +2164,12 @@ const cleanupHistoryExecute = wrapExecute(async (args) => {
|
|
|
1757
2164
|
success: true,
|
|
1758
2165
|
message: report.skipped
|
|
1759
2166
|
? report.skipped
|
|
1760
|
-
:
|
|
2167
|
+
: t("tool.history.cleaned", {
|
|
2168
|
+
deleted: report.deleted,
|
|
2169
|
+
byAge: report.deletedByAge,
|
|
2170
|
+
byCount: report.deletedByCount,
|
|
2171
|
+
kept: report.kept,
|
|
2172
|
+
}),
|
|
1761
2173
|
report,
|
|
1762
2174
|
}),
|
|
1763
2175
|
};
|
|
@@ -1766,7 +2178,7 @@ const cleanupHistoryExecute = wrapExecute(async (args) => {
|
|
|
1766
2178
|
const emitEventExecute = wrapExecute(async (args) => {
|
|
1767
2179
|
const eventName = args.eventName?.trim();
|
|
1768
2180
|
if (!eventName) {
|
|
1769
|
-
return { content: JSON.stringify({ success: false, error: "
|
|
2181
|
+
return { content: JSON.stringify({ success: false, error: t("tool.event.nameRequired") }) };
|
|
1770
2182
|
}
|
|
1771
2183
|
const payload = args.payload ?? {};
|
|
1772
2184
|
const definitions = await loadTaskDefinitions();
|
|
@@ -1789,8 +2201,8 @@ const emitEventExecute = wrapExecute(async (args) => {
|
|
|
1789
2201
|
content: JSON.stringify({
|
|
1790
2202
|
success: true,
|
|
1791
2203
|
message: triggered.length > 0
|
|
1792
|
-
?
|
|
1793
|
-
:
|
|
2204
|
+
? t("tool.event.triggered", { count: triggered.length })
|
|
2205
|
+
: t("tool.event.none", { event: eventName }),
|
|
1794
2206
|
triggered,
|
|
1795
2207
|
}),
|
|
1796
2208
|
};
|
|
@@ -1805,7 +2217,7 @@ const manageSecretsExecute = wrapExecute(async (args) => {
|
|
|
1805
2217
|
return {
|
|
1806
2218
|
content: JSON.stringify({
|
|
1807
2219
|
success: false,
|
|
1808
|
-
error: "
|
|
2220
|
+
error: t("tool.secret.nameRequired"),
|
|
1809
2221
|
}),
|
|
1810
2222
|
};
|
|
1811
2223
|
}
|
|
@@ -1816,8 +2228,8 @@ const manageSecretsExecute = wrapExecute(async (args) => {
|
|
|
1816
2228
|
content: JSON.stringify({
|
|
1817
2229
|
success: existed,
|
|
1818
2230
|
message: existed
|
|
1819
|
-
?
|
|
1820
|
-
:
|
|
2231
|
+
? t("tool.secret.deleted", { name })
|
|
2232
|
+
: t("tool.secret.notFound", { name }),
|
|
1821
2233
|
}),
|
|
1822
2234
|
};
|
|
1823
2235
|
}
|
|
@@ -1826,7 +2238,7 @@ const manageSecretsExecute = wrapExecute(async (args) => {
|
|
|
1826
2238
|
return {
|
|
1827
2239
|
content: JSON.stringify({
|
|
1828
2240
|
success: false,
|
|
1829
|
-
error: "
|
|
2241
|
+
error: t("tool.secret.valueRequired"),
|
|
1830
2242
|
}),
|
|
1831
2243
|
};
|
|
1832
2244
|
}
|
|
@@ -1834,7 +2246,7 @@ const manageSecretsExecute = wrapExecute(async (args) => {
|
|
|
1834
2246
|
return {
|
|
1835
2247
|
content: JSON.stringify({
|
|
1836
2248
|
success: true,
|
|
1837
|
-
message:
|
|
2249
|
+
message: t("tool.secret.saved", { name: item.name }),
|
|
1838
2250
|
secret: item,
|
|
1839
2251
|
}),
|
|
1840
2252
|
};
|
|
@@ -1976,15 +2388,74 @@ function withRpcAudit(handlers) {
|
|
|
1976
2388
|
* работать лишь после перезапуска OpenCode.
|
|
1977
2389
|
*/
|
|
1978
2390
|
let fileWatcherManager = null;
|
|
1979
|
-
|
|
1980
|
-
|
|
2391
|
+
/**
|
|
2392
|
+
* Спринт 27: менеджер git-триггеров. Опрашивает HEAD задач с
|
|
2393
|
+
* triggerType === "git" и запускает их при новых подходящих коммитах.
|
|
2394
|
+
*/
|
|
2395
|
+
let gitTriggerManager = null;
|
|
2396
|
+
/**
|
|
2397
|
+
* Приводит в актуальное состояние все событийные триггеры (файлы и git).
|
|
2398
|
+
* Вызывается после создания, изменения и удаления задачи.
|
|
2399
|
+
*/
|
|
2400
|
+
async function refreshTriggers() {
|
|
2401
|
+
if (fileWatcherManager) {
|
|
2402
|
+
try {
|
|
2403
|
+
await fileWatcherManager.refresh();
|
|
2404
|
+
}
|
|
2405
|
+
catch (err) {
|
|
2406
|
+
console.error(`[windows-scheduler] Не удалось обновить файловые триггеры: ${err instanceof Error ? err.message : String(err)}`);
|
|
2407
|
+
}
|
|
2408
|
+
}
|
|
2409
|
+
if (gitTriggerManager) {
|
|
2410
|
+
try {
|
|
2411
|
+
await gitTriggerManager.refresh();
|
|
2412
|
+
}
|
|
2413
|
+
catch (err) {
|
|
2414
|
+
console.error(`[windows-scheduler] Не удалось обновить git-триггеры: ${err instanceof Error ? err.message : String(err)}`);
|
|
2415
|
+
}
|
|
2416
|
+
}
|
|
2417
|
+
}
|
|
2418
|
+
/** Максимальная задержка переноса событийного запуска (12 часов). */
|
|
2419
|
+
const EVENT_POSTPONE_MAX_MS = 12 * 60 * 60 * 1000;
|
|
2420
|
+
/**
|
|
2421
|
+
* Спринт 27: запуск задачи по событию (файл, git, MCP) с учётом окна запуска
|
|
2422
|
+
* и разрешённых дней недели. Вне окна: skip — пишем причину и выходим,
|
|
2423
|
+
* postpone — таймер до ближайшего открытия, run — запускаем сразу.
|
|
2424
|
+
*/
|
|
2425
|
+
async function scheduleEventRun(taskName, reason) {
|
|
2426
|
+
const definition = getTask(taskName);
|
|
2427
|
+
if (!definition)
|
|
2428
|
+
return;
|
|
2429
|
+
const policy = definition.windowPolicy ?? "postpone";
|
|
2430
|
+
const options = {
|
|
2431
|
+
notBefore: definition.notBefore,
|
|
2432
|
+
notAfter: definition.notAfter,
|
|
2433
|
+
days: definition.activeDays,
|
|
2434
|
+
timeZone: definition.timezone,
|
|
2435
|
+
};
|
|
2436
|
+
const now = new Date();
|
|
2437
|
+
const state = activeWindowState(now, options);
|
|
2438
|
+
if (state.active || policy === "run") {
|
|
2439
|
+
await runTaskEntry(taskName);
|
|
2440
|
+
console.log(`[windows-scheduler] Запуск задачи "${taskName}" (${reason}).`);
|
|
1981
2441
|
return;
|
|
1982
|
-
try {
|
|
1983
|
-
await fileWatcherManager.refresh();
|
|
1984
2442
|
}
|
|
1985
|
-
|
|
1986
|
-
console.
|
|
2443
|
+
if (policy === "skip") {
|
|
2444
|
+
console.log(`[windows-scheduler] Задача "${taskName}" не запущена (${reason}): ${state.reason ?? "вне окна"} — политика skip.`);
|
|
2445
|
+
return;
|
|
1987
2446
|
}
|
|
2447
|
+
const delay = nextWindowOpenDelayMs(now, options);
|
|
2448
|
+
if (delay <= 0 || delay > EVENT_POSTPONE_MAX_MS) {
|
|
2449
|
+
console.log(`[windows-scheduler] Задача "${taskName}" не запущена (${reason}): ${state.reason ?? "вне окна"} — до открытия окна больше 12 ч.`);
|
|
2450
|
+
return;
|
|
2451
|
+
}
|
|
2452
|
+
console.log(`[windows-scheduler] Задача "${taskName}" (${reason}) отложена на ~${Math.round(delay / 60000)} мин: ${state.reason ?? "вне окна"}.`);
|
|
2453
|
+
const timer = setTimeout(() => {
|
|
2454
|
+
void scheduleEventRun(taskName, reason).catch((err) => {
|
|
2455
|
+
console.error(`[windows-scheduler] Не удалось запустить отложенную задачу "${taskName}": ${err instanceof Error ? err.message : String(err)}`);
|
|
2456
|
+
});
|
|
2457
|
+
}, delay);
|
|
2458
|
+
timer.unref?.();
|
|
1988
2459
|
}
|
|
1989
2460
|
export default Plugin.define({
|
|
1990
2461
|
id: "opencode-windows-scheduler",
|
|
@@ -1992,6 +2463,14 @@ export default Plugin.define({
|
|
|
1992
2463
|
// Папка проекта — рабочая директория задач по умолчанию. Благодаря ей
|
|
1993
2464
|
// `opencode run` подхватывает opencode.json с MCP-серверами проекта.
|
|
1994
2465
|
projectDirectory = ctx.location?.directory || process.cwd();
|
|
2466
|
+
// Спринт 28: язык интерфейса берём из настроек. Ошибка чтения не должна
|
|
2467
|
+
// мешать старту — в этом случае остаётся локаль по умолчанию (ru).
|
|
2468
|
+
try {
|
|
2469
|
+
setLocale((await loadSettings()).locale);
|
|
2470
|
+
}
|
|
2471
|
+
catch {
|
|
2472
|
+
// Локаль по умолчанию уже активна.
|
|
2473
|
+
}
|
|
1995
2474
|
// Спринт 12: SQLite — основное хранилище. Открываем БД, при первом запуске
|
|
1996
2475
|
// автоматически переносим данные из JSON, затем восстанавливаем прерванные
|
|
1997
2476
|
// запуски. Ошибки миграции не должны мешать плагину стартовать.
|
|
@@ -2009,6 +2488,9 @@ export default Plugin.define({
|
|
|
2009
2488
|
console.error(`[recovery] Не удалось восстановить незавершённые запуски: ${err instanceof Error ? err.message : String(err)}`);
|
|
2010
2489
|
}
|
|
2011
2490
|
checkJsonBackups();
|
|
2491
|
+
void garbageCollectTaskArtifacts().catch((err) => {
|
|
2492
|
+
console.log(`[gc] Не удалось вычистить мусорные файлы: ${err instanceof Error ? err.message : String(err)}`);
|
|
2493
|
+
});
|
|
2012
2494
|
// Спринт 18: ежедневная очистка истории. Ошибка ретеншна не должна мешать
|
|
2013
2495
|
// плагину стартовать — пишем в лог и продолжаем.
|
|
2014
2496
|
void maybeRunHistoryRetention()
|
|
@@ -2096,14 +2578,23 @@ export default Plugin.define({
|
|
|
2096
2578
|
// запускаются при изменении watchPath через chokidar (с дебаунсом).
|
|
2097
2579
|
fileWatcherManager = new FileWatchManager(async (taskName) => {
|
|
2098
2580
|
try {
|
|
2099
|
-
await
|
|
2100
|
-
console.log(`[windows-scheduler] Запуск задачи "${taskName}" по изменению отслеживаемого файла.`);
|
|
2581
|
+
await scheduleEventRun(taskName, "изменение отслеживаемого файла");
|
|
2101
2582
|
}
|
|
2102
2583
|
catch (err) {
|
|
2103
2584
|
console.error(`[windows-scheduler] Не удалось запустить задачу "${taskName}" по файловому триггеру: ${err instanceof Error ? err.message : String(err)}`);
|
|
2104
2585
|
}
|
|
2105
2586
|
});
|
|
2106
|
-
|
|
2587
|
+
// Спринт 27: git-триггеры — опрос HEAD и запуск при новых коммитах,
|
|
2588
|
+
// затронувших подходящие файлы.
|
|
2589
|
+
gitTriggerManager = new GitTriggerManager(async (taskName, info) => {
|
|
2590
|
+
try {
|
|
2591
|
+
await scheduleEventRun(taskName, `новый коммит ${info.head?.slice(0, 7) ?? ""}`);
|
|
2592
|
+
}
|
|
2593
|
+
catch (err) {
|
|
2594
|
+
console.error(`[windows-scheduler] Не удалось запустить задачу "${taskName}" по git-триггеру: ${err instanceof Error ? err.message : String(err)}`);
|
|
2595
|
+
}
|
|
2596
|
+
});
|
|
2597
|
+
void refreshTriggers();
|
|
2107
2598
|
const registration = await ctx.tool.transform((editor) => {
|
|
2108
2599
|
// editor.add регистрирует новые инструменты плагина с codemode: true,
|
|
2109
2600
|
// чтобы они были видны в Code Mode. Встроенные schedule_* отключены
|
|
@@ -2348,16 +2839,21 @@ export default Plugin.define({
|
|
|
2348
2839
|
// schedule_task и create_task использовали один и тот же путь.
|
|
2349
2840
|
const rpcHandlers = {
|
|
2350
2841
|
get_tasks: async () => {
|
|
2351
|
-
|
|
2842
|
+
const view = await collectTasksView();
|
|
2843
|
+
return {
|
|
2844
|
+
tasks: view.tasks,
|
|
2845
|
+
osAvailable: view.osAvailable,
|
|
2846
|
+
...(view.osError ? { osError: view.osError } : {}),
|
|
2847
|
+
};
|
|
2352
2848
|
},
|
|
2353
2849
|
create_task: async (input) => {
|
|
2354
2850
|
console.log("[windows-scheduler] create_task input:", input);
|
|
2355
|
-
const { name, schedule, prompt, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, dependsOn, triggerType, watchPath, workingDirectory, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, runAt, delaySeconds, session, sessionMaxRuns, } = input;
|
|
2851
|
+
const { name, schedule, prompt, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, dependsOn, triggerType, watchPath, workingDirectory, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, runAt, delaySeconds, session, sessionMaxRuns, runWhenLoggedOff, } = input;
|
|
2356
2852
|
let effectiveRunAt;
|
|
2357
2853
|
if (triggerType === "once") {
|
|
2358
2854
|
const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
|
|
2359
2855
|
if (!normalized.ok) {
|
|
2360
|
-
return { success: false, message:
|
|
2856
|
+
return { success: false, message: t("tool.error.taskReason", { name, error: normalized.error }) };
|
|
2361
2857
|
}
|
|
2362
2858
|
effectiveRunAt = normalized.runAt;
|
|
2363
2859
|
}
|
|
@@ -2365,18 +2861,31 @@ export default Plugin.define({
|
|
|
2365
2861
|
if (session !== undefined) {
|
|
2366
2862
|
const normalizedSession = normalizeSessionMode(session);
|
|
2367
2863
|
if (!normalizedSession) {
|
|
2368
|
-
return { success: false, message:
|
|
2864
|
+
return { success: false, message: t("tool.error.sessionUnknown", { name, session: String(session) }) };
|
|
2369
2865
|
}
|
|
2370
2866
|
effectiveSession = normalizedSession;
|
|
2371
2867
|
}
|
|
2372
2868
|
if (sessionMaxRuns !== undefined &&
|
|
2373
2869
|
(!Number.isInteger(sessionMaxRuns) || sessionMaxRuns < 1)) {
|
|
2374
|
-
return { success: false, message:
|
|
2870
|
+
return { success: false, message: t("tool.error.sessionMaxRuns", { name }) };
|
|
2375
2871
|
}
|
|
2376
2872
|
const effectiveSessionId = effectiveSession === "reuse" ? generateSessionId() : undefined;
|
|
2377
2873
|
try {
|
|
2378
|
-
await schedulerCreateTask(name, schedule ?? "", prompt, undefined, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, undefined, "create", timezone, notBefore, notAfter, undefined, effectiveRunAt, effectiveSession, effectiveSessionId, sessionMaxRuns);
|
|
2379
|
-
|
|
2874
|
+
await schedulerCreateTask(name, schedule ?? "", prompt, undefined, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, undefined, "create", timezone, notBefore, notAfter, undefined, effectiveRunAt, effectiveSession, effectiveSessionId, sessionMaxRuns, undefined, runWhenLoggedOff === true);
|
|
2875
|
+
const nextRun = computeTaskNextRun({
|
|
2876
|
+
schedule: schedule ?? "",
|
|
2877
|
+
triggerType: triggerType ?? "cron",
|
|
2878
|
+
runAt: effectiveRunAt,
|
|
2879
|
+
timezone,
|
|
2880
|
+
notBefore,
|
|
2881
|
+
notAfter,
|
|
2882
|
+
});
|
|
2883
|
+
return {
|
|
2884
|
+
success: true,
|
|
2885
|
+
paused: false,
|
|
2886
|
+
nextRun,
|
|
2887
|
+
message: t("tool.task.created", { name }),
|
|
2888
|
+
};
|
|
2380
2889
|
}
|
|
2381
2890
|
catch (err) {
|
|
2382
2891
|
const message = err instanceof Error ? err.message : String(err);
|
|
@@ -2390,8 +2899,11 @@ export default Plugin.define({
|
|
|
2390
2899
|
return {
|
|
2391
2900
|
success: true,
|
|
2392
2901
|
message: removed.length > 0
|
|
2393
|
-
?
|
|
2394
|
-
|
|
2902
|
+
? t("tool.task.matrixDeletedCount", {
|
|
2903
|
+
name,
|
|
2904
|
+
count: removed.length,
|
|
2905
|
+
})
|
|
2906
|
+
: t("tool.task.deleted", { name }),
|
|
2395
2907
|
};
|
|
2396
2908
|
}
|
|
2397
2909
|
catch (err) {
|
|
@@ -2422,8 +2934,8 @@ export default Plugin.define({
|
|
|
2422
2934
|
return {
|
|
2423
2935
|
success: true,
|
|
2424
2936
|
message: removed.length > 0
|
|
2425
|
-
?
|
|
2426
|
-
: "
|
|
2937
|
+
? t("tool.matrix.orphansRemoved", { count: removed.length })
|
|
2938
|
+
: t("tool.matrix.orphansNone"),
|
|
2427
2939
|
removed,
|
|
2428
2940
|
};
|
|
2429
2941
|
}
|
|
@@ -2443,9 +2955,21 @@ export default Plugin.define({
|
|
|
2443
2955
|
if (definition?.matrix) {
|
|
2444
2956
|
const matrixResult = await runMatrix(definition);
|
|
2445
2957
|
const total = definition.matrix.workspaceIds.length;
|
|
2446
|
-
const message =
|
|
2447
|
-
|
|
2448
|
-
|
|
2958
|
+
const message = t("tool.matrix.started", {
|
|
2959
|
+
name,
|
|
2960
|
+
started: matrixResult.started.length,
|
|
2961
|
+
total,
|
|
2962
|
+
}) +
|
|
2963
|
+
(matrixResult.skipped.length
|
|
2964
|
+
? t("tool.matrix.startedSkipped", {
|
|
2965
|
+
count: matrixResult.skipped.length,
|
|
2966
|
+
})
|
|
2967
|
+
: "") +
|
|
2968
|
+
(matrixResult.errors.length
|
|
2969
|
+
? t("tool.matrix.startedErrors", {
|
|
2970
|
+
errors: matrixResult.errors.join("; "),
|
|
2971
|
+
})
|
|
2972
|
+
: ".");
|
|
2449
2973
|
return { success: matrixResult.success, message };
|
|
2450
2974
|
}
|
|
2451
2975
|
// Контроль параллелизма: не позволяем запускать новую задачу,
|
|
@@ -2457,7 +2981,7 @@ export default Plugin.define({
|
|
|
2457
2981
|
if (runningCount >= settings.maxConcurrent) {
|
|
2458
2982
|
return {
|
|
2459
2983
|
success: false,
|
|
2460
|
-
message: "
|
|
2984
|
+
message: t("tool.matrix.limit"),
|
|
2461
2985
|
};
|
|
2462
2986
|
}
|
|
2463
2987
|
}
|
|
@@ -2466,9 +2990,9 @@ export default Plugin.define({
|
|
|
2466
2990
|
// в том числе инициированном из GUI, — дублировать запись здесь не нужно.
|
|
2467
2991
|
if (result.alreadyRunning) {
|
|
2468
2992
|
// Мягкое предупреждение: задача уже идёт, это не ошибка запуска.
|
|
2469
|
-
return { success: true, message:
|
|
2993
|
+
return { success: true, message: t("tool.task.alreadyRunning", { name }) };
|
|
2470
2994
|
}
|
|
2471
|
-
return { success: true, message:
|
|
2995
|
+
return { success: true, message: t("tool.task.started", { name }) };
|
|
2472
2996
|
}
|
|
2473
2997
|
catch (err) {
|
|
2474
2998
|
return { success: false, message: `schtasks error: ${err instanceof Error ? err.message : String(err)}` };
|
|
@@ -2478,7 +3002,7 @@ export default Plugin.define({
|
|
|
2478
3002
|
const { eventName, payload } = input;
|
|
2479
3003
|
const normalized = eventName?.trim();
|
|
2480
3004
|
if (!normalized) {
|
|
2481
|
-
return { success: false, message: "
|
|
3005
|
+
return { success: false, message: t("tool.event.nameRequiredShort"), triggered: [] };
|
|
2482
3006
|
}
|
|
2483
3007
|
// Ищем задачи с MCP-триггером, совпадающим по имени события и фильтру.
|
|
2484
3008
|
const definitions = await loadTaskDefinitions();
|
|
@@ -2501,18 +3025,18 @@ export default Plugin.define({
|
|
|
2501
3025
|
return {
|
|
2502
3026
|
success: true,
|
|
2503
3027
|
triggered,
|
|
2504
|
-
message:
|
|
3028
|
+
message: t("tool.event.processed", { event: normalized, count: triggered.length }),
|
|
2505
3029
|
};
|
|
2506
3030
|
},
|
|
2507
3031
|
pause_task: async (input) => {
|
|
2508
3032
|
const { name, until } = input;
|
|
2509
3033
|
const result = await pauseOrResumeTask(name, true, until);
|
|
2510
|
-
return
|
|
3034
|
+
return result;
|
|
2511
3035
|
},
|
|
2512
3036
|
resume_task: async (input) => {
|
|
2513
3037
|
const { name } = input;
|
|
2514
3038
|
const result = await pauseOrResumeTask(name, false);
|
|
2515
|
-
return
|
|
3039
|
+
return result;
|
|
2516
3040
|
},
|
|
2517
3041
|
update_task: async (input) => {
|
|
2518
3042
|
return await updateTaskFromInput(input);
|
|
@@ -2546,8 +3070,12 @@ export default Plugin.define({
|
|
|
2546
3070
|
const report = await runHistoryRetention({ retentionDays, maxRecords });
|
|
2547
3071
|
const message = report.skipped
|
|
2548
3072
|
? report.skipped
|
|
2549
|
-
:
|
|
2550
|
-
|
|
3073
|
+
: t("tool.history.cleaned", {
|
|
3074
|
+
deleted: report.deleted,
|
|
3075
|
+
byAge: report.deletedByAge,
|
|
3076
|
+
byCount: report.deletedByCount,
|
|
3077
|
+
kept: report.kept,
|
|
3078
|
+
});
|
|
2551
3079
|
return {
|
|
2552
3080
|
success: true,
|
|
2553
3081
|
message,
|
|
@@ -2563,7 +3091,9 @@ export default Plugin.define({
|
|
|
2563
3091
|
catch (err) {
|
|
2564
3092
|
return {
|
|
2565
3093
|
success: false,
|
|
2566
|
-
message:
|
|
3094
|
+
message: t("tool.history.cleanFailed", {
|
|
3095
|
+
error: err instanceof Error ? err.message : String(err),
|
|
3096
|
+
}),
|
|
2567
3097
|
deleted: 0,
|
|
2568
3098
|
deletedByAge: 0,
|
|
2569
3099
|
deletedByCount: 0,
|
|
@@ -2647,7 +3177,7 @@ export default Plugin.define({
|
|
|
2647
3177
|
const { parentId } = input;
|
|
2648
3178
|
const target = (parentId ?? "").trim();
|
|
2649
3179
|
if (!target) {
|
|
2650
|
-
return { success: false, error: "
|
|
3180
|
+
return { success: false, error: t("tool.matrix.parentMissing") };
|
|
2651
3181
|
}
|
|
2652
3182
|
try {
|
|
2653
3183
|
const report = aggregateMatrixResults(target);
|
|
@@ -2724,7 +3254,7 @@ export default Plugin.define({
|
|
|
2724
3254
|
const { id, name, path: workspacePath, color, env, envFile } = input;
|
|
2725
3255
|
const workspace = updateWorkspace(id, { name, path: workspacePath, color, env, envFile });
|
|
2726
3256
|
if (!workspace) {
|
|
2727
|
-
return { success: false, error: "
|
|
3257
|
+
return { success: false, error: t("tool.workspace.notFound") };
|
|
2728
3258
|
}
|
|
2729
3259
|
// env-файлы существующих задач перегенерируются сразу (Спринт 21).
|
|
2730
3260
|
await refreshWorkspaceEnvFiles(workspace.id);
|
|
@@ -2748,8 +3278,8 @@ export default Plugin.define({
|
|
|
2748
3278
|
return {
|
|
2749
3279
|
success: deleted,
|
|
2750
3280
|
message: deleted
|
|
2751
|
-
? "
|
|
2752
|
-
: "
|
|
3281
|
+
? t("tool.workspace.deleted")
|
|
3282
|
+
: t("tool.workspace.notFound"),
|
|
2753
3283
|
};
|
|
2754
3284
|
}
|
|
2755
3285
|
catch (err) {
|
|
@@ -2773,8 +3303,8 @@ export default Plugin.define({
|
|
|
2773
3303
|
current,
|
|
2774
3304
|
restartRequired: true,
|
|
2775
3305
|
message: isProfilePinnedByEnv()
|
|
2776
|
-
?
|
|
2777
|
-
:
|
|
3306
|
+
? t("tool.profile.envVarLong", { name: current })
|
|
3307
|
+
: t("tool.profile.active", { name: sanitizeProfileName(name) }),
|
|
2778
3308
|
};
|
|
2779
3309
|
}
|
|
2780
3310
|
catch (err) {
|
|
@@ -2793,7 +3323,7 @@ export default Plugin.define({
|
|
|
2793
3323
|
const profile = listProfiles().find((item) => item.name === meta.name);
|
|
2794
3324
|
return {
|
|
2795
3325
|
success: true,
|
|
2796
|
-
message:
|
|
3326
|
+
message: t("tool.profile.created", { name: meta.name, port: meta.port }),
|
|
2797
3327
|
profile: profile ?? {
|
|
2798
3328
|
name: meta.name,
|
|
2799
3329
|
dir: getProfileDir(meta.name),
|
|
@@ -2817,8 +3347,8 @@ export default Plugin.define({
|
|
|
2817
3347
|
return {
|
|
2818
3348
|
success: removed,
|
|
2819
3349
|
message: removed
|
|
2820
|
-
?
|
|
2821
|
-
: "
|
|
3350
|
+
? t("tool.profile.deleted", { name: sanitizeProfileName(name) })
|
|
3351
|
+
: t("tool.profile.notFound"),
|
|
2822
3352
|
};
|
|
2823
3353
|
}
|
|
2824
3354
|
catch (err) {
|
|
@@ -2829,9 +3359,10 @@ export default Plugin.define({
|
|
|
2829
3359
|
return await loadSettings();
|
|
2830
3360
|
},
|
|
2831
3361
|
save_settings: async (input) => {
|
|
2832
|
-
const { maxConcurrent, winterMode, notifications, history, integrations, audit } = input;
|
|
3362
|
+
const { maxConcurrent, locale, winterMode, notifications, history, integrations, audit } = input;
|
|
2833
3363
|
const current = await loadSettings();
|
|
2834
3364
|
if (maxConcurrent === undefined &&
|
|
3365
|
+
locale === undefined &&
|
|
2835
3366
|
winterMode === undefined &&
|
|
2836
3367
|
notifications === undefined &&
|
|
2837
3368
|
history === undefined &&
|
|
@@ -2840,6 +3371,7 @@ export default Plugin.define({
|
|
|
2840
3371
|
return {
|
|
2841
3372
|
success: false,
|
|
2842
3373
|
maxConcurrent: current.maxConcurrent,
|
|
3374
|
+
locale: current.locale,
|
|
2843
3375
|
winterMode: current.winterMode,
|
|
2844
3376
|
notifications: current.notifications,
|
|
2845
3377
|
history: current.history,
|
|
@@ -2849,15 +3381,19 @@ export default Plugin.define({
|
|
|
2849
3381
|
}
|
|
2850
3382
|
const settings = await saveSettings({
|
|
2851
3383
|
maxConcurrent,
|
|
3384
|
+
locale,
|
|
2852
3385
|
winterMode,
|
|
2853
3386
|
notifications,
|
|
2854
3387
|
history,
|
|
2855
3388
|
integrations,
|
|
2856
3389
|
audit,
|
|
2857
3390
|
});
|
|
3391
|
+
// Локаль процесса меняется сразу — перезапуск не нужен.
|
|
3392
|
+
setLocale(settings.locale);
|
|
2858
3393
|
return {
|
|
2859
3394
|
success: true,
|
|
2860
3395
|
maxConcurrent: settings.maxConcurrent,
|
|
3396
|
+
locale: settings.locale,
|
|
2861
3397
|
winterMode: settings.winterMode,
|
|
2862
3398
|
notifications: settings.notifications,
|
|
2863
3399
|
history: settings.history,
|
|
@@ -2881,15 +3417,15 @@ export default Plugin.define({
|
|
|
2881
3417
|
const source = (input ?? {});
|
|
2882
3418
|
const name = (source.name ?? "").trim();
|
|
2883
3419
|
if (!name) {
|
|
2884
|
-
return { success: false, message: "
|
|
3420
|
+
return { success: false, message: t("tool.secret.needName") };
|
|
2885
3421
|
}
|
|
2886
3422
|
if (typeof source.value !== "string" || source.value.length === 0) {
|
|
2887
|
-
return { success: false, message: "
|
|
3423
|
+
return { success: false, message: t("tool.secret.needValue") };
|
|
2888
3424
|
}
|
|
2889
3425
|
const secret = setSecret(name, source.value);
|
|
2890
3426
|
return {
|
|
2891
3427
|
success: true,
|
|
2892
|
-
message:
|
|
3428
|
+
message: t("tool.secret.saved", { name: secret.name }),
|
|
2893
3429
|
secret,
|
|
2894
3430
|
};
|
|
2895
3431
|
}
|
|
@@ -2904,15 +3440,15 @@ export default Plugin.define({
|
|
|
2904
3440
|
try {
|
|
2905
3441
|
const name = ((input ?? {}).name ?? "").trim();
|
|
2906
3442
|
if (!name) {
|
|
2907
|
-
return { success: false, message: "
|
|
3443
|
+
return { success: false, message: t("tool.secret.needName") };
|
|
2908
3444
|
}
|
|
2909
3445
|
const existed = hasSecret(name);
|
|
2910
3446
|
deleteSecret(name);
|
|
2911
3447
|
return {
|
|
2912
3448
|
success: existed,
|
|
2913
3449
|
message: existed
|
|
2914
|
-
?
|
|
2915
|
-
:
|
|
3450
|
+
? t("tool.secret.deleted", { name })
|
|
3451
|
+
: t("tool.secret.notFound", { name }),
|
|
2916
3452
|
};
|
|
2917
3453
|
}
|
|
2918
3454
|
catch (err) {
|
|
@@ -2949,7 +3485,7 @@ export default Plugin.define({
|
|
|
2949
3485
|
if (!source?.name?.trim() || !source?.prompt?.trim()) {
|
|
2950
3486
|
return {
|
|
2951
3487
|
success: false,
|
|
2952
|
-
error: "
|
|
3488
|
+
error: t("tool.template.namePromptRequired"),
|
|
2953
3489
|
};
|
|
2954
3490
|
}
|
|
2955
3491
|
const template = await saveTemplate({
|
|
@@ -2976,7 +3512,7 @@ export default Plugin.define({
|
|
|
2976
3512
|
delete_template: async (input) => {
|
|
2977
3513
|
const { id } = input;
|
|
2978
3514
|
if (!id) {
|
|
2979
|
-
return { success: false, error: "
|
|
3515
|
+
return { success: false, error: t("tool.template.needId") };
|
|
2980
3516
|
}
|
|
2981
3517
|
try {
|
|
2982
3518
|
await deleteTemplate(id);
|
|
@@ -3006,14 +3542,14 @@ export default Plugin.define({
|
|
|
3006
3542
|
import_tasks: async (input) => {
|
|
3007
3543
|
const { data } = input;
|
|
3008
3544
|
if (!data) {
|
|
3009
|
-
return { success: false, error: "
|
|
3545
|
+
return { success: false, error: t("tool.transfer.noData") };
|
|
3010
3546
|
}
|
|
3011
3547
|
try {
|
|
3012
3548
|
const parsed = parseImportJson(data);
|
|
3013
3549
|
if (parsed.tasks.length === 0) {
|
|
3014
3550
|
return {
|
|
3015
3551
|
success: false,
|
|
3016
|
-
error: "
|
|
3552
|
+
error: t("tool.transfer.noTasksInFile"),
|
|
3017
3553
|
errors: parsed.errors,
|
|
3018
3554
|
};
|
|
3019
3555
|
}
|
|
@@ -3021,7 +3557,16 @@ export default Plugin.define({
|
|
|
3021
3557
|
const errors = [...parsed.errors];
|
|
3022
3558
|
for (const def of parsed.tasks) {
|
|
3023
3559
|
try {
|
|
3024
|
-
await schedulerCreateTask(def.name, def.schedule, def.prompt, def.timeoutSeconds, def.workingDirectory ?? def.workdir, def.retryCount, def.retryDelay, def.qualityGate, def.nextTaskOnSuccess, def.nextTaskOnError, def.triggerType, def.watchPath, def.dependsOn, def.model, def.priority, def.beforeScript, def.afterScript, def.mcpEvent, def.workspaceId, def.allowedTools, def.deniedTools, def.matrix, def.matrixParentId, "create", def.timezone, def.notBefore, def.notAfter, def.pausedUntil, def.runAt
|
|
3560
|
+
await schedulerCreateTask(def.name, def.schedule, def.prompt, def.timeoutSeconds, def.workingDirectory ?? def.workdir, def.retryCount, def.retryDelay, def.qualityGate, def.nextTaskOnSuccess, def.nextTaskOnError, def.triggerType, def.watchPath, def.dependsOn, def.model, def.priority, def.beforeScript, def.afterScript, def.mcpEvent, def.workspaceId, def.allowedTools, def.deniedTools, def.matrix, def.matrixParentId, "create", def.timezone, def.notBefore, def.notAfter, def.pausedUntil, def.runAt, def.session ?? "new", def.sessionId, def.sessionMaxRuns, {
|
|
3561
|
+
activeDays: def.activeDays,
|
|
3562
|
+
windowPolicy: def.windowPolicy,
|
|
3563
|
+
watchGlobs: def.watchGlobs,
|
|
3564
|
+
watchIgnore: def.watchIgnore,
|
|
3565
|
+
gitBranch: def.gitBranch,
|
|
3566
|
+
gitPaths: def.gitPaths,
|
|
3567
|
+
gitIgnore: def.gitIgnore,
|
|
3568
|
+
gitPollSeconds: def.gitPollSeconds,
|
|
3569
|
+
}, def.runWhenLoggedOff === true, def.paused === true);
|
|
3025
3570
|
await saveTaskDefinition(def);
|
|
3026
3571
|
imported.push(def.name);
|
|
3027
3572
|
}
|
|
@@ -3050,7 +3595,7 @@ export default Plugin.define({
|
|
|
3050
3595
|
// Повторный вызов не создаёт второй сервер — защита от двойного запуска
|
|
3051
3596
|
// реализована внутри startDashboardServer.
|
|
3052
3597
|
const dashboard = await startDashboardServer({
|
|
3053
|
-
getTasks: collectTasksView,
|
|
3598
|
+
getTasks: async () => (await collectTasksView()).tasks,
|
|
3054
3599
|
runTask: (name) => runTaskEntry(name),
|
|
3055
3600
|
deleteTask: async (name) => {
|
|
3056
3601
|
await deleteTaskWithFamily(name);
|
|
@@ -3085,7 +3630,7 @@ function resolveMatrixExtraConfig(name, matrix, ids) {
|
|
|
3085
3630
|
if (typeof matrix.concurrency !== "number" ||
|
|
3086
3631
|
!Number.isFinite(matrix.concurrency) ||
|
|
3087
3632
|
matrix.concurrency < 1) {
|
|
3088
|
-
throw new Error(
|
|
3633
|
+
throw new Error(t("tool.error.matrixConcurrency", { task: name }));
|
|
3089
3634
|
}
|
|
3090
3635
|
extra.concurrency = Math.floor(matrix.concurrency);
|
|
3091
3636
|
}
|
|
@@ -3095,8 +3640,10 @@ function resolveMatrixExtraConfig(name, matrix, ids) {
|
|
|
3095
3640
|
for (const [key, value] of Object.entries(matrix.overrides)) {
|
|
3096
3641
|
const workspaceKey = key.trim();
|
|
3097
3642
|
if (!allowed.has(workspaceKey)) {
|
|
3098
|
-
throw new Error(
|
|
3099
|
-
|
|
3643
|
+
throw new Error(t("tool.error.matrixOverride", {
|
|
3644
|
+
task: name,
|
|
3645
|
+
workspace: workspaceKey,
|
|
3646
|
+
}));
|
|
3100
3647
|
}
|
|
3101
3648
|
if (!value || typeof value !== "object")
|
|
3102
3649
|
continue;
|
|
@@ -3120,10 +3667,6 @@ function resolveMatrixExtraConfig(name, matrix, ids) {
|
|
|
3120
3667
|
}
|
|
3121
3668
|
return extra;
|
|
3122
3669
|
}
|
|
3123
|
-
/**
|
|
3124
|
-
* Общая логика создания задачи: используется и schedule_task (инструмент),
|
|
3125
|
-
* и create_task (RPC-метод для GUI).
|
|
3126
|
-
*/
|
|
3127
3670
|
async function schedulerCreateTask(name, schedule, prompt, timeoutSeconds, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, matrixParentId,
|
|
3128
3671
|
/** create — пересоздать клонов с нуля; sync — только diff (Спринт 17). */
|
|
3129
3672
|
matrixMode = "create",
|
|
@@ -3142,7 +3685,28 @@ session,
|
|
|
3142
3685
|
/** ID сессии для reuse (генерируется автоматически; пользователь не задаёт). */
|
|
3143
3686
|
sessionId,
|
|
3144
3687
|
/** Сколько запусков переживает reuse-сессия до ротации (0/undefined — без ограничения). */
|
|
3145
|
-
sessionMaxRuns
|
|
3688
|
+
sessionMaxRuns,
|
|
3689
|
+
/** Спринт 27: дни недели, политика окна, glob- и git-фильтры. */
|
|
3690
|
+
triggerExtras,
|
|
3691
|
+
/** Спринт 27.5.4: Windows — запускать без входа пользователя (/ru SYSTEM). */
|
|
3692
|
+
runWhenLoggedOff,
|
|
3693
|
+
/**
|
|
3694
|
+
* Спринт 27.5.8: пересоздать задачу сразу отключённой (пауза переживает
|
|
3695
|
+
* update). Для матрицы пауза применяется к клонам.
|
|
3696
|
+
*/
|
|
3697
|
+
paused) {
|
|
3698
|
+
// Спринт 27.5 (hotfix 1.5.1): проверяем имя до создания wrapper/prompt и записи
|
|
3699
|
+
// в БД. Недопустимые символы отклоняются с понятным сообщением, а не ошибкой
|
|
3700
|
+
// schtasks; имя нормализуется (trim) для всех путей: MCP, RPC и импорт.
|
|
3701
|
+
const normalizedName = name.trim();
|
|
3702
|
+
const nameError = validateTaskName(normalizedName);
|
|
3703
|
+
if (nameError) {
|
|
3704
|
+
throw new Error(nameError);
|
|
3705
|
+
}
|
|
3706
|
+
name = normalizedName;
|
|
3707
|
+
// Для отката файлов: при обновлении существующей задачи файлы переиспользуются,
|
|
3708
|
+
// удалять их при сбое нельзя — в БД остаётся прежнее определение.
|
|
3709
|
+
const definitionExisted = Boolean(getTask(normalizedName));
|
|
3146
3710
|
const normalizedModel = model?.trim() || undefined;
|
|
3147
3711
|
const normalizedPriority = normalizePriority(priority);
|
|
3148
3712
|
const normalizedBefore = beforeScript?.trim() || undefined;
|
|
@@ -3151,6 +3715,34 @@ sessionMaxRuns) {
|
|
|
3151
3715
|
const normalizedNotBefore = notBefore?.trim() || undefined;
|
|
3152
3716
|
const normalizedNotAfter = notAfter?.trim() || undefined;
|
|
3153
3717
|
const normalizedPausedUntil = pausedUntil?.trim() || undefined;
|
|
3718
|
+
// Спринт 27.5.4: true → задача работает без входа (Windows /ru SYSTEM).
|
|
3719
|
+
const normalizedRunWhenLoggedOff = runWhenLoggedOff === true ? true : undefined;
|
|
3720
|
+
// Спринт 27.5.8: пауза сохраняется при пересоздании задачи.
|
|
3721
|
+
const normalizedPaused = paused === true ? true : undefined;
|
|
3722
|
+
// Спринт 27: дни недели, политика окна и glob/git-фильтры.
|
|
3723
|
+
const normalizeGlobList = (raw) => {
|
|
3724
|
+
if (!Array.isArray(raw))
|
|
3725
|
+
return undefined;
|
|
3726
|
+
const cleaned = Array.from(new Set(raw
|
|
3727
|
+
.filter((item) => typeof item === "string")
|
|
3728
|
+
.map((item) => item.trim())
|
|
3729
|
+
.filter(Boolean)));
|
|
3730
|
+
return cleaned.length > 0 ? cleaned : undefined;
|
|
3731
|
+
};
|
|
3732
|
+
const normalizedActiveDays = normalizeActiveDays(triggerExtras?.activeDays);
|
|
3733
|
+
const normalizedWindowPolicy = triggerExtras?.windowPolicy === "skip" || triggerExtras?.windowPolicy === "run"
|
|
3734
|
+
? triggerExtras.windowPolicy
|
|
3735
|
+
: undefined;
|
|
3736
|
+
const normalizedWatchGlobs = normalizeGlobList(triggerExtras?.watchGlobs);
|
|
3737
|
+
const normalizedWatchIgnore = normalizeGlobList(triggerExtras?.watchIgnore);
|
|
3738
|
+
const normalizedGitBranch = triggerExtras?.gitBranch?.trim() || undefined;
|
|
3739
|
+
const normalizedGitPaths = normalizeGlobList(triggerExtras?.gitPaths);
|
|
3740
|
+
const normalizedGitIgnore = normalizeGlobList(triggerExtras?.gitIgnore);
|
|
3741
|
+
const normalizedGitPollSeconds = typeof triggerExtras?.gitPollSeconds === "number" &&
|
|
3742
|
+
Number.isFinite(triggerExtras.gitPollSeconds) &&
|
|
3743
|
+
triggerExtras.gitPollSeconds >= 5
|
|
3744
|
+
? Math.floor(triggerExtras.gitPollSeconds)
|
|
3745
|
+
: undefined;
|
|
3154
3746
|
const normalizedMcpEvent = mcpEvent && mcpEvent.event?.trim()
|
|
3155
3747
|
? {
|
|
3156
3748
|
server: mcpEvent.server?.trim() || "",
|
|
@@ -3165,7 +3757,7 @@ sessionMaxRuns) {
|
|
|
3165
3757
|
if (effectiveTriggerType === "once") {
|
|
3166
3758
|
const normalized = normalizeOneShotRunAt({ runAt });
|
|
3167
3759
|
if (!normalized.ok) {
|
|
3168
|
-
throw new Error(
|
|
3760
|
+
throw new Error(t("tool.error.taskReason", { name, error: normalized.error }));
|
|
3169
3761
|
}
|
|
3170
3762
|
effectiveRunAt = normalized.runAt;
|
|
3171
3763
|
}
|
|
@@ -3176,7 +3768,10 @@ sessionMaxRuns) {
|
|
|
3176
3768
|
if (session !== undefined) {
|
|
3177
3769
|
const normalizedSession = normalizeSessionMode(session);
|
|
3178
3770
|
if (!normalizedSession) {
|
|
3179
|
-
throw new Error(
|
|
3771
|
+
throw new Error(t("tool.error.sessionUnknown", {
|
|
3772
|
+
name,
|
|
3773
|
+
session: String(session),
|
|
3774
|
+
}));
|
|
3180
3775
|
}
|
|
3181
3776
|
effectiveSession = normalizedSession;
|
|
3182
3777
|
}
|
|
@@ -3197,7 +3792,7 @@ sessionMaxRuns) {
|
|
|
3197
3792
|
return cleaned.length > 0 ? cleaned : undefined;
|
|
3198
3793
|
};
|
|
3199
3794
|
if (Array.isArray(allowedTools) && allowedTools.filter((t) => typeof t === "string" && t.trim()).length === 0) {
|
|
3200
|
-
throw new Error(
|
|
3795
|
+
throw new Error(t("tool.error.allowedToolsEmpty", { task: name }));
|
|
3201
3796
|
}
|
|
3202
3797
|
const normalizedAllowedTools = normalizeToolList(allowedTools);
|
|
3203
3798
|
const normalizedDeniedTools = normalizeToolList(deniedTools);
|
|
@@ -3206,25 +3801,29 @@ sessionMaxRuns) {
|
|
|
3206
3801
|
let normalizedMatrix;
|
|
3207
3802
|
if (matrix) {
|
|
3208
3803
|
if (workspaceId?.trim()) {
|
|
3209
|
-
throw new Error(
|
|
3804
|
+
throw new Error(t("tool.error.workspaceIdConflict", { task: name }));
|
|
3210
3805
|
}
|
|
3211
3806
|
const ids = Array.from(new Set((Array.isArray(matrix.workspaceIds) ? matrix.workspaceIds : [])
|
|
3212
3807
|
.filter((id) => typeof id === "string")
|
|
3213
3808
|
.map((id) => id.trim())
|
|
3214
3809
|
.filter(Boolean)));
|
|
3215
3810
|
if (ids.length === 0) {
|
|
3216
|
-
throw new Error(
|
|
3811
|
+
throw new Error(t("tool.error.workspaceIdsEmpty", { task: name }));
|
|
3217
3812
|
}
|
|
3218
3813
|
for (const id of ids) {
|
|
3219
3814
|
const ws = getWorkspace(id);
|
|
3220
3815
|
if (!ws) {
|
|
3221
|
-
throw new Error(
|
|
3816
|
+
throw new Error(t("tool.error.workspaceMissing", { task: name, id }));
|
|
3222
3817
|
}
|
|
3223
3818
|
try {
|
|
3224
3819
|
validateWorkspacePath(ws.path);
|
|
3225
3820
|
}
|
|
3226
3821
|
catch {
|
|
3227
|
-
throw new Error(
|
|
3822
|
+
throw new Error(t("tool.error.workspaceUnavailable", {
|
|
3823
|
+
task: name,
|
|
3824
|
+
workspace: ws.name,
|
|
3825
|
+
path: ws.path,
|
|
3826
|
+
}));
|
|
3228
3827
|
}
|
|
3229
3828
|
}
|
|
3230
3829
|
normalizedMatrix = {
|
|
@@ -3243,7 +3842,19 @@ sessionMaxRuns) {
|
|
|
3243
3842
|
}
|
|
3244
3843
|
// MCP-триггер без имени события бессмыслен — валидируем до создания файлов.
|
|
3245
3844
|
if (effectiveTriggerType === "mcp-event" && !normalizedMcpEvent) {
|
|
3246
|
-
throw new Error("
|
|
3845
|
+
throw new Error(t("tool.error.mcpEventRequired"));
|
|
3846
|
+
}
|
|
3847
|
+
// Спринт 27: git-триггеру нужен git-репозиторий в рабочей директории.
|
|
3848
|
+
if (effectiveTriggerType === "git") {
|
|
3849
|
+
const gitCwd = workspaceId?.trim()
|
|
3850
|
+
? getWorkspace(workspaceId.trim())?.path
|
|
3851
|
+
: workingDirectory?.trim() || projectDirectory || process.cwd();
|
|
3852
|
+
if (!gitCwd) {
|
|
3853
|
+
throw new Error(t("tool.error.gitCwdRequired", { task: name }));
|
|
3854
|
+
}
|
|
3855
|
+
if (!readGitBranch(gitCwd)) {
|
|
3856
|
+
throw new Error(t("tool.error.gitNoRepo", { task: name, path: gitCwd }));
|
|
3857
|
+
}
|
|
3247
3858
|
}
|
|
3248
3859
|
// Валидируем cron-выражение до создания файлов. Для file/mcp-event
|
|
3249
3860
|
// расписание не используется вовсе.
|
|
@@ -3257,12 +3868,22 @@ sessionMaxRuns) {
|
|
|
3257
3868
|
throw new Error(err.message || String(err));
|
|
3258
3869
|
}
|
|
3259
3870
|
if (normalizedTz && !isValidIanaTimeZone(normalizedTz)) {
|
|
3260
|
-
throw new Error(
|
|
3261
|
-
|
|
3871
|
+
throw new Error(t("tool.error.timezone", {
|
|
3872
|
+
task: name,
|
|
3873
|
+
timezone: normalizedTz,
|
|
3874
|
+
}));
|
|
3875
|
+
}
|
|
3876
|
+
const windowError = validateLaunchWindow(normalizedNotBefore, normalizedNotAfter);
|
|
3877
|
+
if (windowError) {
|
|
3878
|
+
throw new Error(t("tool.error.window", { task: name, error: windowError }));
|
|
3262
3879
|
}
|
|
3880
|
+
}
|
|
3881
|
+
// Спринт 27: окно и дни недели применимы и к событийным триггерам
|
|
3882
|
+
// (file/git/mcp-event/once) — проверяем корректность до создания задачи.
|
|
3883
|
+
if (effectiveTriggerType !== "cron") {
|
|
3263
3884
|
const windowError = validateLaunchWindow(normalizedNotBefore, normalizedNotAfter);
|
|
3264
3885
|
if (windowError) {
|
|
3265
|
-
throw new Error(
|
|
3886
|
+
throw new Error(t("tool.error.window", { task: name, error: windowError }));
|
|
3266
3887
|
}
|
|
3267
3888
|
}
|
|
3268
3889
|
const sanitized = sanitizeName(name);
|
|
@@ -3271,7 +3892,7 @@ sessionMaxRuns) {
|
|
|
3271
3892
|
// Шлюз расписания (Спринт 19): нужен только для cron в poll-режиме
|
|
3272
3893
|
// (нестандартный cron или чужая IANA-зона) либо при окне запуска.
|
|
3273
3894
|
const gate = effectiveTriggerType === "cron"
|
|
3274
|
-
? buildScheduleGate(schedule, normalizedTz, normalizedNotBefore, normalizedNotAfter)
|
|
3895
|
+
? buildScheduleGate(schedule, normalizedTz, normalizedNotBefore, normalizedNotAfter, normalizedActiveDays, normalizedWindowPolicy)
|
|
3275
3896
|
: undefined;
|
|
3276
3897
|
const wrapperGate = gate
|
|
3277
3898
|
? {
|
|
@@ -3286,14 +3907,19 @@ sessionMaxRuns) {
|
|
|
3286
3907
|
const normalizedWorkspaceId = workspaceId?.trim() || undefined;
|
|
3287
3908
|
const workspace = normalizedWorkspaceId ? getWorkspace(normalizedWorkspaceId) : undefined;
|
|
3288
3909
|
if (normalizedWorkspaceId && !workspace) {
|
|
3289
|
-
throw new Error(
|
|
3910
|
+
throw new Error(t("tool.error.workspaceIdMissing", {
|
|
3911
|
+
id: normalizedWorkspaceId,
|
|
3912
|
+
}));
|
|
3290
3913
|
}
|
|
3291
3914
|
if (workspace) {
|
|
3292
3915
|
try {
|
|
3293
3916
|
validateWorkspacePath(workspace.path);
|
|
3294
3917
|
}
|
|
3295
3918
|
catch {
|
|
3296
|
-
throw new Error(
|
|
3919
|
+
throw new Error(t("tool.error.workspacePathMissing", {
|
|
3920
|
+
name: workspace.name,
|
|
3921
|
+
path: workspace.path,
|
|
3922
|
+
}));
|
|
3297
3923
|
}
|
|
3298
3924
|
if (workingDirectory?.trim() && workingDirectory.trim() !== workspace.path) {
|
|
3299
3925
|
console.warn(`[workspace] Задача "${name}": workingDirectory "${workingDirectory.trim()}" ` +
|
|
@@ -3314,7 +3940,9 @@ sessionMaxRuns) {
|
|
|
3314
3940
|
await fs.writeFile(logFile, "", "utf8");
|
|
3315
3941
|
}
|
|
3316
3942
|
catch (err) {
|
|
3317
|
-
throw new Error(
|
|
3943
|
+
throw new Error(t("tool.error.prepareFiles", {
|
|
3944
|
+
error: err.message || String(err),
|
|
3945
|
+
}));
|
|
3318
3946
|
}
|
|
3319
3947
|
// Обёртка зависит от платформы:
|
|
3320
3948
|
// - Windows: .cmd → PowerShell-скрипт (lock, таймаут, метрики);
|
|
@@ -3353,8 +3981,17 @@ sessionMaxRuns) {
|
|
|
3353
3981
|
}
|
|
3354
3982
|
}
|
|
3355
3983
|
catch (err) {
|
|
3356
|
-
throw new Error(
|
|
3984
|
+
throw new Error(t("tool.error.wrapper", {
|
|
3985
|
+
error: err.message || String(err),
|
|
3986
|
+
}));
|
|
3357
3987
|
}
|
|
3988
|
+
// 27.5.5.3: при сбое создания новой задачи убираем подготовленные файлы.
|
|
3989
|
+
// При обновлении файлы переиспользуются существующей задачей — не удаляем.
|
|
3990
|
+
const rollbackArtifacts = async () => {
|
|
3991
|
+
if (definitionExisted)
|
|
3992
|
+
return;
|
|
3993
|
+
await Promise.all([wrapperPath, promptFile, logFile, taskEnvFile].map((file) => file ? fs.unlink(file).catch(() => undefined) : Promise.resolve()));
|
|
3994
|
+
};
|
|
3358
3995
|
try {
|
|
3359
3996
|
// Бэкенд сам преобразует cron в родное расписание ОС.
|
|
3360
3997
|
await scheduler.createTask({
|
|
@@ -3371,11 +4008,47 @@ sessionMaxRuns) {
|
|
|
3371
4008
|
timezone: normalizedTz,
|
|
3372
4009
|
notBefore: normalizedNotBefore,
|
|
3373
4010
|
notAfter: normalizedNotAfter,
|
|
4011
|
+
runWhenLoggedOff: normalizedRunWhenLoggedOff,
|
|
3374
4012
|
});
|
|
3375
4013
|
}
|
|
3376
4014
|
catch (err) {
|
|
4015
|
+
await rollbackArtifacts();
|
|
3377
4016
|
throw new Error(err instanceof Error ? err.message : String(err));
|
|
3378
4017
|
}
|
|
4018
|
+
// Проверяем фактическое наличие задачи в планировщике: до 3 попыток с паузой
|
|
4019
|
+
// 200 мс. Это ловит случай, когда ОС/обёртка вернула код 0, но задачи нет.
|
|
4020
|
+
const isListed = (tasks) => tasks.some((task) => (task.taskName || "").trim().toLowerCase() === name.toLowerCase());
|
|
4021
|
+
let listedTasks;
|
|
4022
|
+
let verifyQueryError;
|
|
4023
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
4024
|
+
try {
|
|
4025
|
+
listedTasks = await scheduler.listTasks();
|
|
4026
|
+
if (isListed(listedTasks))
|
|
4027
|
+
break;
|
|
4028
|
+
}
|
|
4029
|
+
catch (err) {
|
|
4030
|
+
verifyQueryError = err;
|
|
4031
|
+
}
|
|
4032
|
+
if (attempt < 2) {
|
|
4033
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
4034
|
+
}
|
|
4035
|
+
}
|
|
4036
|
+
if (listedTasks && !isListed(listedTasks)) {
|
|
4037
|
+
await rollbackArtifacts();
|
|
4038
|
+
throw new Error(t("tool.error.schedulerNotConfirmed", {
|
|
4039
|
+
task: name,
|
|
4040
|
+
scheduler: scheduler.title,
|
|
4041
|
+
}) +
|
|
4042
|
+
" " +
|
|
4043
|
+
(definitionExisted
|
|
4044
|
+
? t("tool.error.schedulerKeptFiles")
|
|
4045
|
+
: t("tool.error.schedulerRemovedFiles")));
|
|
4046
|
+
}
|
|
4047
|
+
if (!listedTasks && verifyQueryError) {
|
|
4048
|
+
// Список получить не удалось — не удаляем возможно созданную задачу,
|
|
4049
|
+
// но явно предупреждаем: проверка наличия не выполнена.
|
|
4050
|
+
console.warn(`[windows-scheduler] Задача "${name}" создана, но проверить её в планировщике не удалось: ${verifyQueryError instanceof Error ? verifyQueryError.message : String(verifyQueryError)}`);
|
|
4051
|
+
}
|
|
3379
4052
|
// Сохраняем определение задачи для последующего экспорта/импорта.
|
|
3380
4053
|
// Определение до перезаписи: нужно и для очереди матрицы, и для счётчика сессии.
|
|
3381
4054
|
const previousDefinition = getTask(name);
|
|
@@ -3411,6 +4084,19 @@ sessionMaxRuns) {
|
|
|
3411
4084
|
timezone: normalizedTz,
|
|
3412
4085
|
notBefore: normalizedNotBefore,
|
|
3413
4086
|
notAfter: normalizedNotAfter,
|
|
4087
|
+
// Спринт 27.5.4: режим входа (Windows: /ru SYSTEM при true).
|
|
4088
|
+
runWhenLoggedOff: normalizedRunWhenLoggedOff,
|
|
4089
|
+
// Спринт 27.5.8: бессрочная пауза переживает пересоздание.
|
|
4090
|
+
paused: normalizedPaused,
|
|
4091
|
+
// Спринт 27: дни недели, политика окна, glob- и git-фильтры.
|
|
4092
|
+
activeDays: normalizedActiveDays,
|
|
4093
|
+
windowPolicy: normalizedWindowPolicy,
|
|
4094
|
+
watchGlobs: normalizedWatchGlobs,
|
|
4095
|
+
watchIgnore: normalizedWatchIgnore,
|
|
4096
|
+
gitBranch: normalizedGitBranch,
|
|
4097
|
+
gitPaths: normalizedGitPaths,
|
|
4098
|
+
gitIgnore: normalizedGitIgnore,
|
|
4099
|
+
gitPollSeconds: normalizedGitPollSeconds,
|
|
3414
4100
|
pausedUntil: normalizedPausedUntil,
|
|
3415
4101
|
allowedTools: normalizedAllowedTools,
|
|
3416
4102
|
deniedTools: normalizedDeniedTools,
|
|
@@ -3440,7 +4126,7 @@ sessionMaxRuns) {
|
|
|
3440
4126
|
// с нуля, а синхронизируются с новым определением; выполняющиеся — не трогаем.
|
|
3441
4127
|
if (normalizedMatrix) {
|
|
3442
4128
|
const createClone = async (clone) => {
|
|
3443
|
-
await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil);
|
|
4129
|
+
await schedulerCreateTask(clone.name, clone.schedule, clone.prompt, clone.timeoutSeconds, undefined, clone.retryCount, clone.retryDelay, clone.qualityGate, undefined, undefined, "file", undefined, undefined, clone.model, clone.priority, clone.beforeScript, clone.afterScript, undefined, clone.workspaceId, clone.allowedTools, clone.deniedTools, undefined, name, "create", clone.timezone, clone.notBefore, clone.notAfter, clone.pausedUntil, clone.runAt, clone.session, clone.sessionId, clone.sessionMaxRuns, undefined, clone.runWhenLoggedOff, clone.paused);
|
|
3444
4130
|
};
|
|
3445
4131
|
const removeChild = async (child) => {
|
|
3446
4132
|
try {
|
|
@@ -3455,6 +4141,8 @@ sessionMaxRuns) {
|
|
|
3455
4141
|
catch {
|
|
3456
4142
|
// Не критично.
|
|
3457
4143
|
}
|
|
4144
|
+
// Спринт 27.5.7: при откате прогона не оставляем и файлы клона.
|
|
4145
|
+
await removeTaskArtifacts(child);
|
|
3458
4146
|
};
|
|
3459
4147
|
// Создаёт/обновляет/удаляет matrix-complete по текущему определению.
|
|
3460
4148
|
const syncAggregator = async () => {
|
|
@@ -3467,8 +4155,10 @@ sessionMaxRuns) {
|
|
|
3467
4155
|
const cloneNames = listMatrixClones(name).map((clone) => clone.name);
|
|
3468
4156
|
if (cloneNames.length === 0)
|
|
3469
4157
|
return undefined;
|
|
3470
|
-
await schedulerCreateTask(aggregatorName, schedule,
|
|
3471
|
-
|
|
4158
|
+
await schedulerCreateTask(aggregatorName, schedule, t("tool.matrix.completed", {
|
|
4159
|
+
name,
|
|
4160
|
+
clones: cloneNames.join(", "),
|
|
4161
|
+
}), timeoutSeconds, undefined, undefined, undefined, undefined, undefined, undefined, "file", undefined, cloneNames, normalizedModel, normalizedPriority);
|
|
3472
4162
|
return aggregatorName;
|
|
3473
4163
|
};
|
|
3474
4164
|
if (matrixMode === "sync") {
|
|
@@ -3493,13 +4183,101 @@ sessionMaxRuns) {
|
|
|
3493
4183
|
for (const child of removeMatrixChildren(name)) {
|
|
3494
4184
|
await removeChild(child);
|
|
3495
4185
|
}
|
|
3496
|
-
|
|
3497
|
-
|
|
3498
|
-
|
|
4186
|
+
// Спринт 27.5.7: если клон не создался, откатываем весь прогон. Иначе
|
|
4187
|
+
// остаётся родитель с половиной клонов — он выглядит рабочим, но часть
|
|
4188
|
+
// workspace никогда не запускается. Ошибку expandMatrixTask (неизвестный
|
|
4189
|
+
// workspace) обрабатываем там же: родитель уже записан в БД.
|
|
4190
|
+
const createdInRun = [];
|
|
4191
|
+
try {
|
|
4192
|
+
const clones = expandMatrixTask(taskDefinition);
|
|
4193
|
+
for (const clone of clones) {
|
|
4194
|
+
try {
|
|
4195
|
+
await createClone(clone);
|
|
4196
|
+
createdInRun.push(clone.name);
|
|
4197
|
+
}
|
|
4198
|
+
catch (err) {
|
|
4199
|
+
const workspaceLabel = clone.workspaceId
|
|
4200
|
+
? getWorkspace(clone.workspaceId)?.name ?? clone.workspaceId
|
|
4201
|
+
: "без workspace";
|
|
4202
|
+
throw new Error(t("tool.error.matrixCloneFailed", {
|
|
4203
|
+
clone: clone.name,
|
|
4204
|
+
workspace: workspaceLabel,
|
|
4205
|
+
error: err instanceof Error ? err.message : String(err),
|
|
4206
|
+
}));
|
|
4207
|
+
}
|
|
4208
|
+
}
|
|
4209
|
+
await syncAggregator();
|
|
4210
|
+
}
|
|
4211
|
+
catch (err) {
|
|
4212
|
+
for (const child of [...createdInRun].reverse()) {
|
|
4213
|
+
await removeChild(child);
|
|
4214
|
+
}
|
|
4215
|
+
const aggregatorName = matrixCompleteName(name);
|
|
4216
|
+
if (getTask(aggregatorName)) {
|
|
4217
|
+
await removeChild(aggregatorName);
|
|
4218
|
+
}
|
|
4219
|
+
// Новая матрица: без клонов родитель бесполезен — убираем и его,
|
|
4220
|
+
// вместе с подготовленными файлами обёртки.
|
|
4221
|
+
if (!definitionExisted) {
|
|
4222
|
+
try {
|
|
4223
|
+
await scheduler.deleteTask(name);
|
|
4224
|
+
}
|
|
4225
|
+
catch {
|
|
4226
|
+
// Задачи могло не быть: бэкенд уже вернул ошибку.
|
|
4227
|
+
}
|
|
4228
|
+
try {
|
|
4229
|
+
await removeTaskDefinition(name);
|
|
4230
|
+
}
|
|
4231
|
+
catch {
|
|
4232
|
+
// Не критично: запись могла не сохраниться.
|
|
4233
|
+
}
|
|
4234
|
+
await rollbackArtifacts();
|
|
4235
|
+
}
|
|
4236
|
+
throw new Error(t("tool.error.matrixExpandRuntime", {
|
|
4237
|
+
name,
|
|
4238
|
+
error: err instanceof Error ? err.message : String(err),
|
|
4239
|
+
}));
|
|
3499
4240
|
}
|
|
3500
|
-
await syncAggregator();
|
|
3501
4241
|
}
|
|
3502
4242
|
}
|
|
4243
|
+
// Спринт 27.5.8: пересозданная задача должна остаться на паузе. У матрицы
|
|
4244
|
+
// пауза применяется к клонам — родитель сам никогда не выполняется.
|
|
4245
|
+
if (normalizedPaused) {
|
|
4246
|
+
const pauseTargets = normalizedMatrix
|
|
4247
|
+
? listMatrixClones(name).map((clone) => clone.name)
|
|
4248
|
+
: [name];
|
|
4249
|
+
for (const target of pauseTargets) {
|
|
4250
|
+
try {
|
|
4251
|
+
await scheduler.pauseTask(target);
|
|
4252
|
+
}
|
|
4253
|
+
catch (err) {
|
|
4254
|
+
console.warn(`[windows-scheduler] Задача "${target}": пауза не восстановлена после пересоздания: ${err instanceof Error ? err.message : String(err)}`);
|
|
4255
|
+
}
|
|
4256
|
+
}
|
|
4257
|
+
}
|
|
4258
|
+
}
|
|
4259
|
+
/**
|
|
4260
|
+
* Спринт 27.5.6: восстановление задачи из определения в БД.
|
|
4261
|
+
*
|
|
4262
|
+
* update_task пересоздаёт задачу в планировщике (delete + create). Раньше при
|
|
4263
|
+
* сбое create после успешного delete старая версия терялась навсегда: в ОС её
|
|
4264
|
+
* уже нет, а в БД лежит новое (не применённое) определение. Здесь мы заново
|
|
4265
|
+
* создаём задачу из прежнего определения — обёртка, промпт, расписание и
|
|
4266
|
+
* пауза восстанавливаются тем же путём, что и при обычном create.
|
|
4267
|
+
*/
|
|
4268
|
+
async function recreateTaskFromDefinition(definition) {
|
|
4269
|
+
const paused = Boolean(definition.paused === true ||
|
|
4270
|
+
(definition.pausedUntil && Date.parse(definition.pausedUntil) > Date.now()));
|
|
4271
|
+
await schedulerCreateTask(definition.name, definition.schedule ?? "", definition.prompt, definition.timeoutSeconds, definition.workingDirectory, definition.retryCount, definition.retryDelay, definition.qualityGate, definition.nextTaskOnSuccess, definition.nextTaskOnError, definition.triggerType ?? "cron", definition.watchPath, Array.isArray(definition.dependsOn) ? definition.dependsOn : undefined, definition.model, definition.priority, definition.beforeScript, definition.afterScript, definition.mcpEvent, definition.workspaceId, definition.allowedTools, definition.deniedTools, definition.matrix, definition.matrixParentId, "create", definition.timezone, definition.notBefore, definition.notAfter, definition.pausedUntil, definition.runAt, definition.session ?? "new", definition.sessionId, definition.sessionMaxRuns, {
|
|
4272
|
+
activeDays: definition.activeDays,
|
|
4273
|
+
windowPolicy: definition.windowPolicy,
|
|
4274
|
+
watchGlobs: definition.watchGlobs,
|
|
4275
|
+
watchIgnore: definition.watchIgnore,
|
|
4276
|
+
gitBranch: definition.gitBranch,
|
|
4277
|
+
gitPaths: definition.gitPaths,
|
|
4278
|
+
gitIgnore: definition.gitIgnore,
|
|
4279
|
+
gitPollSeconds: definition.gitPollSeconds,
|
|
4280
|
+
}, definition.runWhenLoggedOff, paused);
|
|
3503
4281
|
}
|
|
3504
4282
|
/**
|
|
3505
4283
|
* Запуск задачи «как есть», но с учётом матрицы: родитель раскладывается
|
|
@@ -3528,18 +4306,51 @@ async function runTaskEntry(name) {
|
|
|
3528
4306
|
throw err;
|
|
3529
4307
|
}
|
|
3530
4308
|
}
|
|
4309
|
+
/**
|
|
4310
|
+
* Спринт 27.5.3: чтение задач ОС с одним повтором.
|
|
4311
|
+
*
|
|
4312
|
+
* Сразу после мутации (create/delete/pause/resume) `schtasks /query` иногда
|
|
4313
|
+
* отдаёт пустой список, хотя в БД задачи уже есть, или падает. Один короткий
|
|
4314
|
+
* retry убирает ложный «задач нет»; если ОС так и не ответила осмысленно —
|
|
4315
|
+
* возвращаем `osAvailable: false`, и вызывающий код показывает состояние БД.
|
|
4316
|
+
*/
|
|
4317
|
+
async function readOsTasksWithRetry(expectNonEmpty, delayMs = 300) {
|
|
4318
|
+
let lastError;
|
|
4319
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
4320
|
+
if (attempt > 0) {
|
|
4321
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
4322
|
+
}
|
|
4323
|
+
try {
|
|
4324
|
+
const tasks = await scheduler.listTasks();
|
|
4325
|
+
if (tasks.length > 0 || !expectNonEmpty) {
|
|
4326
|
+
return { tasks, osAvailable: true };
|
|
4327
|
+
}
|
|
4328
|
+
lastError = "планировщик ОС вернул пустой список, хотя в БД есть задачи";
|
|
4329
|
+
}
|
|
4330
|
+
catch (err) {
|
|
4331
|
+
lastError = err instanceof Error ? err.message : String(err);
|
|
4332
|
+
}
|
|
4333
|
+
}
|
|
4334
|
+
return { tasks: [], osAvailable: false, osError: lastError };
|
|
4335
|
+
}
|
|
3531
4336
|
/**
|
|
3532
4337
|
* Собирает задачи плагина в формате, который отдают оба потребителя:
|
|
3533
4338
|
* RPC get_tasks (GUI) и инструмент list_tasks (агент).
|
|
4339
|
+
*
|
|
4340
|
+
* Спринт 27.5.3: возвращает также состояние чтения ОС. Если ОС недоступна,
|
|
4341
|
+
* `tasks` — состояние из БД (задачи помечены `orphaned: true`), а не пустой
|
|
4342
|
+
* массив: иначе GUI и агент решали бы, что задач нет.
|
|
3534
4343
|
*/
|
|
3535
4344
|
async function collectTasksView() {
|
|
3536
|
-
const
|
|
4345
|
+
const defs = await loadTaskDefinitions();
|
|
4346
|
+
const osRead = await readOsTasksWithRetry(defs.length > 0);
|
|
4347
|
+
const tasks = osRead.tasks;
|
|
3537
4348
|
// Читаем историю один раз, чтобы определить финальный статус по последней записи.
|
|
3538
4349
|
const history = await loadHistory();
|
|
3539
4350
|
// loadHistory() отдаёт записи от новых к старым; helper оставляет самую свежую.
|
|
3540
4351
|
const lastByTask = latestHistoryByTask(history);
|
|
3541
|
-
//
|
|
3542
|
-
|
|
4352
|
+
// Определения задач читаются один раз заранее (см. выше) — расписание,
|
|
4353
|
+
// повторы, цепочки, директория.
|
|
3543
4354
|
const workspaces = listWorkspaces();
|
|
3544
4355
|
const workspaceById = new Map(workspaces.map((workspace) => [workspace.id, workspace]));
|
|
3545
4356
|
// Счётчики запусков по задачам. Основной источник — таблица metrics
|
|
@@ -3579,7 +4390,7 @@ async function collectTasksView() {
|
|
|
3579
4390
|
orphaned: true,
|
|
3580
4391
|
})),
|
|
3581
4392
|
];
|
|
3582
|
-
|
|
4393
|
+
const view = sources.map(({ task: t, orphaned }) => {
|
|
3583
4394
|
// Все бэкенды возвращают короткие имена (без папки планировщика).
|
|
3584
4395
|
const name = t.taskName || "";
|
|
3585
4396
|
// Приоритет 1: статус, который сообщает планировщик ОС.
|
|
@@ -3619,6 +4430,13 @@ async function collectTasksView() {
|
|
|
3619
4430
|
error: 0,
|
|
3620
4431
|
partial: 0,
|
|
3621
4432
|
};
|
|
4433
|
+
// Спринт 27.5.2: пауза учитывает и флаг ОС, и активный pausedUntil.
|
|
4434
|
+
// nextRun считаем из определения — schtasks после мутации отдаёт
|
|
4435
|
+
// nextRunTime с задержкой, из-за чего API показывал null после resume.
|
|
4436
|
+
const pausedUntil = def?.pausedUntil ?? null;
|
|
4437
|
+
const paused = Boolean(t.paused) ||
|
|
4438
|
+
def?.paused === true ||
|
|
4439
|
+
Boolean(pausedUntil && Date.parse(pausedUntil) > Date.now());
|
|
3622
4440
|
return {
|
|
3623
4441
|
name,
|
|
3624
4442
|
schedule: def?.schedule ?? "",
|
|
@@ -3627,15 +4445,15 @@ async function collectTasksView() {
|
|
|
3627
4445
|
// Спринт 24 (фикс): явный признак паузы. Раньше GUI пытался вывести его
|
|
3628
4446
|
// из текстового статуса, но mapStatus() превращает "disabled" в "unknown",
|
|
3629
4447
|
// поэтому кнопка «возобновить» была недоступна.
|
|
3630
|
-
paused
|
|
4448
|
+
paused,
|
|
3631
4449
|
runsTotal: counts.total,
|
|
3632
4450
|
runsSuccess: counts.success,
|
|
3633
4451
|
runsError: counts.error,
|
|
3634
4452
|
runsPartial: counts.partial,
|
|
3635
|
-
|
|
3636
|
-
|
|
3637
|
-
|
|
3638
|
-
|
|
4453
|
+
nextRun: paused
|
|
4454
|
+
? null
|
|
4455
|
+
: computeTaskNextRun(def) ??
|
|
4456
|
+
(t.nextRunTime ? String(t.nextRunTime) : null),
|
|
3639
4457
|
runAt: def?.runAt ?? null,
|
|
3640
4458
|
session: def?.session ?? "new",
|
|
3641
4459
|
sessionId: def?.sessionId ?? null,
|
|
@@ -3658,6 +4476,10 @@ async function collectTasksView() {
|
|
|
3658
4476
|
notBefore: def?.notBefore ?? null,
|
|
3659
4477
|
notAfter: def?.notAfter ?? null,
|
|
3660
4478
|
pausedUntil: def?.pausedUntil ?? null,
|
|
4479
|
+
// Спринт 27.5.4: режим входа — из ОС (Interactive/Background) и из
|
|
4480
|
+
// определения (запуск без входа через /ru SYSTEM).
|
|
4481
|
+
logonMode: t.logonMode ?? null,
|
|
4482
|
+
runWhenLoggedOff: Boolean(def?.runWhenLoggedOff),
|
|
3661
4483
|
workingDirectory: workspace?.path ?? def?.workingDirectory ?? def?.workdir ?? null,
|
|
3662
4484
|
workspaceId: workspace?.id ?? def?.workspaceId ?? null,
|
|
3663
4485
|
workspaceName: workspace?.name ?? null,
|
|
@@ -3680,6 +4502,7 @@ async function collectTasksView() {
|
|
|
3680
4502
|
prompt: def?.prompt ?? "",
|
|
3681
4503
|
};
|
|
3682
4504
|
});
|
|
4505
|
+
return { tasks: view, osAvailable: osRead.osAvailable, osError: osRead.osError };
|
|
3683
4506
|
}
|
|
3684
4507
|
/**
|
|
3685
4508
|
* Проверяет фильтр MCP-события.
|