opencode-windows-scheduler 1.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +58 -7
- package/README.md +14 -4
- package/README.ru.md +14 -4
- package/ROADMAP.md +30 -20
- package/dist/core/analytics.d.ts +129 -0
- package/dist/core/analytics.d.ts.map +1 -0
- package/dist/core/analytics.js +286 -0
- package/dist/core/dry-run.d.ts +13 -0
- package/dist/core/dry-run.d.ts.map +1 -1
- package/dist/core/dry-run.js +30 -0
- package/dist/core/matrix.d.ts.map +1 -1
- package/dist/core/matrix.js +10 -0
- package/dist/core/ps-wrapper.d.ts +32 -2
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +101 -3
- package/dist/core/retention.d.ts +29 -0
- package/dist/core/retention.d.ts.map +1 -0
- package/dist/core/retention.js +98 -0
- package/dist/core/schedule-gate.d.ts +2 -0
- package/dist/core/schedule-gate.d.ts.map +1 -0
- package/dist/core/schedule-gate.js +182 -0
- package/dist/core/schedule-v2.d.ts +88 -0
- package/dist/core/schedule-v2.d.ts.map +1 -0
- package/dist/core/schedule-v2.js +496 -0
- package/dist/core/scheduler/types.d.ts +15 -0
- package/dist/core/scheduler/types.d.ts.map +1 -1
- package/dist/core/scheduler/windows.d.ts.map +1 -1
- package/dist/core/scheduler/windows.js +13 -1
- package/dist/core/wrappers/bash.d.ts +15 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +44 -1
- package/dist/db/history-repo.d.ts +41 -0
- package/dist/db/history-repo.d.ts.map +1 -1
- package/dist/db/history-repo.js +78 -0
- package/dist/db/schema.d.ts +1 -1
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +11 -0
- package/dist/index.d.ts +117 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1094 -56
- package/dist/notifications.d.ts +112 -6
- package/dist/notifications.d.ts.map +1 -1
- package/dist/notifications.js +396 -34
- package/dist/profiles.d.ts +60 -0
- package/dist/profiles.d.ts.map +1 -0
- package/dist/profiles.js +209 -0
- package/dist/rpc.d.ts +645 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +251 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +200 -7
- package/dist/settings.d.ts +80 -0
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +159 -8
- package/dist/task-transfer.d.ts +13 -0
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +26 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +3 -11
- package/dist/version.d.ts +8 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +27 -0
- package/dist/workspaces.d.ts +43 -0
- package/dist/workspaces.d.ts.map +1 -1
- package/dist/workspaces.js +174 -8
- package/docs/ARCHITECTURE.md +45 -13
- package/docs/FEATURES.md +103 -12
- package/gui-experimental.cjs +4 -2
- package/package.json +8 -2
- package/src/core/analytics.ts +414 -0
- package/src/core/dry-run.ts +42 -0
- package/src/core/matrix.ts +10 -0
- package/src/core/ps-wrapper.ts +117 -3
- package/src/core/retention.ts +141 -0
- package/src/core/schedule-gate.ts +213 -0
- package/src/core/schedule-v2.ts +533 -0
- package/src/core/scheduler/types.ts +15 -0
- package/src/core/scheduler/windows.ts +13 -1
- package/src/core/wrappers/bash.ts +60 -0
- package/src/db/history-repo.ts +116 -0
- package/src/db/schema.ts +14 -0
- package/src/gui.tsx +3613 -2725
- package/src/index.ts +1325 -55
- package/src/notifications.ts +516 -40
- package/src/profiles.ts +236 -0
- package/src/rpc.ts +267 -2
- package/src/server.ts +226 -7
- package/src/settings.ts +285 -9
- package/src/task-transfer.ts +44 -0
- package/src/types.ts +3 -13
- package/src/version.ts +27 -0
- package/src/workspaces.ts +214 -8
- package/dist/gui-experimental.cjs +0 -1
package/src/index.ts
CHANGED
|
@@ -7,8 +7,8 @@ import fs from "node:fs/promises";
|
|
|
7
7
|
import path from "node:path";
|
|
8
8
|
import { LockManager } from "./core/lock.js";
|
|
9
9
|
import { LOCK_DIR, LOG_DIR, PLUGIN_DIR, sanitizeName } from "./types.js";
|
|
10
|
-
import {
|
|
11
|
-
import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath } from "./core/ps-wrapper.js";
|
|
10
|
+
import { parseCron, buildScheduleGate, isValidIanaTimeZone, validateLaunchWindow, prevRun } from "./core/schedule-v2.js";
|
|
11
|
+
import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath, requestImmediateRun } from "./core/ps-wrapper.js";
|
|
12
12
|
import { getSchedulerBackend } from "./core/scheduler/index.js";
|
|
13
13
|
import { SCHEDULER_SKILL_ID, loadSchedulerSkill } from "./skill.js";
|
|
14
14
|
import { getTaskLogs } from "./core/scheduler/logs.js";
|
|
@@ -29,8 +29,18 @@ import {
|
|
|
29
29
|
import { SchedulerRpc } from "./rpc.js";
|
|
30
30
|
import { loadHistory, loadMetrics } from "./history.js";
|
|
31
31
|
import { loadSettings, saveSettings } from "./settings.js";
|
|
32
|
-
import type { NotificationSettings } from "./settings.js";
|
|
33
|
-
import {
|
|
32
|
+
import type { HistorySettings, NotificationSettings } from "./settings.js";
|
|
33
|
+
import { runHistoryRetention, maybeRunHistoryRetention } from "./core/retention.js";
|
|
34
|
+
import { buildAnalytics } from "./core/analytics.js";
|
|
35
|
+
import { getHistory, listRunningRecords } from "./db/history-repo.js";
|
|
36
|
+
import { getAllMetrics } from "./db/metrics-repo.js";
|
|
37
|
+
import {
|
|
38
|
+
findStuckMatrixClones,
|
|
39
|
+
maybeSendDigest,
|
|
40
|
+
notifyStuckMatrix,
|
|
41
|
+
sendDigestNow,
|
|
42
|
+
sendTestNotification,
|
|
43
|
+
} from "./notifications.js";
|
|
34
44
|
import {
|
|
35
45
|
loadTaskDefinitions,
|
|
36
46
|
saveTaskDefinition,
|
|
@@ -49,10 +59,21 @@ import type {
|
|
|
49
59
|
import { loadTemplates, saveTemplate, deleteTemplate } from "./templates.js";
|
|
50
60
|
import type { TaskTemplate } from "./templates.js";
|
|
51
61
|
import { startDashboardServer, closeDashboardServer, getDashboardPort } from "./server.js";
|
|
62
|
+
import {
|
|
63
|
+
DEFAULT_PROFILE,
|
|
64
|
+
createProfile,
|
|
65
|
+
deleteProfile,
|
|
66
|
+
getProfileDir,
|
|
67
|
+
getProfileName,
|
|
68
|
+
isProfilePinnedByEnv,
|
|
69
|
+
listProfiles,
|
|
70
|
+
sanitizeProfileName,
|
|
71
|
+
setActiveProfile,
|
|
72
|
+
} from "./profiles.js";
|
|
52
73
|
import { closeDb, initDb } from "./db/index.js";
|
|
53
74
|
import { migrateJsonToDb } from "./db/migrate.js";
|
|
54
75
|
import { checkJsonBackups, recoverInterruptedRuns } from "./db/recovery.js";
|
|
55
|
-
import { getTask, listMatrixClones } from "./db/tasks-repo.js";
|
|
76
|
+
import { getTask, listMatrixClones, saveTask } from "./db/tasks-repo.js";
|
|
56
77
|
import {
|
|
57
78
|
addWorkspace,
|
|
58
79
|
deleteWorkspace,
|
|
@@ -61,6 +82,8 @@ import {
|
|
|
61
82
|
updateWorkspace,
|
|
62
83
|
validateWorkspacePath,
|
|
63
84
|
readGitBranch,
|
|
85
|
+
writeWorkspaceEnvFile,
|
|
86
|
+
maskEnvForLog,
|
|
64
87
|
} from "./workspaces.js";
|
|
65
88
|
|
|
66
89
|
// Путь к вспомогательному node-скрипту записи истории/метрик (dist/core/record-history.js).
|
|
@@ -85,6 +108,24 @@ const recorderPath = (() => {
|
|
|
85
108
|
return distPath;
|
|
86
109
|
})();
|
|
87
110
|
|
|
111
|
+
/**
|
|
112
|
+
* Путь к гейту расписания (dist/core/schedule-gate.js). Обёртка запускает его
|
|
113
|
+
* перед opencode и выходит, если cron не сработал или запуск перенесён.
|
|
114
|
+
*/
|
|
115
|
+
const gatePath = (() => {
|
|
116
|
+
const resolved = require.resolve("./core/schedule-gate.js");
|
|
117
|
+
if (!resolved.endsWith(".ts")) return resolved;
|
|
118
|
+
const distPath = resolved
|
|
119
|
+
.replace(/([\\/])src([\\/])/, "$1dist$2")
|
|
120
|
+
.replace(/\.ts$/, ".js");
|
|
121
|
+
if (existsSync(distPath)) return distPath;
|
|
122
|
+
console.warn(
|
|
123
|
+
"[windows-scheduler] Не найден собранный schedule-gate.js: " +
|
|
124
|
+
`${distPath}. Гейт расписания не будет проверяться. Выполните npm run build.`
|
|
125
|
+
);
|
|
126
|
+
return distPath;
|
|
127
|
+
})();
|
|
128
|
+
|
|
88
129
|
/** Бэкенд планировщика текущей ОС (schtasks / crontab / launchd). */
|
|
89
130
|
const scheduler = getSchedulerBackend();
|
|
90
131
|
|
|
@@ -146,8 +187,24 @@ export const scheduleTaskSchema = z.object({
|
|
|
146
187
|
schedule: z
|
|
147
188
|
.string()
|
|
148
189
|
.describe(
|
|
149
|
-
"
|
|
190
|
+
"Cron expression (5 fields: minute hour day-of-month month day-of-week). Supports ranges, lists, */N steps, month/weekday names, @every 15m|2h|1d, L (last day of month) and FRI#3 (third Friday). Expressions schtasks cannot express are checked every minute inside the wrapper."
|
|
191
|
+
),
|
|
192
|
+
timezone: z
|
|
193
|
+
.string()
|
|
194
|
+
.optional()
|
|
195
|
+
.describe(
|
|
196
|
+
"IANA timezone of the schedule, e.g. Europe/Moscow. Defaults to the system timezone. A zone different from the system one is evaluated by the wrapper (poll mode)."
|
|
150
197
|
),
|
|
198
|
+
notBefore: z
|
|
199
|
+
.string()
|
|
200
|
+
.optional()
|
|
201
|
+
.describe(
|
|
202
|
+
"Launch window start in HH:MM (24h). Together with notAfter: a run outside the window is postponed to the next window opening, not skipped."
|
|
203
|
+
),
|
|
204
|
+
notAfter: z
|
|
205
|
+
.string()
|
|
206
|
+
.optional()
|
|
207
|
+
.describe("Launch window end in HH:MM (24h). May be earlier than notBefore (window crosses midnight)."),
|
|
151
208
|
prompt: z
|
|
152
209
|
.string()
|
|
153
210
|
.describe("Prompt passed to the agent on every run."),
|
|
@@ -219,6 +276,12 @@ export const scheduleTaskSchema = z.object({
|
|
|
219
276
|
.describe(
|
|
220
277
|
"MCP event trigger: server, event name and an optional filter (key=value or regex)."
|
|
221
278
|
),
|
|
279
|
+
watchPath: z
|
|
280
|
+
.string()
|
|
281
|
+
.optional()
|
|
282
|
+
.describe(
|
|
283
|
+
"File or directory to watch when triggerType is \"file\". Can be set here or later via update_task."
|
|
284
|
+
),
|
|
222
285
|
workingDirectory: z
|
|
223
286
|
.string()
|
|
224
287
|
.optional()
|
|
@@ -265,7 +328,19 @@ export const updateTaskSchema = z.object({
|
|
|
265
328
|
schedule: z
|
|
266
329
|
.string()
|
|
267
330
|
.optional()
|
|
268
|
-
.describe("New
|
|
331
|
+
.describe("New cron expression. Keeps the current value when omitted."),
|
|
332
|
+
timezone: z
|
|
333
|
+
.string()
|
|
334
|
+
.optional()
|
|
335
|
+
.describe("New IANA timezone. Empty string clears it (system timezone)."),
|
|
336
|
+
notBefore: z
|
|
337
|
+
.string()
|
|
338
|
+
.optional()
|
|
339
|
+
.describe("New launch window start HH:MM. Empty string clears the window."),
|
|
340
|
+
notAfter: z
|
|
341
|
+
.string()
|
|
342
|
+
.optional()
|
|
343
|
+
.describe("New launch window end HH:MM. Empty string clears the window."),
|
|
269
344
|
prompt: z
|
|
270
345
|
.string()
|
|
271
346
|
.optional()
|
|
@@ -344,6 +419,12 @@ export const updateTaskSchema = z.object({
|
|
|
344
419
|
|
|
345
420
|
const pauseTaskSchema = z.object({
|
|
346
421
|
name: z.string().describe("Task name to pause."),
|
|
422
|
+
until: z
|
|
423
|
+
.string()
|
|
424
|
+
.optional()
|
|
425
|
+
.describe(
|
|
426
|
+
"Optional ISO date/time to resume automatically (e.g. 2026-12-01T09:00:00Z). The plugin re-enables the task at that moment."
|
|
427
|
+
),
|
|
347
428
|
});
|
|
348
429
|
|
|
349
430
|
const resumeTaskSchema = z.object({
|
|
@@ -390,18 +471,167 @@ const manageWorkspacesSchema = z.object({
|
|
|
390
471
|
name: z.string().optional().describe("Workspace display name (add/update)."),
|
|
391
472
|
path: z.string().optional().describe("Absolute workspace path (add/update)."),
|
|
392
473
|
color: z.string().optional().describe("Marker color, e.g. #4f8cff (add/update)."),
|
|
474
|
+
env: z
|
|
475
|
+
.record(z.string(), z.string())
|
|
476
|
+
.nullable()
|
|
477
|
+
.optional()
|
|
478
|
+
.describe(
|
|
479
|
+
"Env-переменные workspace (ключ → значение). Переопределяют значения из envFile; секреты маскируются в логах (add/update)."
|
|
480
|
+
),
|
|
481
|
+
envFile: z
|
|
482
|
+
.string()
|
|
483
|
+
.nullable()
|
|
484
|
+
.optional()
|
|
485
|
+
.describe("Путь к .env-файлу workspace (add/update, null — очистить)."),
|
|
393
486
|
});
|
|
394
487
|
|
|
395
488
|
export const matrixControlSchema = z.object({
|
|
396
489
|
action: z
|
|
397
|
-
.enum(["results", "cancel", "cleanup"])
|
|
490
|
+
.enum(["results", "cancel", "cleanup", "preview"])
|
|
398
491
|
.describe(
|
|
399
|
-
"results — aggregate status of a matrix; cancel — cancel pending clones; cleanup — delete orphaned clones and aggregators."
|
|
492
|
+
"results — aggregate status of a matrix; cancel — cancel pending clones; cleanup — delete orphaned clones and aggregators; preview — dry-expand a matrix config into clone names without creating anything."
|
|
400
493
|
),
|
|
401
494
|
name: z
|
|
402
495
|
.string()
|
|
403
496
|
.optional()
|
|
404
|
-
.describe("Matrix parent name (required for results and cancel)."),
|
|
497
|
+
.describe("Matrix parent name (required for results and cancel; used as clone prefix for preview)."),
|
|
498
|
+
workspaceIds: z
|
|
499
|
+
.array(z.string())
|
|
500
|
+
.optional()
|
|
501
|
+
.describe("Preview only: workspace ids to fan out to (omit for every workspace)."),
|
|
502
|
+
strategy: z
|
|
503
|
+
.enum(["parallel", "sequential"])
|
|
504
|
+
.optional()
|
|
505
|
+
.describe("Preview only: clone execution strategy."),
|
|
506
|
+
failureMode: z
|
|
507
|
+
.enum(["continue", "stop"])
|
|
508
|
+
.optional()
|
|
509
|
+
.describe("Preview only: what to do when one clone fails."),
|
|
510
|
+
aggregation: z
|
|
511
|
+
.enum(["summary", "per-task"])
|
|
512
|
+
.optional()
|
|
513
|
+
.describe("Preview only: how clone results are aggregated."),
|
|
514
|
+
});
|
|
515
|
+
|
|
516
|
+
/** get_metrics — общая статистика запусков. */
|
|
517
|
+
export const getMetricsSchema = z.object({});
|
|
518
|
+
|
|
519
|
+
/** get_analytics — аналитика за период. */
|
|
520
|
+
export const getAnalyticsSchema = z.object({
|
|
521
|
+
days: z
|
|
522
|
+
.number()
|
|
523
|
+
.int()
|
|
524
|
+
.min(1)
|
|
525
|
+
.max(365)
|
|
526
|
+
.optional()
|
|
527
|
+
.describe("Analysis window in days (default 14)."),
|
|
528
|
+
topLimit: z
|
|
529
|
+
.number()
|
|
530
|
+
.int()
|
|
531
|
+
.min(1)
|
|
532
|
+
.max(50)
|
|
533
|
+
.optional()
|
|
534
|
+
.describe("How many top tasks to include (default 10)."),
|
|
535
|
+
});
|
|
536
|
+
|
|
537
|
+
/** manage_settings — глобальные настройки планировщика. */
|
|
538
|
+
export const manageSettingsSchema = z.object({
|
|
539
|
+
action: z
|
|
540
|
+
.enum(["get", "update"])
|
|
541
|
+
.describe("get — current settings; update — merge the provided fields and save."),
|
|
542
|
+
maxConcurrent: z
|
|
543
|
+
.number()
|
|
544
|
+
.int()
|
|
545
|
+
.min(1)
|
|
546
|
+
.max(16)
|
|
547
|
+
.optional()
|
|
548
|
+
.describe("How many task runs may execute at the same time."),
|
|
549
|
+
winterMode: z
|
|
550
|
+
.boolean()
|
|
551
|
+
.optional()
|
|
552
|
+
.describe("Winter mode: gentler scheduling of deferred runs."),
|
|
553
|
+
notifications: z
|
|
554
|
+
.any()
|
|
555
|
+
.optional()
|
|
556
|
+
.describe("Notification settings patch (enabled, onlyOnError, webhook, templates, filters, matrix, digest)."),
|
|
557
|
+
history: z
|
|
558
|
+
.object({
|
|
559
|
+
retentionDays: z.number().int().min(1).max(3650).optional(),
|
|
560
|
+
maxRecords: z.number().int().min(100).max(1000000).optional(),
|
|
561
|
+
})
|
|
562
|
+
.optional()
|
|
563
|
+
.describe("History retention policy."),
|
|
564
|
+
});
|
|
565
|
+
|
|
566
|
+
/** manage_templates — пользовательские шаблоны задач. */
|
|
567
|
+
export const manageTemplatesSchema = z.object({
|
|
568
|
+
action: z
|
|
569
|
+
.enum(["list", "save", "delete"])
|
|
570
|
+
.describe("list — all templates; save — create or update (id omitted = create); delete — remove by id."),
|
|
571
|
+
id: z.string().optional().describe("Template id for update/delete."),
|
|
572
|
+
name: z.string().optional().describe("Template name."),
|
|
573
|
+
prompt: z.string().optional().describe("Prompt text stored in the template."),
|
|
574
|
+
schedule: z.string().optional().describe("Cron expression."),
|
|
575
|
+
timeoutSeconds: z.number().int().positive().optional(),
|
|
576
|
+
model: z.string().optional(),
|
|
577
|
+
priority: z.number().int().min(0).max(10).optional(),
|
|
578
|
+
retryCount: z.number().int().min(0).optional(),
|
|
579
|
+
retryDelay: z.number().int().min(0).optional(),
|
|
580
|
+
qualityGate: z.string().optional(),
|
|
581
|
+
beforeScript: z.string().optional(),
|
|
582
|
+
afterScript: z.string().optional(),
|
|
583
|
+
nextTaskOnSuccess: z.string().optional(),
|
|
584
|
+
nextTaskOnError: z.string().optional(),
|
|
585
|
+
dependsOn: z.array(z.string()).optional(),
|
|
586
|
+
triggerType: z.enum(["cron", "file", "mcp-event"]).optional(),
|
|
587
|
+
mcpEvent: z
|
|
588
|
+
.object({
|
|
589
|
+
server: z.string(),
|
|
590
|
+
event: z.string(),
|
|
591
|
+
filter: z.string().optional(),
|
|
592
|
+
})
|
|
593
|
+
.optional(),
|
|
594
|
+
watchPath: z.string().optional(),
|
|
595
|
+
workingDirectory: z.string().optional(),
|
|
596
|
+
allowedTools: z.array(z.string()).optional(),
|
|
597
|
+
deniedTools: z.array(z.string()).optional(),
|
|
598
|
+
});
|
|
599
|
+
|
|
600
|
+
/** manage_profiles — изолированные профили планировщика. */
|
|
601
|
+
export const manageProfilesSchema = z.object({
|
|
602
|
+
action: z
|
|
603
|
+
.enum(["list", "create", "switch", "delete"])
|
|
604
|
+
.describe("list — profiles; create — new profile; switch — make active (restart required); delete — remove profile data."),
|
|
605
|
+
name: z.string().optional().describe("Profile name (required for create/switch/delete)."),
|
|
606
|
+
port: z.number().int().min(1).max(65535).optional().describe("Dashboard port for a new profile."),
|
|
607
|
+
});
|
|
608
|
+
|
|
609
|
+
/** transfer_tasks — экспорт и импорт задач. */
|
|
610
|
+
export const transferTasksSchema = z.object({
|
|
611
|
+
action: z.enum(["export", "import"]).describe("export — JSON snapshot; import — recreate tasks from a snapshot."),
|
|
612
|
+
data: z.string().optional().describe("JSON produced by export (required for import)."),
|
|
613
|
+
});
|
|
614
|
+
|
|
615
|
+
/** send_notification — проверка уведомлений и дайджест. */
|
|
616
|
+
export const sendNotificationSchema = z.object({
|
|
617
|
+
action: z
|
|
618
|
+
.enum(["test", "digest"])
|
|
619
|
+
.describe("test — send a test message through the configured channel; digest — send the digest now."),
|
|
620
|
+
});
|
|
621
|
+
|
|
622
|
+
/** get_dashboard_info — сведения о панели управления. */
|
|
623
|
+
export const getDashboardInfoSchema = z.object({});
|
|
624
|
+
|
|
625
|
+
/** cleanup_history — удаление старой истории. */
|
|
626
|
+
export const cleanupHistorySchema = z.object({
|
|
627
|
+
retentionDays: z.number().int().min(1).max(3650).optional().describe("Override the retention window."),
|
|
628
|
+
maxRecords: z.number().int().min(100).max(1000000).optional().describe("Override the record cap."),
|
|
629
|
+
});
|
|
630
|
+
|
|
631
|
+
/** emit_event — запуск задач по MCP-событию. */
|
|
632
|
+
export const emitEventSchema = z.object({
|
|
633
|
+
eventName: z.string().min(1).describe("Event name, for example 'deploy.finished'."),
|
|
634
|
+
payload: z.any().optional().describe("Event payload passed to trigger filters."),
|
|
405
635
|
});
|
|
406
636
|
|
|
407
637
|
type ScheduleArgs = z.infer<typeof scheduleTaskSchema>;
|
|
@@ -416,6 +646,16 @@ type TaskLogsArgs = z.infer<typeof getTaskLogsSchema>;
|
|
|
416
646
|
type DryRunArgs = z.infer<typeof dryRunSchema>;
|
|
417
647
|
type WorkspacesArgs = z.infer<typeof manageWorkspacesSchema>;
|
|
418
648
|
type MatrixControlArgs = z.infer<typeof matrixControlSchema>;
|
|
649
|
+
type MetricsArgs = z.infer<typeof getMetricsSchema>;
|
|
650
|
+
type AnalyticsArgs = z.infer<typeof getAnalyticsSchema>;
|
|
651
|
+
type SettingsArgs = z.infer<typeof manageSettingsSchema>;
|
|
652
|
+
type TemplatesArgs = z.infer<typeof manageTemplatesSchema>;
|
|
653
|
+
type ProfilesArgs = z.infer<typeof manageProfilesSchema>;
|
|
654
|
+
type TransferArgs = z.infer<typeof transferTasksSchema>;
|
|
655
|
+
type NotificationArgs = z.infer<typeof sendNotificationSchema>;
|
|
656
|
+
type DashboardInfoArgs = z.infer<typeof getDashboardInfoSchema>;
|
|
657
|
+
type CleanupHistoryArgs = z.infer<typeof cleanupHistorySchema>;
|
|
658
|
+
type EmitEventArgs = z.infer<typeof emitEventSchema>;
|
|
419
659
|
|
|
420
660
|
/**
|
|
421
661
|
* Директория проекта, в которой запущен OpenCode. Используется как рабочая
|
|
@@ -464,11 +704,15 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
|
|
|
464
704
|
nextTaskOnError,
|
|
465
705
|
triggerType,
|
|
466
706
|
mcpEvent,
|
|
707
|
+
watchPath,
|
|
467
708
|
workingDirectory,
|
|
468
709
|
workspaceId,
|
|
469
710
|
allowedTools,
|
|
470
711
|
deniedTools,
|
|
471
712
|
matrix,
|
|
713
|
+
timezone,
|
|
714
|
+
notBefore,
|
|
715
|
+
notAfter,
|
|
472
716
|
} = args;
|
|
473
717
|
|
|
474
718
|
try {
|
|
@@ -484,7 +728,7 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
|
|
|
484
728
|
nextTaskOnSuccess,
|
|
485
729
|
nextTaskOnError,
|
|
486
730
|
triggerType,
|
|
487
|
-
|
|
731
|
+
watchPath,
|
|
488
732
|
dependsOn,
|
|
489
733
|
model,
|
|
490
734
|
priority,
|
|
@@ -494,7 +738,12 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
|
|
|
494
738
|
workspaceId,
|
|
495
739
|
allowedTools,
|
|
496
740
|
deniedTools,
|
|
497
|
-
matrix
|
|
741
|
+
matrix,
|
|
742
|
+
undefined,
|
|
743
|
+
"create",
|
|
744
|
+
timezone,
|
|
745
|
+
notBefore,
|
|
746
|
+
notAfter
|
|
498
747
|
);
|
|
499
748
|
} catch (err: any) {
|
|
500
749
|
return {
|
|
@@ -505,6 +754,10 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
|
|
|
505
754
|
};
|
|
506
755
|
}
|
|
507
756
|
|
|
757
|
+
// Новый файловый триггер должен начать работать сразу, без перезапуска
|
|
758
|
+
// OpenCode: пересобираем набор watcher-ов после создания задачи.
|
|
759
|
+
await refreshFileTriggers();
|
|
760
|
+
|
|
508
761
|
const workspace = workspaceId ? getWorkspace(workspaceId) : undefined;
|
|
509
762
|
const effectiveWorkdir =
|
|
510
763
|
workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
|
|
@@ -527,6 +780,9 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
|
|
|
527
780
|
nextTaskOnSuccess: nextTaskOnSuccess?.trim() || null,
|
|
528
781
|
nextTaskOnError: nextTaskOnError?.trim() || null,
|
|
529
782
|
triggerType: triggerType ?? "cron",
|
|
783
|
+
timezone: timezone?.trim() || null,
|
|
784
|
+
notBefore: notBefore?.trim() || null,
|
|
785
|
+
notAfter: notAfter?.trim() || null,
|
|
530
786
|
mcpEvent: mcpEvent ?? null,
|
|
531
787
|
workingDirectory: effectiveWorkdir,
|
|
532
788
|
workspaceId: workspace?.id ?? null,
|
|
@@ -622,7 +878,12 @@ async function cancelMatrixRun(
|
|
|
622
878
|
clone.allowedTools,
|
|
623
879
|
clone.deniedTools,
|
|
624
880
|
undefined,
|
|
625
|
-
definition.name
|
|
881
|
+
definition.name,
|
|
882
|
+
"create",
|
|
883
|
+
clone.timezone,
|
|
884
|
+
clone.notBefore,
|
|
885
|
+
clone.notAfter,
|
|
886
|
+
clone.pausedUntil
|
|
626
887
|
);
|
|
627
888
|
} catch (err: any) {
|
|
628
889
|
warnings.push(
|
|
@@ -692,7 +953,7 @@ async function cleanupOrphanedMatrixTasks(): Promise<string[]> {
|
|
|
692
953
|
*/
|
|
693
954
|
async function deleteTaskWithFamily(
|
|
694
955
|
name: string
|
|
695
|
-
): Promise<{ removed: string[] }> {
|
|
956
|
+
): Promise<{ removed: string[]; existed: boolean }> {
|
|
696
957
|
const trimmed = name.trim();
|
|
697
958
|
const guard = getMatrixDeletionGuard(trimmed);
|
|
698
959
|
if (guard) throw new Error(guard);
|
|
@@ -700,6 +961,21 @@ async function deleteTaskWithFamily(
|
|
|
700
961
|
const plan = planMatrixFamilyDelete(trimmed);
|
|
701
962
|
const removed: string[] = [];
|
|
702
963
|
|
|
964
|
+
// Отличаем реальное удаление от «удаления пустоты»: раньше инструмент
|
|
965
|
+
// отвечал success даже на имя, которого никогда не существовало.
|
|
966
|
+
let existed = Boolean(getTask(trimmed));
|
|
967
|
+
if (!existed) {
|
|
968
|
+
try {
|
|
969
|
+
const osTasks = await scheduler.listTasks();
|
|
970
|
+
existed = osTasks.some(
|
|
971
|
+
(task) => task.taskName.toLowerCase() === trimmed.toLowerCase()
|
|
972
|
+
);
|
|
973
|
+
} catch {
|
|
974
|
+
// ОС-планировщик недоступен — довольствуемся данными БД.
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
if (plan && plan.children.length > 0) existed = true;
|
|
978
|
+
|
|
703
979
|
if (plan) {
|
|
704
980
|
for (const child of plan.children) {
|
|
705
981
|
try {
|
|
@@ -723,7 +999,7 @@ async function deleteTaskWithFamily(
|
|
|
723
999
|
// Определения могло уже не быть — задача всё равно удалена из ОС.
|
|
724
1000
|
}
|
|
725
1001
|
|
|
726
|
-
return { removed };
|
|
1002
|
+
return { removed, existed };
|
|
727
1003
|
}
|
|
728
1004
|
|
|
729
1005
|
/** delete_task — удаление задачи по имени (/f) */
|
|
@@ -731,7 +1007,17 @@ const deleteTaskExecute = wrapExecute<DeleteArgs>(async (args) => {
|
|
|
731
1007
|
const { name } = args;
|
|
732
1008
|
|
|
733
1009
|
try {
|
|
734
|
-
const { removed } = await deleteTaskWithFamily(name);
|
|
1010
|
+
const { removed, existed } = await deleteTaskWithFamily(name);
|
|
1011
|
+
// Убираем watcher удалённой задачи, не дожидаясь перезапуска плагина.
|
|
1012
|
+
await refreshFileTriggers();
|
|
1013
|
+
if (!existed && removed.length === 0) {
|
|
1014
|
+
return {
|
|
1015
|
+
content: JSON.stringify({
|
|
1016
|
+
success: false,
|
|
1017
|
+
error: `Задача "${name}" не найдена — удалять нечего.`,
|
|
1018
|
+
}),
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
735
1021
|
return {
|
|
736
1022
|
content: JSON.stringify({
|
|
737
1023
|
success: true,
|
|
@@ -757,7 +1043,7 @@ const runTaskNowExecute = wrapExecute<RunNowArgs>(async (args) => {
|
|
|
757
1043
|
|
|
758
1044
|
let alreadyRunning = false;
|
|
759
1045
|
try {
|
|
760
|
-
const result = await
|
|
1046
|
+
const result = await runTaskEntry(name);
|
|
761
1047
|
alreadyRunning = result.alreadyRunning;
|
|
762
1048
|
} catch (err: any) {
|
|
763
1049
|
return {
|
|
@@ -839,6 +1125,9 @@ async function updateTaskFromInput(
|
|
|
839
1125
|
const schedule = clearableString(input.schedule ?? input.newSchedule, previous.schedule);
|
|
840
1126
|
const prompt = clearableString(input.prompt ?? input.newPrompt, previous.prompt);
|
|
841
1127
|
const triggerType = input.triggerType ?? previous.triggerType ?? "cron";
|
|
1128
|
+
const timezone = clearableString(input.timezone, previous.timezone);
|
|
1129
|
+
const notBefore = clearableString(input.notBefore, previous.notBefore);
|
|
1130
|
+
const notAfter = clearableString(input.notAfter, previous.notAfter);
|
|
842
1131
|
|
|
843
1132
|
if (triggerType === "cron" && !schedule) {
|
|
844
1133
|
return {
|
|
@@ -886,7 +1175,11 @@ async function updateTaskFromInput(
|
|
|
886
1175
|
undefined,
|
|
887
1176
|
// Если задача была матрицей — синхронизируем клонов, а не
|
|
888
1177
|
// пересоздаём их с нуля (Спринт 17).
|
|
889
|
-
matrixWas && matrixNext ? "sync" : "create"
|
|
1178
|
+
matrixWas && matrixNext ? "sync" : "create",
|
|
1179
|
+
timezone,
|
|
1180
|
+
notBefore,
|
|
1181
|
+
notAfter,
|
|
1182
|
+
previous.pausedUntil
|
|
890
1183
|
);
|
|
891
1184
|
|
|
892
1185
|
// Матрица отключена при обновлении — убираем клонов и агрегатор.
|
|
@@ -894,6 +1187,10 @@ async function updateTaskFromInput(
|
|
|
894
1187
|
await removeMatrixChildrenFromScheduler(name);
|
|
895
1188
|
}
|
|
896
1189
|
|
|
1190
|
+
// Пересоздание могло изменить triggerType/watchPath — сразу
|
|
1191
|
+
// пересобираем набор файловых watcher-ов.
|
|
1192
|
+
await refreshFileTriggers();
|
|
1193
|
+
|
|
897
1194
|
return { success: true, message: `Задача "${name}" обновлена.` };
|
|
898
1195
|
} catch (err: any) {
|
|
899
1196
|
return {
|
|
@@ -915,7 +1212,8 @@ const updateTaskExecute = wrapExecute<UpdateArgs>(async (args) => {
|
|
|
915
1212
|
*/
|
|
916
1213
|
async function pauseOrResumeTask(
|
|
917
1214
|
name: string,
|
|
918
|
-
paused: boolean
|
|
1215
|
+
paused: boolean,
|
|
1216
|
+
until?: string
|
|
919
1217
|
): Promise<{ success: boolean; message: string; affected: string[]; warnings: string[] }> {
|
|
920
1218
|
const trimmed = name.trim();
|
|
921
1219
|
const definition = getTask(trimmed);
|
|
@@ -928,6 +1226,29 @@ async function pauseOrResumeTask(
|
|
|
928
1226
|
};
|
|
929
1227
|
}
|
|
930
1228
|
|
|
1229
|
+
// Пауза до даты (Спринт 19): проверяем ISO-момент до каких-либо изменений.
|
|
1230
|
+
let pausedUntil: string | undefined;
|
|
1231
|
+
if (paused && until?.trim()) {
|
|
1232
|
+
const parsed = Date.parse(until.trim());
|
|
1233
|
+
if (Number.isNaN(parsed)) {
|
|
1234
|
+
return {
|
|
1235
|
+
success: false,
|
|
1236
|
+
message: `Задача "${trimmed}": некорректная дата паузы "${until}". Нужен ISO-момент, например 2026-12-01T09:00:00Z.`,
|
|
1237
|
+
affected: [],
|
|
1238
|
+
warnings: [],
|
|
1239
|
+
};
|
|
1240
|
+
}
|
|
1241
|
+
if (parsed <= Date.now()) {
|
|
1242
|
+
return {
|
|
1243
|
+
success: false,
|
|
1244
|
+
message: `Задача "${trimmed}": дата паузы уже прошла.`,
|
|
1245
|
+
affected: [],
|
|
1246
|
+
warnings: [],
|
|
1247
|
+
};
|
|
1248
|
+
}
|
|
1249
|
+
pausedUntil = new Date(parsed).toISOString();
|
|
1250
|
+
}
|
|
1251
|
+
|
|
931
1252
|
const targets = definition.matrix
|
|
932
1253
|
? listMatrixClones(trimmed).map((clone) => clone.name)
|
|
933
1254
|
: [trimmed];
|
|
@@ -957,11 +1278,35 @@ async function pauseOrResumeTask(
|
|
|
957
1278
|
}
|
|
958
1279
|
}
|
|
959
1280
|
|
|
1281
|
+
// Фиксируем (или снимаем) автопродолжение в определении задачи. У матрицы
|
|
1282
|
+
// родитель хранит pausedUntil за всех клонов — их включает авто-resume.
|
|
1283
|
+
const definitionUpdates = paused
|
|
1284
|
+
? pausedUntil
|
|
1285
|
+
? { pausedUntil }
|
|
1286
|
+
: undefined
|
|
1287
|
+
: definition.pausedUntil
|
|
1288
|
+
? { pausedUntil: undefined }
|
|
1289
|
+
: undefined;
|
|
1290
|
+
if (definitionUpdates && affected.length > 0) {
|
|
1291
|
+
try {
|
|
1292
|
+
saveTask({ ...definition, ...definitionUpdates });
|
|
1293
|
+
} catch (err: any) {
|
|
1294
|
+
warnings.push(
|
|
1295
|
+
`не удалось сохранить автопродолжение: ${
|
|
1296
|
+
err instanceof Error ? err.message : String(err)
|
|
1297
|
+
}`
|
|
1298
|
+
);
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
const untilText = pausedUntil
|
|
1303
|
+
? ` до ${new Date(pausedUntil).toLocaleString()}`
|
|
1304
|
+
: "";
|
|
960
1305
|
const verb = paused ? "поставлена на паузу" : "возобновлена";
|
|
961
1306
|
const message = definition.matrix
|
|
962
|
-
? `Матрица "${trimmed}" ${verb}: ${affected.length} из ${targets.length} клонов.` +
|
|
1307
|
+
? `Матрица "${trimmed}" ${verb}${untilText}: ${affected.length} из ${targets.length} клонов.` +
|
|
963
1308
|
(warnings.length > 0 ? ` Ошибки: ${warnings.join("; ")}.` : "")
|
|
964
|
-
: `Задача "${trimmed}" ${verb}.` +
|
|
1309
|
+
: `Задача "${trimmed}" ${verb}${untilText}.` +
|
|
965
1310
|
(warnings.length > 0 ? ` Ошибка: ${warnings.join("; ")}.` : "");
|
|
966
1311
|
|
|
967
1312
|
return {
|
|
@@ -973,7 +1318,7 @@ async function pauseOrResumeTask(
|
|
|
973
1318
|
}
|
|
974
1319
|
|
|
975
1320
|
const pauseTaskExecute = wrapExecute<PauseArgs>(async (args) => {
|
|
976
|
-
const result = await pauseOrResumeTask(args.name, true);
|
|
1321
|
+
const result = await pauseOrResumeTask(args.name, true, args.until);
|
|
977
1322
|
return { content: JSON.stringify(result) };
|
|
978
1323
|
});
|
|
979
1324
|
|
|
@@ -982,6 +1327,88 @@ const resumeTaskExecute = wrapExecute<ResumeArgs>(async (args) => {
|
|
|
982
1327
|
return { content: JSON.stringify(result) };
|
|
983
1328
|
});
|
|
984
1329
|
|
|
1330
|
+
/** Периодичность проверки автопродолжения задач (Спринт 19). */
|
|
1331
|
+
const PAUSED_UNTIL_CHECK_MS = 5 * 60 * 1000;
|
|
1332
|
+
/** Период проверки дайджеста и зависших матриц (Спринт 20). */
|
|
1333
|
+
const NOTIFICATION_CHECK_MS = 60 * 1000;
|
|
1334
|
+
|
|
1335
|
+
/**
|
|
1336
|
+
* Спринт 19: автопродолжение задач, поставленных на паузу до даты.
|
|
1337
|
+
* Включает задачу в планировщике ОС и снимает `pausedUntil` из определения.
|
|
1338
|
+
* Клоны матрицы не обрабатываются отдельно — за них отвечает родитель.
|
|
1339
|
+
*/
|
|
1340
|
+
async function resumeExpiredPauses(): Promise<void> {
|
|
1341
|
+
const now = Date.now();
|
|
1342
|
+
const definitions = await loadTaskDefinitions();
|
|
1343
|
+
for (const definition of definitions) {
|
|
1344
|
+
if (!definition.pausedUntil) continue;
|
|
1345
|
+
if (definition.matrixParentId) continue;
|
|
1346
|
+
const untilMs = Date.parse(definition.pausedUntil);
|
|
1347
|
+
if (!Number.isFinite(untilMs) || untilMs > now) continue;
|
|
1348
|
+
|
|
1349
|
+
try {
|
|
1350
|
+
const targets = definition.matrix
|
|
1351
|
+
? listMatrixClones(definition.name).map((clone) => clone.name)
|
|
1352
|
+
: [definition.name];
|
|
1353
|
+
for (const target of targets) {
|
|
1354
|
+
await scheduler.resumeTask(target);
|
|
1355
|
+
}
|
|
1356
|
+
await saveTaskDefinition({ ...definition, pausedUntil: undefined });
|
|
1357
|
+
console.log(
|
|
1358
|
+
`[windows-scheduler] Автопродолжение: задача "${definition.name}" включена (пауза истекла).`
|
|
1359
|
+
);
|
|
1360
|
+
} catch (err: any) {
|
|
1361
|
+
console.error(
|
|
1362
|
+
`[windows-scheduler] Не удалось автопродолжить задачу "${definition.name}": ${
|
|
1363
|
+
err instanceof Error ? err.message : String(err)
|
|
1364
|
+
}`
|
|
1365
|
+
);
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
/** Уже отправленные уведомления о зависших клонах (id записи истории). */
|
|
1371
|
+
const notifiedStuckRecords = new Set<number>();
|
|
1372
|
+
|
|
1373
|
+
/**
|
|
1374
|
+
* Детектор зависших матриц (Спринт 20): клоны, которые выполняются дольше
|
|
1375
|
+
* `notifications.matrix.stuckAfterMinutes`. Каждый запуск уведомляется один раз.
|
|
1376
|
+
*/
|
|
1377
|
+
async function checkStuckMatrices(): Promise<void> {
|
|
1378
|
+
const settings = await loadSettings();
|
|
1379
|
+
const config = settings.notifications;
|
|
1380
|
+
if (!config?.enabled) return;
|
|
1381
|
+
const matrix = config.matrix;
|
|
1382
|
+
if (!matrix?.enabled) return;
|
|
1383
|
+
const threshold = matrix.stuckAfterMinutes;
|
|
1384
|
+
if (!Number.isFinite(threshold) || threshold <= 0) return;
|
|
1385
|
+
|
|
1386
|
+
const running = listRunningRecords();
|
|
1387
|
+
if (running.length === 0) {
|
|
1388
|
+
notifiedStuckRecords.clear();
|
|
1389
|
+
return;
|
|
1390
|
+
}
|
|
1391
|
+
// Снимаем отметки с завершившихся записей, чтобы Set не рос бесконечно.
|
|
1392
|
+
const runningIds = new Set(running.map((record) => record.id));
|
|
1393
|
+
for (const id of notifiedStuckRecords) {
|
|
1394
|
+
if (!runningIds.has(id)) notifiedStuckRecords.delete(id);
|
|
1395
|
+
}
|
|
1396
|
+
|
|
1397
|
+
const parentByClone = new Map<string, string>();
|
|
1398
|
+
for (const definition of await loadTaskDefinitions()) {
|
|
1399
|
+
if (definition.matrixParentId) {
|
|
1400
|
+
parentByClone.set(definition.name.toLowerCase(), definition.matrixParentId);
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
const stuck = findStuckMatrixClones(running, parentByClone, new Date(), threshold);
|
|
1405
|
+
for (const item of stuck) {
|
|
1406
|
+
if (notifiedStuckRecords.has(item.id)) continue;
|
|
1407
|
+
notifiedStuckRecords.add(item.id);
|
|
1408
|
+
await notifyStuckMatrix(item);
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
|
|
985
1412
|
/** get_history — история запусков с фильтрами по задаче и статусу. */
|
|
986
1413
|
const getHistoryExecute = wrapExecute<HistoryArgs>(async (args) => {
|
|
987
1414
|
const limit = Math.max(1, Math.min(args.limit ?? 20, 200));
|
|
@@ -1054,6 +1481,22 @@ const dryRunExecute = wrapExecute<DryRunArgs>(async (args) => {
|
|
|
1054
1481
|
};
|
|
1055
1482
|
});
|
|
1056
1483
|
|
|
1484
|
+
/**
|
|
1485
|
+
* Перегенерирует env-файлы всех задач, привязанных к workspace (Спринт 21).
|
|
1486
|
+
* Обёртки читают env-файл при запуске, поэтому перезапуск задач не нужен.
|
|
1487
|
+
*/
|
|
1488
|
+
async function refreshWorkspaceEnvFiles(workspaceId: string): Promise<number> {
|
|
1489
|
+
const workspace = getWorkspace(workspaceId);
|
|
1490
|
+
if (!workspace) return 0;
|
|
1491
|
+
let refreshed = 0;
|
|
1492
|
+
for (const task of await loadTaskDefinitions()) {
|
|
1493
|
+
if (task.workspaceId !== workspaceId) continue;
|
|
1494
|
+
writeWorkspaceEnvFile(workspace, PLUGIN_DIR, sanitizeName(task.name));
|
|
1495
|
+
refreshed += 1;
|
|
1496
|
+
}
|
|
1497
|
+
return refreshed;
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1057
1500
|
/** manage_workspaces — CRUD multi-repo workspace-ов. */
|
|
1058
1501
|
const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
|
|
1059
1502
|
try {
|
|
@@ -1061,6 +1504,7 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
|
|
|
1061
1504
|
case "list": {
|
|
1062
1505
|
const workspaces = listWorkspaces().map((workspace) => ({
|
|
1063
1506
|
...workspace,
|
|
1507
|
+
env: maskEnvForLog(workspace.env),
|
|
1064
1508
|
gitBranch: readGitBranch(workspace.path) ?? null,
|
|
1065
1509
|
}));
|
|
1066
1510
|
return {
|
|
@@ -1084,12 +1528,15 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
|
|
|
1084
1528
|
name: args.name,
|
|
1085
1529
|
path: args.path,
|
|
1086
1530
|
color: args.color,
|
|
1531
|
+
env: args.env,
|
|
1532
|
+
envFile: args.envFile,
|
|
1087
1533
|
});
|
|
1088
1534
|
return {
|
|
1089
1535
|
content: JSON.stringify({
|
|
1090
1536
|
success: true,
|
|
1091
1537
|
workspace: {
|
|
1092
1538
|
...workspace,
|
|
1539
|
+
env: maskEnvForLog(workspace.env),
|
|
1093
1540
|
gitBranch: readGitBranch(workspace.path) ?? null,
|
|
1094
1541
|
},
|
|
1095
1542
|
}),
|
|
@@ -1108,6 +1555,8 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
|
|
|
1108
1555
|
name: args.name,
|
|
1109
1556
|
path: args.path,
|
|
1110
1557
|
color: args.color,
|
|
1558
|
+
env: args.env,
|
|
1559
|
+
envFile: args.envFile,
|
|
1111
1560
|
});
|
|
1112
1561
|
if (!workspace) {
|
|
1113
1562
|
return {
|
|
@@ -1117,11 +1566,16 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
|
|
|
1117
1566
|
}),
|
|
1118
1567
|
};
|
|
1119
1568
|
}
|
|
1569
|
+
// Env-файлы уже созданных задач перегенерируются сразу: обёртки читают
|
|
1570
|
+
// файл при запуске, поэтому ждать обновления задачи не нужно.
|
|
1571
|
+
const refreshedTasks = await refreshWorkspaceEnvFiles(workspace.id);
|
|
1120
1572
|
return {
|
|
1121
1573
|
content: JSON.stringify({
|
|
1122
1574
|
success: true,
|
|
1575
|
+
refreshedTasks,
|
|
1123
1576
|
workspace: {
|
|
1124
1577
|
...workspace,
|
|
1578
|
+
env: maskEnvForLog(workspace.env),
|
|
1125
1579
|
gitBranch: readGitBranch(workspace.path) ?? null,
|
|
1126
1580
|
},
|
|
1127
1581
|
}),
|
|
@@ -1157,8 +1611,32 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
|
|
|
1157
1611
|
}
|
|
1158
1612
|
});
|
|
1159
1613
|
|
|
1160
|
-
/** matrix_control — результаты,
|
|
1614
|
+
/** matrix_control — результаты, отмена, очистка и предпросмотр матриц. */
|
|
1161
1615
|
const matrixControlExecute = wrapExecute<MatrixControlArgs>(async (args) => {
|
|
1616
|
+
if (args.action === "preview") {
|
|
1617
|
+
const clones = expandMatrixTask({
|
|
1618
|
+
name: (args.name ?? "").trim() || "task",
|
|
1619
|
+
schedule: "* * * * *",
|
|
1620
|
+
prompt: "preview",
|
|
1621
|
+
matrix: {
|
|
1622
|
+
workspaceIds: Array.isArray(args.workspaceIds) ? args.workspaceIds : [],
|
|
1623
|
+
strategy: args.strategy,
|
|
1624
|
+
failureMode: args.failureMode,
|
|
1625
|
+
aggregation: args.aggregation,
|
|
1626
|
+
},
|
|
1627
|
+
} as any);
|
|
1628
|
+
return {
|
|
1629
|
+
content: JSON.stringify({
|
|
1630
|
+
success: true,
|
|
1631
|
+
clones: clones.map((clone) => ({
|
|
1632
|
+
name: clone.name,
|
|
1633
|
+
workspaceId: clone.workspaceId ?? "",
|
|
1634
|
+
workspaceName: clone.workspaceId ? getWorkspace(clone.workspaceId)?.name ?? null : null,
|
|
1635
|
+
})),
|
|
1636
|
+
}),
|
|
1637
|
+
};
|
|
1638
|
+
}
|
|
1639
|
+
|
|
1162
1640
|
if (args.action === "cleanup") {
|
|
1163
1641
|
const removed = await cleanupOrphanedMatrixTasks();
|
|
1164
1642
|
return {
|
|
@@ -1216,6 +1694,334 @@ const matrixControlExecute = wrapExecute<MatrixControlArgs>(async (args) => {
|
|
|
1216
1694
|
}
|
|
1217
1695
|
});
|
|
1218
1696
|
|
|
1697
|
+
/** get_metrics — суммарная статистика запусков. */
|
|
1698
|
+
const getMetricsExecute = wrapExecute<MetricsArgs>(async () => {
|
|
1699
|
+
const metrics = await loadMetrics();
|
|
1700
|
+
return { content: JSON.stringify({ success: true, metrics }) };
|
|
1701
|
+
});
|
|
1702
|
+
|
|
1703
|
+
/** get_analytics — аналитика запусков и стоимости за период. */
|
|
1704
|
+
const getAnalyticsExecute = wrapExecute<AnalyticsArgs>(async (args) => {
|
|
1705
|
+
const windowDays = Math.min(365, Math.max(1, Math.floor(Number(args.days) || 14)));
|
|
1706
|
+
const records = getHistory(null, 20000);
|
|
1707
|
+
const definitions = await loadTaskDefinitions();
|
|
1708
|
+
const report = buildAnalytics(records, {
|
|
1709
|
+
days: windowDays,
|
|
1710
|
+
topLimit: Math.max(1, Math.floor(Number(args.topLimit) || 10)),
|
|
1711
|
+
tasks: definitions.map((definition) => ({
|
|
1712
|
+
name: definition.name,
|
|
1713
|
+
matrixParentId: definition.matrixParentId,
|
|
1714
|
+
})),
|
|
1715
|
+
});
|
|
1716
|
+
return { content: JSON.stringify({ success: true, report }) };
|
|
1717
|
+
});
|
|
1718
|
+
|
|
1719
|
+
/** manage_settings — чтение и изменение глобальных настроек. */
|
|
1720
|
+
const manageSettingsExecute = wrapExecute<SettingsArgs>(async (args) => {
|
|
1721
|
+
const current = await loadSettings();
|
|
1722
|
+
if (args.action === "get") {
|
|
1723
|
+
return { content: JSON.stringify({ success: true, settings: current }) };
|
|
1724
|
+
}
|
|
1725
|
+
|
|
1726
|
+
if (
|
|
1727
|
+
args.maxConcurrent === undefined &&
|
|
1728
|
+
args.winterMode === undefined &&
|
|
1729
|
+
args.notifications === undefined &&
|
|
1730
|
+
args.history === undefined
|
|
1731
|
+
) {
|
|
1732
|
+
return {
|
|
1733
|
+
content: JSON.stringify({
|
|
1734
|
+
success: false,
|
|
1735
|
+
error: "Для action=update передайте хотя бы одно поле: maxConcurrent, winterMode, notifications или history.",
|
|
1736
|
+
settings: current,
|
|
1737
|
+
}),
|
|
1738
|
+
};
|
|
1739
|
+
}
|
|
1740
|
+
|
|
1741
|
+
const settings = await saveSettings({
|
|
1742
|
+
maxConcurrent: args.maxConcurrent,
|
|
1743
|
+
winterMode: args.winterMode,
|
|
1744
|
+
notifications: args.notifications as NotificationSettings | undefined,
|
|
1745
|
+
history: args.history as HistorySettings | undefined,
|
|
1746
|
+
});
|
|
1747
|
+
return { content: JSON.stringify({ success: true, settings }) };
|
|
1748
|
+
});
|
|
1749
|
+
|
|
1750
|
+
/** manage_templates — список, сохранение и удаление шаблонов задач. */
|
|
1751
|
+
const manageTemplatesExecute = wrapExecute<TemplatesArgs>(async (args) => {
|
|
1752
|
+
if (args.action === "list") {
|
|
1753
|
+
return { content: JSON.stringify({ success: true, templates: await loadTemplates() }) };
|
|
1754
|
+
}
|
|
1755
|
+
|
|
1756
|
+
if (args.action === "delete") {
|
|
1757
|
+
const id = args.id?.trim();
|
|
1758
|
+
if (!id) {
|
|
1759
|
+
return { content: JSON.stringify({ success: false, error: "Для action=delete нужен id шаблона." }) };
|
|
1760
|
+
}
|
|
1761
|
+
const before = await loadTemplates();
|
|
1762
|
+
const existed = before.some((template) => template.id === id);
|
|
1763
|
+
await deleteTemplate(id);
|
|
1764
|
+
return {
|
|
1765
|
+
content: JSON.stringify({
|
|
1766
|
+
success: existed,
|
|
1767
|
+
message: existed ? `Шаблон ${id} удалён.` : `Шаблон ${id} не найден.`,
|
|
1768
|
+
}),
|
|
1769
|
+
};
|
|
1770
|
+
}
|
|
1771
|
+
|
|
1772
|
+
const { action, ...fields } = args;
|
|
1773
|
+
if (!fields.name?.trim() || !fields.prompt?.trim()) {
|
|
1774
|
+
return {
|
|
1775
|
+
content: JSON.stringify({
|
|
1776
|
+
success: false,
|
|
1777
|
+
error: "Для action=save нужны непустые name и prompt.",
|
|
1778
|
+
}),
|
|
1779
|
+
};
|
|
1780
|
+
}
|
|
1781
|
+
const template = await saveTemplate(fields as Omit<TaskTemplate, "id"> & { id?: string });
|
|
1782
|
+
return { content: JSON.stringify({ success: true, template }) };
|
|
1783
|
+
});
|
|
1784
|
+
|
|
1785
|
+
/** manage_profiles — список, создание, переключение и удаление профилей. */
|
|
1786
|
+
const manageProfilesExecute = wrapExecute<ProfilesArgs>(async (args) => {
|
|
1787
|
+
if (args.action === "list") {
|
|
1788
|
+
return {
|
|
1789
|
+
content: JSON.stringify({
|
|
1790
|
+
success: true,
|
|
1791
|
+
current: getProfileName(),
|
|
1792
|
+
pinnedByEnv: isProfilePinnedByEnv(),
|
|
1793
|
+
profiles: listProfiles(),
|
|
1794
|
+
}),
|
|
1795
|
+
};
|
|
1796
|
+
}
|
|
1797
|
+
|
|
1798
|
+
const name = args.name?.trim();
|
|
1799
|
+
if (!name) {
|
|
1800
|
+
return {
|
|
1801
|
+
content: JSON.stringify({
|
|
1802
|
+
success: false,
|
|
1803
|
+
error: `Для action=${args.action} нужно имя профиля.`,
|
|
1804
|
+
}),
|
|
1805
|
+
};
|
|
1806
|
+
}
|
|
1807
|
+
|
|
1808
|
+
if (args.action === "create") {
|
|
1809
|
+
const meta = createProfile(name, args.port);
|
|
1810
|
+
const profile = listProfiles().find((item) => item.name === meta.name);
|
|
1811
|
+
return {
|
|
1812
|
+
content: JSON.stringify({
|
|
1813
|
+
success: true,
|
|
1814
|
+
message: `Профиль "${meta.name}" создан (порт дашборда ${meta.port}).`,
|
|
1815
|
+
profile: profile ?? {
|
|
1816
|
+
name: meta.name,
|
|
1817
|
+
dir: getProfileDir(meta.name),
|
|
1818
|
+
port: meta.port,
|
|
1819
|
+
isDefault: meta.name === DEFAULT_PROFILE,
|
|
1820
|
+
active: meta.name === getProfileName(),
|
|
1821
|
+
},
|
|
1822
|
+
}),
|
|
1823
|
+
};
|
|
1824
|
+
}
|
|
1825
|
+
|
|
1826
|
+
if (args.action === "switch") {
|
|
1827
|
+
setActiveProfile(name);
|
|
1828
|
+
const current = getProfileName();
|
|
1829
|
+
return {
|
|
1830
|
+
content: JSON.stringify({
|
|
1831
|
+
success: true,
|
|
1832
|
+
current,
|
|
1833
|
+
restartRequired: true,
|
|
1834
|
+
message: isProfilePinnedByEnv()
|
|
1835
|
+
? `Профиль задан переменной OPENCODE_SCHEDULER_PROFILE=${current}. Перезапустите OpenCode.`
|
|
1836
|
+
: `Активный профиль: ${sanitizeProfileName(name)}. Перезапустите OpenCode, чтобы применить изменения.`,
|
|
1837
|
+
}),
|
|
1838
|
+
};
|
|
1839
|
+
}
|
|
1840
|
+
|
|
1841
|
+
const removed = deleteProfile(name);
|
|
1842
|
+
return {
|
|
1843
|
+
content: JSON.stringify({
|
|
1844
|
+
success: removed,
|
|
1845
|
+
message: removed
|
|
1846
|
+
? `Профиль "${sanitizeProfileName(name)}" удалён вместе с его БД и настройками.`
|
|
1847
|
+
: "Профиль не найден.",
|
|
1848
|
+
}),
|
|
1849
|
+
};
|
|
1850
|
+
});
|
|
1851
|
+
|
|
1852
|
+
/** transfer_tasks — экспорт и импорт задач. */
|
|
1853
|
+
const transferTasksExecute = wrapExecute<TransferArgs>(async (args) => {
|
|
1854
|
+
if (args.action === "export") {
|
|
1855
|
+
const tasks = await scheduler.listTasks();
|
|
1856
|
+
const { data, count } = await buildExportJson(
|
|
1857
|
+
tasks.map((task) => ({ ...task, name: task.taskName || "" }))
|
|
1858
|
+
);
|
|
1859
|
+
return { content: JSON.stringify({ success: true, data, count }) };
|
|
1860
|
+
}
|
|
1861
|
+
|
|
1862
|
+
if (!args.data) {
|
|
1863
|
+
return { content: JSON.stringify({ success: false, error: "Для action=import нужны данные экспорта." }) };
|
|
1864
|
+
}
|
|
1865
|
+
const parsed = parseImportJson(args.data);
|
|
1866
|
+
if (parsed.tasks.length === 0) {
|
|
1867
|
+
return {
|
|
1868
|
+
content: JSON.stringify({
|
|
1869
|
+
success: false,
|
|
1870
|
+
error: "В данных нет задач для импорта.",
|
|
1871
|
+
errors: parsed.errors,
|
|
1872
|
+
}),
|
|
1873
|
+
};
|
|
1874
|
+
}
|
|
1875
|
+
|
|
1876
|
+
const imported: string[] = [];
|
|
1877
|
+
const errors: string[] = [...parsed.errors];
|
|
1878
|
+
for (const def of parsed.tasks) {
|
|
1879
|
+
try {
|
|
1880
|
+
await schedulerCreateTask(
|
|
1881
|
+
def.name,
|
|
1882
|
+
def.schedule,
|
|
1883
|
+
def.prompt,
|
|
1884
|
+
def.timeoutSeconds,
|
|
1885
|
+
def.workingDirectory ?? def.workdir,
|
|
1886
|
+
def.retryCount,
|
|
1887
|
+
def.retryDelay,
|
|
1888
|
+
def.qualityGate,
|
|
1889
|
+
def.nextTaskOnSuccess,
|
|
1890
|
+
def.nextTaskOnError,
|
|
1891
|
+
def.triggerType,
|
|
1892
|
+
def.watchPath,
|
|
1893
|
+
def.dependsOn,
|
|
1894
|
+
def.model,
|
|
1895
|
+
def.priority,
|
|
1896
|
+
def.beforeScript,
|
|
1897
|
+
def.afterScript,
|
|
1898
|
+
def.mcpEvent,
|
|
1899
|
+
def.workspaceId,
|
|
1900
|
+
def.allowedTools,
|
|
1901
|
+
def.deniedTools,
|
|
1902
|
+
def.matrix,
|
|
1903
|
+
def.matrixParentId,
|
|
1904
|
+
"create",
|
|
1905
|
+
def.timezone,
|
|
1906
|
+
def.notBefore,
|
|
1907
|
+
def.notAfter,
|
|
1908
|
+
def.pausedUntil
|
|
1909
|
+
);
|
|
1910
|
+
await saveTaskDefinition(def);
|
|
1911
|
+
imported.push(def.name);
|
|
1912
|
+
} catch (err: any) {
|
|
1913
|
+
errors.push(`${def.name}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1914
|
+
}
|
|
1915
|
+
}
|
|
1916
|
+
await refreshFileTriggers();
|
|
1917
|
+
return {
|
|
1918
|
+
content: JSON.stringify({ success: errors.length === 0, imported, errors }),
|
|
1919
|
+
};
|
|
1920
|
+
});
|
|
1921
|
+
|
|
1922
|
+
/** send_notification — тестовое уведомление или дайджест. */
|
|
1923
|
+
const sendNotificationExecute = wrapExecute<NotificationArgs>(async (args) => {
|
|
1924
|
+
const result =
|
|
1925
|
+
args.action === "test"
|
|
1926
|
+
? await sendTestNotification()
|
|
1927
|
+
: await sendDigestNow({ updateLastSentAt: false });
|
|
1928
|
+
return { content: JSON.stringify(result) };
|
|
1929
|
+
});
|
|
1930
|
+
|
|
1931
|
+
/** get_dashboard_info — порт дашборда, платформа и активный профиль. */
|
|
1932
|
+
const getDashboardInfoExecute = wrapExecute<DashboardInfoArgs>(async () => {
|
|
1933
|
+
const port = getDashboardPort();
|
|
1934
|
+
return {
|
|
1935
|
+
content: JSON.stringify({
|
|
1936
|
+
success: true,
|
|
1937
|
+
port,
|
|
1938
|
+
url: port ? `http://127.0.0.1:${port}` : null,
|
|
1939
|
+
platform: scheduler.platform,
|
|
1940
|
+
title: scheduler.title,
|
|
1941
|
+
profile: getProfileName(),
|
|
1942
|
+
}),
|
|
1943
|
+
};
|
|
1944
|
+
});
|
|
1945
|
+
|
|
1946
|
+
/** cleanup_history — удаление старых записей истории. */
|
|
1947
|
+
const cleanupHistoryExecute = wrapExecute<CleanupHistoryArgs>(async (args) => {
|
|
1948
|
+
const report = await runHistoryRetention({
|
|
1949
|
+
retentionDays: args.retentionDays,
|
|
1950
|
+
maxRecords: args.maxRecords,
|
|
1951
|
+
});
|
|
1952
|
+
return {
|
|
1953
|
+
content: JSON.stringify({
|
|
1954
|
+
success: true,
|
|
1955
|
+
message: report.skipped
|
|
1956
|
+
? report.skipped
|
|
1957
|
+
: `Удалено ${report.deleted} записей (по возрасту: ${report.deletedByAge}, по лимиту: ${report.deletedByCount}), осталось ${report.kept}.`,
|
|
1958
|
+
report,
|
|
1959
|
+
}),
|
|
1960
|
+
};
|
|
1961
|
+
});
|
|
1962
|
+
|
|
1963
|
+
/** emit_event — запуск задач, подписанных на MCP-событие. */
|
|
1964
|
+
const emitEventExecute = wrapExecute<EmitEventArgs>(async (args) => {
|
|
1965
|
+
const eventName = args.eventName?.trim();
|
|
1966
|
+
if (!eventName) {
|
|
1967
|
+
return { content: JSON.stringify({ success: false, error: "Не передано имя события." }) };
|
|
1968
|
+
}
|
|
1969
|
+
const payload = args.payload ?? {};
|
|
1970
|
+
const definitions = await loadTaskDefinitions();
|
|
1971
|
+
const matched = definitions
|
|
1972
|
+
.filter(
|
|
1973
|
+
(def) =>
|
|
1974
|
+
def.triggerType === "mcp-event" &&
|
|
1975
|
+
def.mcpEvent?.event?.toLowerCase() === eventName.toLowerCase() &&
|
|
1976
|
+
matchesEventFilter(def.mcpEvent?.filter, payload)
|
|
1977
|
+
)
|
|
1978
|
+
.sort(
|
|
1979
|
+
(a, b) =>
|
|
1980
|
+
(normalizePriority(b.priority) ?? 0) - (normalizePriority(a.priority) ?? 0)
|
|
1981
|
+
);
|
|
1982
|
+
|
|
1983
|
+
const triggered: string[] = [];
|
|
1984
|
+
for (const def of matched) {
|
|
1985
|
+
try {
|
|
1986
|
+
await runTaskEntry(def.name);
|
|
1987
|
+
triggered.push(def.name);
|
|
1988
|
+
} catch (err: any) {
|
|
1989
|
+
console.error(`[windows-scheduler] emit_event: не удалось запустить ${def.name}:`, err);
|
|
1990
|
+
}
|
|
1991
|
+
}
|
|
1992
|
+
return {
|
|
1993
|
+
content: JSON.stringify({
|
|
1994
|
+
success: true,
|
|
1995
|
+
message:
|
|
1996
|
+
triggered.length > 0
|
|
1997
|
+
? `Запущено задач: ${triggered.length}.`
|
|
1998
|
+
: `Нет задач, подписанных на событие "${eventName}".`,
|
|
1999
|
+
triggered,
|
|
2000
|
+
}),
|
|
2001
|
+
};
|
|
2002
|
+
});
|
|
2003
|
+
|
|
2004
|
+
/**
|
|
2005
|
+
* Менеджер файловых триггеров живёт на уровне модуля, чтобы его можно было
|
|
2006
|
+
* обновлять после создания/изменения/удаления задачи. Раньше refresh()
|
|
2007
|
+
* вызывался только при старте плагина, из-за чего новые watchPath начинали
|
|
2008
|
+
* работать лишь после перезапуска OpenCode.
|
|
2009
|
+
*/
|
|
2010
|
+
let fileWatcherManager: FileWatchManager | null = null;
|
|
2011
|
+
|
|
2012
|
+
async function refreshFileTriggers(): Promise<void> {
|
|
2013
|
+
if (!fileWatcherManager) return;
|
|
2014
|
+
try {
|
|
2015
|
+
await fileWatcherManager.refresh();
|
|
2016
|
+
} catch (err: any) {
|
|
2017
|
+
console.error(
|
|
2018
|
+
`[windows-scheduler] Не удалось обновить файловые триггеры: ${
|
|
2019
|
+
err instanceof Error ? err.message : String(err)
|
|
2020
|
+
}`
|
|
2021
|
+
);
|
|
2022
|
+
}
|
|
2023
|
+
}
|
|
2024
|
+
|
|
1219
2025
|
export default Plugin.define({
|
|
1220
2026
|
id: "opencode-windows-scheduler",
|
|
1221
2027
|
setup: async (ctx) => {
|
|
@@ -1247,6 +2053,62 @@ export default Plugin.define({
|
|
|
1247
2053
|
}
|
|
1248
2054
|
checkJsonBackups();
|
|
1249
2055
|
|
|
2056
|
+
// Спринт 18: ежедневная очистка истории. Ошибка ретеншна не должна мешать
|
|
2057
|
+
// плагину стартовать — пишем в лог и продолжаем.
|
|
2058
|
+
void maybeRunHistoryRetention()
|
|
2059
|
+
.then((report) => {
|
|
2060
|
+
if (report && report.deleted > 0) {
|
|
2061
|
+
console.log(
|
|
2062
|
+
`[retention] Удалено ${report.deleted} записей истории ` +
|
|
2063
|
+
`(по возрасту: ${report.deletedByAge}, по лимиту: ${report.deletedByCount}); ` +
|
|
2064
|
+
`осталось ${report.kept}.`
|
|
2065
|
+
);
|
|
2066
|
+
}
|
|
2067
|
+
})
|
|
2068
|
+
.catch((err: any) => {
|
|
2069
|
+
console.error(
|
|
2070
|
+
`[retention] Не удалось очистить историю: ${
|
|
2071
|
+
err instanceof Error ? err.message : String(err)
|
|
2072
|
+
}`
|
|
2073
|
+
);
|
|
2074
|
+
});
|
|
2075
|
+
|
|
2076
|
+
// Спринт 19: автопродолжение задач, поставленных на паузу до даты.
|
|
2077
|
+
// Проверяем сразу при старте и далее раз в 5 минут, пока плагин жив.
|
|
2078
|
+
void resumeExpiredPauses().catch((err: any) => {
|
|
2079
|
+
console.error(
|
|
2080
|
+
`[windows-scheduler] Не удалось проверить автопродолжение: ${
|
|
2081
|
+
err instanceof Error ? err.message : String(err)
|
|
2082
|
+
}`
|
|
2083
|
+
);
|
|
2084
|
+
});
|
|
2085
|
+
const pausedUntilTimer = setInterval(() => {
|
|
2086
|
+
void resumeExpiredPauses().catch((err: any) => {
|
|
2087
|
+
console.error(
|
|
2088
|
+
`[windows-scheduler] Не удалось проверить автопродолжение: ${
|
|
2089
|
+
err instanceof Error ? err.message : String(err)
|
|
2090
|
+
}`
|
|
2091
|
+
);
|
|
2092
|
+
});
|
|
2093
|
+
}, PAUSED_UNTIL_CHECK_MS);
|
|
2094
|
+
pausedUntilTimer.unref?.();
|
|
2095
|
+
|
|
2096
|
+
// Спринт 20: дайджест и детектор зависших матриц. Проверяем сразу при
|
|
2097
|
+
// старте и далее раз в минуту; таймер не держит процесс Node живым.
|
|
2098
|
+
const notificationTimer = setInterval(() => {
|
|
2099
|
+
void maybeSendDigest().catch(() => undefined);
|
|
2100
|
+
void checkStuckMatrices().catch((err: any) => {
|
|
2101
|
+
console.error(
|
|
2102
|
+
`[windows-scheduler] Детектор зависших матриц: ${
|
|
2103
|
+
err instanceof Error ? err.message : String(err)
|
|
2104
|
+
}`
|
|
2105
|
+
);
|
|
2106
|
+
});
|
|
2107
|
+
}, NOTIFICATION_CHECK_MS);
|
|
2108
|
+
notificationTimer.unref?.();
|
|
2109
|
+
void maybeSendDigest().catch(() => undefined);
|
|
2110
|
+
void checkStuckMatrices().catch(() => undefined);
|
|
2111
|
+
|
|
1250
2112
|
// Инициализация блокировок: создаём директорию и очищаем зависшие lock-файлы (>24 ч).
|
|
1251
2113
|
const lockManager = new LockManager(LOCK_DIR);
|
|
1252
2114
|
await lockManager.initialize();
|
|
@@ -1270,22 +2132,24 @@ export default Plugin.define({
|
|
|
1270
2132
|
// Catch-up имеет смысл только для cron-задач.
|
|
1271
2133
|
if ((def.triggerType ?? "cron") !== "cron") continue;
|
|
1272
2134
|
if (!def.schedule) continue;
|
|
1273
|
-
|
|
1274
|
-
if (
|
|
1275
|
-
const
|
|
2135
|
+
// Задача на паузе до даты — её включит авто-продолжение.
|
|
2136
|
+
if (def.pausedUntil) continue;
|
|
2137
|
+
const prev = prevRun(def.schedule, now, def.timezone);
|
|
2138
|
+
if (!prev) continue;
|
|
2139
|
+
const ageMs = now.getTime() - prev.getTime();
|
|
1276
2140
|
if (ageMs < catchUpThresholdMs) continue;
|
|
1277
2141
|
|
|
1278
2142
|
// Есть ли запись в истории после предполагаемого времени запуска?
|
|
1279
2143
|
const ranAfter = history.some(
|
|
1280
2144
|
(r) =>
|
|
1281
2145
|
r.taskName.toLowerCase() === def.name.toLowerCase() &&
|
|
1282
|
-
new Date(r.startedAt).getTime() >=
|
|
2146
|
+
new Date(r.startedAt).getTime() >= prev.getTime()
|
|
1283
2147
|
);
|
|
1284
2148
|
if (ranAfter) continue;
|
|
1285
2149
|
|
|
1286
2150
|
// Запускаем задачу и пишем в лог.
|
|
1287
2151
|
try {
|
|
1288
|
-
await
|
|
2152
|
+
await runTaskEntry(def.name);
|
|
1289
2153
|
console.log(
|
|
1290
2154
|
`[windows-scheduler] Запущено восстановление пропущенной задачи "${def.name}" (последний срабатывал ~${Math.round(ageMs / 1000)} с назад).`
|
|
1291
2155
|
);
|
|
@@ -1306,9 +2170,9 @@ export default Plugin.define({
|
|
|
1306
2170
|
|
|
1307
2171
|
// Файловые триггеры (File Watchers): задачи с triggerType === "file"
|
|
1308
2172
|
// запускаются при изменении watchPath через chokidar (с дебаунсом).
|
|
1309
|
-
|
|
2173
|
+
fileWatcherManager = new FileWatchManager(async (taskName) => {
|
|
1310
2174
|
try {
|
|
1311
|
-
await
|
|
2175
|
+
await runTaskEntry(taskName);
|
|
1312
2176
|
console.log(
|
|
1313
2177
|
`[windows-scheduler] Запуск задачи "${taskName}" по изменению отслеживаемого файла.`
|
|
1314
2178
|
);
|
|
@@ -1320,7 +2184,7 @@ export default Plugin.define({
|
|
|
1320
2184
|
);
|
|
1321
2185
|
}
|
|
1322
2186
|
});
|
|
1323
|
-
void
|
|
2187
|
+
void refreshFileTriggers();
|
|
1324
2188
|
|
|
1325
2189
|
const registration = await ctx.tool.transform((editor) => {
|
|
1326
2190
|
// editor.add регистрирует новые инструменты плагина с codemode: true,
|
|
@@ -1436,10 +2300,100 @@ export default Plugin.define({
|
|
|
1436
2300
|
name: "matrix_control",
|
|
1437
2301
|
input: matrixControlSchema,
|
|
1438
2302
|
description:
|
|
1439
|
-
"Matrix lifecycle: results (aggregate status/counters of a matrix), cancel (cancel pending clones, stop running ones)
|
|
2303
|
+
"Matrix lifecycle: results (aggregate status/counters of a matrix), cancel (cancel pending clones, stop running ones), cleanup (delete orphaned clones and aggregators whose parent is gone) or preview (expand a matrix config into clone names without creating anything).",
|
|
1440
2304
|
options: { codemode: true },
|
|
1441
2305
|
execute: matrixControlExecute as any,
|
|
1442
2306
|
});
|
|
2307
|
+
|
|
2308
|
+
editor.add({
|
|
2309
|
+
name: "get_metrics",
|
|
2310
|
+
input: getMetricsSchema,
|
|
2311
|
+
description:
|
|
2312
|
+
"Returns aggregate run metrics: total runs, successes and failures across all tasks.",
|
|
2313
|
+
options: { codemode: true },
|
|
2314
|
+
execute: getMetricsExecute as any,
|
|
2315
|
+
});
|
|
2316
|
+
|
|
2317
|
+
editor.add({
|
|
2318
|
+
name: "get_analytics",
|
|
2319
|
+
input: getAnalyticsSchema,
|
|
2320
|
+
description:
|
|
2321
|
+
"Returns an analytics report for a period: run counts, success rate, duration, tokens and cost, plus top tasks.",
|
|
2322
|
+
options: { codemode: true },
|
|
2323
|
+
execute: getAnalyticsExecute as any,
|
|
2324
|
+
});
|
|
2325
|
+
|
|
2326
|
+
editor.add({
|
|
2327
|
+
name: "manage_settings",
|
|
2328
|
+
input: manageSettingsSchema,
|
|
2329
|
+
description:
|
|
2330
|
+
"Reads or updates global scheduler settings: maxConcurrent, winterMode, notifications (webhook, filters, matrix alerts, digest) and history retention. Updates are merged into the current settings.",
|
|
2331
|
+
options: { codemode: true },
|
|
2332
|
+
execute: manageSettingsExecute as any,
|
|
2333
|
+
});
|
|
2334
|
+
|
|
2335
|
+
editor.add({
|
|
2336
|
+
name: "manage_templates",
|
|
2337
|
+
input: manageTemplatesSchema,
|
|
2338
|
+
description:
|
|
2339
|
+
"Lists, saves or deletes reusable task templates (prompt, schedule, retries, Quality Gate, chains, triggers, tool restrictions).",
|
|
2340
|
+
options: { codemode: true },
|
|
2341
|
+
execute: manageTemplatesExecute as any,
|
|
2342
|
+
});
|
|
2343
|
+
|
|
2344
|
+
editor.add({
|
|
2345
|
+
name: "manage_profiles",
|
|
2346
|
+
input: manageProfilesSchema,
|
|
2347
|
+
description:
|
|
2348
|
+
"Lists, creates, switches or deletes isolated scheduler profiles (separate database, settings and dashboard port). Switching requires an OpenCode restart.",
|
|
2349
|
+
options: { codemode: true },
|
|
2350
|
+
execute: manageProfilesExecute as any,
|
|
2351
|
+
});
|
|
2352
|
+
|
|
2353
|
+
editor.add({
|
|
2354
|
+
name: "transfer_tasks",
|
|
2355
|
+
input: transferTasksSchema,
|
|
2356
|
+
description:
|
|
2357
|
+
"Exports all tasks as a portable JSON snapshot or imports tasks from such a snapshot, recreating them in the OS scheduler.",
|
|
2358
|
+
options: { codemode: true },
|
|
2359
|
+
execute: transferTasksExecute as any,
|
|
2360
|
+
});
|
|
2361
|
+
|
|
2362
|
+
editor.add({
|
|
2363
|
+
name: "send_notification",
|
|
2364
|
+
input: sendNotificationSchema,
|
|
2365
|
+
description:
|
|
2366
|
+
"Sends a test notification through the configured channel or sends the digest immediately.",
|
|
2367
|
+
options: { codemode: true },
|
|
2368
|
+
execute: sendNotificationExecute as any,
|
|
2369
|
+
});
|
|
2370
|
+
|
|
2371
|
+
editor.add({
|
|
2372
|
+
name: "get_dashboard_info",
|
|
2373
|
+
input: getDashboardInfoSchema,
|
|
2374
|
+
description:
|
|
2375
|
+
"Returns dashboard port and URL, OS platform, scheduler title and the active profile.",
|
|
2376
|
+
options: { codemode: true },
|
|
2377
|
+
execute: getDashboardInfoExecute as any,
|
|
2378
|
+
});
|
|
2379
|
+
|
|
2380
|
+
editor.add({
|
|
2381
|
+
name: "cleanup_history",
|
|
2382
|
+
input: cleanupHistorySchema,
|
|
2383
|
+
description:
|
|
2384
|
+
"Deletes old run history by age and/or record cap, using the stored retention policy unless overridden.",
|
|
2385
|
+
options: { codemode: true },
|
|
2386
|
+
execute: cleanupHistoryExecute as any,
|
|
2387
|
+
});
|
|
2388
|
+
|
|
2389
|
+
editor.add({
|
|
2390
|
+
name: "emit_event",
|
|
2391
|
+
input: emitEventSchema,
|
|
2392
|
+
description:
|
|
2393
|
+
"Emits an MCP event: every task with triggerType 'mcp-event' matching the event name (and filter) is started in priority order.",
|
|
2394
|
+
options: { codemode: true },
|
|
2395
|
+
execute: emitEventExecute as any,
|
|
2396
|
+
});
|
|
1443
2397
|
});
|
|
1444
2398
|
|
|
1445
2399
|
// Нативный скилл плагина: агент видит краткое описание в списке доступных
|
|
@@ -1499,6 +2453,9 @@ export default Plugin.define({
|
|
|
1499
2453
|
allowedTools,
|
|
1500
2454
|
deniedTools,
|
|
1501
2455
|
matrix,
|
|
2456
|
+
timezone,
|
|
2457
|
+
notBefore,
|
|
2458
|
+
notAfter,
|
|
1502
2459
|
} = input as {
|
|
1503
2460
|
name: string;
|
|
1504
2461
|
schedule: string;
|
|
@@ -1521,6 +2478,9 @@ export default Plugin.define({
|
|
|
1521
2478
|
allowedTools?: string[];
|
|
1522
2479
|
deniedTools?: string[];
|
|
1523
2480
|
matrix?: MatrixConfig;
|
|
2481
|
+
timezone?: string;
|
|
2482
|
+
notBefore?: string;
|
|
2483
|
+
notAfter?: string;
|
|
1524
2484
|
};
|
|
1525
2485
|
try {
|
|
1526
2486
|
await schedulerCreateTask(
|
|
@@ -1545,7 +2505,12 @@ export default Plugin.define({
|
|
|
1545
2505
|
workspaceId,
|
|
1546
2506
|
allowedTools,
|
|
1547
2507
|
deniedTools,
|
|
1548
|
-
matrix
|
|
2508
|
+
matrix,
|
|
2509
|
+
undefined,
|
|
2510
|
+
"create",
|
|
2511
|
+
timezone,
|
|
2512
|
+
notBefore,
|
|
2513
|
+
notAfter
|
|
1549
2514
|
);
|
|
1550
2515
|
return { success: true, message: `Задача "${name}" успешно создана.` };
|
|
1551
2516
|
} catch (err: any) {
|
|
@@ -1676,7 +2641,7 @@ export default Plugin.define({
|
|
|
1676
2641
|
const triggered: string[] = [];
|
|
1677
2642
|
for (const def of matched) {
|
|
1678
2643
|
try {
|
|
1679
|
-
await
|
|
2644
|
+
await runTaskEntry(def.name);
|
|
1680
2645
|
triggered.push(def.name);
|
|
1681
2646
|
console.log(
|
|
1682
2647
|
`[windows-scheduler] Запуск задачи "${def.name}" по MCP-событию "${normalized}".`
|
|
@@ -1697,8 +2662,8 @@ export default Plugin.define({
|
|
|
1697
2662
|
};
|
|
1698
2663
|
},
|
|
1699
2664
|
pause_task: async (input: unknown) => {
|
|
1700
|
-
const { name } = input as { name: string };
|
|
1701
|
-
const result = await pauseOrResumeTask(name, true);
|
|
2665
|
+
const { name, until } = input as { name: string; until?: string };
|
|
2666
|
+
const result = await pauseOrResumeTask(name, true, until);
|
|
1702
2667
|
return { success: result.success, message: result.message };
|
|
1703
2668
|
},
|
|
1704
2669
|
resume_task: async (input: unknown) => {
|
|
@@ -1718,13 +2683,80 @@ export default Plugin.define({
|
|
|
1718
2683
|
return { success: true, logs: result.logs };
|
|
1719
2684
|
},
|
|
1720
2685
|
get_history: async (input: unknown) => {
|
|
1721
|
-
const { limit } = input as { limit?: number };
|
|
1722
|
-
const
|
|
2686
|
+
const { limit, taskName } = input as { limit?: number; taskName?: string };
|
|
2687
|
+
const filter = taskName?.trim().toLowerCase();
|
|
2688
|
+
const records = (await loadHistory()).filter(
|
|
2689
|
+
(record) => !filter || record.taskName.toLowerCase() === filter
|
|
2690
|
+
);
|
|
1723
2691
|
return { records: records.slice(0, limit ?? 10) };
|
|
1724
2692
|
},
|
|
1725
2693
|
get_metrics: async () => {
|
|
1726
2694
|
return await loadMetrics();
|
|
1727
2695
|
},
|
|
2696
|
+
cleanup_history: async (input: unknown) => {
|
|
2697
|
+
const { retentionDays, maxRecords } = input as {
|
|
2698
|
+
retentionDays?: number;
|
|
2699
|
+
maxRecords?: number;
|
|
2700
|
+
};
|
|
2701
|
+
try {
|
|
2702
|
+
const report = await runHistoryRetention({ retentionDays, maxRecords });
|
|
2703
|
+
const message = report.skipped
|
|
2704
|
+
? report.skipped
|
|
2705
|
+
: `Удалено ${report.deleted} записей (по возрасту: ${report.deletedByAge}, по лимиту: ` +
|
|
2706
|
+
`${report.deletedByCount}), осталось ${report.kept}.`;
|
|
2707
|
+
return {
|
|
2708
|
+
success: true,
|
|
2709
|
+
message,
|
|
2710
|
+
deleted: report.deleted,
|
|
2711
|
+
deletedByAge: report.deletedByAge,
|
|
2712
|
+
deletedByCount: report.deletedByCount,
|
|
2713
|
+
kept: report.kept,
|
|
2714
|
+
retentionDays: report.retentionDays,
|
|
2715
|
+
maxRecords: report.maxRecords,
|
|
2716
|
+
vacuumed: report.vacuumed,
|
|
2717
|
+
};
|
|
2718
|
+
} catch (err: any) {
|
|
2719
|
+
return {
|
|
2720
|
+
success: false,
|
|
2721
|
+
message: `Не удалось очистить историю: ${
|
|
2722
|
+
err instanceof Error ? err.message : String(err)
|
|
2723
|
+
}`,
|
|
2724
|
+
deleted: 0,
|
|
2725
|
+
deletedByAge: 0,
|
|
2726
|
+
deletedByCount: 0,
|
|
2727
|
+
kept: 0,
|
|
2728
|
+
retentionDays: 0,
|
|
2729
|
+
maxRecords: 0,
|
|
2730
|
+
vacuumed: false,
|
|
2731
|
+
};
|
|
2732
|
+
}
|
|
2733
|
+
},
|
|
2734
|
+
get_analytics: async (input: unknown) => {
|
|
2735
|
+
const { days, topLimit } = input as { days?: number; topLimit?: number };
|
|
2736
|
+
try {
|
|
2737
|
+
const windowDays = Math.min(
|
|
2738
|
+
365,
|
|
2739
|
+
Math.max(1, Math.floor(Number(days) || 14))
|
|
2740
|
+
);
|
|
2741
|
+
const records = getHistory(null, 20000);
|
|
2742
|
+
const definitions = await loadTaskDefinitions();
|
|
2743
|
+
const report = buildAnalytics(records, {
|
|
2744
|
+
days: windowDays,
|
|
2745
|
+
topLimit: Math.max(1, Math.floor(Number(topLimit) || 10)),
|
|
2746
|
+
tasks: definitions.map((definition) => ({
|
|
2747
|
+
name: definition.name,
|
|
2748
|
+
matrixParentId: definition.matrixParentId,
|
|
2749
|
+
})),
|
|
2750
|
+
});
|
|
2751
|
+
return { success: true, report };
|
|
2752
|
+
} catch (err: any) {
|
|
2753
|
+
return {
|
|
2754
|
+
success: false,
|
|
2755
|
+
report: null,
|
|
2756
|
+
error: err instanceof Error ? err.message : String(err),
|
|
2757
|
+
};
|
|
2758
|
+
}
|
|
2759
|
+
},
|
|
1728
2760
|
get_dashboard_port: async () => {
|
|
1729
2761
|
return { port: getDashboardPort() };
|
|
1730
2762
|
},
|
|
@@ -1826,36 +2858,57 @@ export default Plugin.define({
|
|
|
1826
2858
|
return {
|
|
1827
2859
|
workspaces: listWorkspaces().map((workspace) => ({
|
|
1828
2860
|
...workspace,
|
|
2861
|
+
env: maskEnvForLog(workspace.env),
|
|
1829
2862
|
gitBranch: readGitBranch(workspace.path) ?? null,
|
|
1830
2863
|
})),
|
|
1831
2864
|
};
|
|
1832
2865
|
},
|
|
1833
2866
|
add_workspace: async (input: unknown) => {
|
|
1834
2867
|
try {
|
|
1835
|
-
const { name, path: workspacePath, color } = input as {
|
|
2868
|
+
const { name, path: workspacePath, color, env, envFile } = input as {
|
|
1836
2869
|
name?: string;
|
|
1837
2870
|
path: string;
|
|
1838
2871
|
color?: string;
|
|
2872
|
+
env?: Record<string, string> | null;
|
|
2873
|
+
envFile?: string | null;
|
|
2874
|
+
};
|
|
2875
|
+
const workspace = addWorkspace({ name, path: workspacePath, color, env, envFile });
|
|
2876
|
+
return {
|
|
2877
|
+
success: true,
|
|
2878
|
+
workspace: {
|
|
2879
|
+
...workspace,
|
|
2880
|
+
env: maskEnvForLog(workspace.env),
|
|
2881
|
+
gitBranch: readGitBranch(workspace.path) ?? null,
|
|
2882
|
+
},
|
|
1839
2883
|
};
|
|
1840
|
-
const workspace = addWorkspace({ name, path: workspacePath, color });
|
|
1841
|
-
return { success: true, workspace: { ...workspace, gitBranch: readGitBranch(workspace.path) ?? null } };
|
|
1842
2884
|
} catch (err: any) {
|
|
1843
2885
|
return { success: false, error: err instanceof Error ? err.message : String(err) };
|
|
1844
2886
|
}
|
|
1845
2887
|
},
|
|
1846
2888
|
update_workspace: async (input: unknown) => {
|
|
1847
2889
|
try {
|
|
1848
|
-
const { id, name, path: workspacePath, color } = input as {
|
|
2890
|
+
const { id, name, path: workspacePath, color, env, envFile } = input as {
|
|
1849
2891
|
id: string;
|
|
1850
2892
|
name?: string;
|
|
1851
2893
|
path?: string;
|
|
1852
2894
|
color?: string;
|
|
2895
|
+
env?: Record<string, string> | null;
|
|
2896
|
+
envFile?: string | null;
|
|
1853
2897
|
};
|
|
1854
|
-
const workspace = updateWorkspace(id, { name, path: workspacePath, color });
|
|
2898
|
+
const workspace = updateWorkspace(id, { name, path: workspacePath, color, env, envFile });
|
|
1855
2899
|
if (!workspace) {
|
|
1856
2900
|
return { success: false, error: "Workspace не найден." };
|
|
1857
2901
|
}
|
|
1858
|
-
|
|
2902
|
+
// env-файлы существующих задач перегенерируются сразу (Спринт 21).
|
|
2903
|
+
await refreshWorkspaceEnvFiles(workspace.id);
|
|
2904
|
+
return {
|
|
2905
|
+
success: true,
|
|
2906
|
+
workspace: {
|
|
2907
|
+
...workspace,
|
|
2908
|
+
env: maskEnvForLog(workspace.env),
|
|
2909
|
+
gitBranch: readGitBranch(workspace.path) ?? null,
|
|
2910
|
+
},
|
|
2911
|
+
};
|
|
1859
2912
|
} catch (err: any) {
|
|
1860
2913
|
return { success: false, error: err instanceof Error ? err.message : String(err) };
|
|
1861
2914
|
}
|
|
@@ -1874,39 +2927,118 @@ export default Plugin.define({
|
|
|
1874
2927
|
return { success: false, message: err instanceof Error ? err.message : String(err) };
|
|
1875
2928
|
}
|
|
1876
2929
|
},
|
|
2930
|
+
get_profiles: async () => {
|
|
2931
|
+
return {
|
|
2932
|
+
current: getProfileName(),
|
|
2933
|
+
pinnedByEnv: isProfilePinnedByEnv(),
|
|
2934
|
+
profiles: listProfiles(),
|
|
2935
|
+
};
|
|
2936
|
+
},
|
|
2937
|
+
set_profile: async (input: unknown) => {
|
|
2938
|
+
const { name } = input as { name: string };
|
|
2939
|
+
try {
|
|
2940
|
+
setActiveProfile(name);
|
|
2941
|
+
const current = getProfileName();
|
|
2942
|
+
return {
|
|
2943
|
+
success: true,
|
|
2944
|
+
current,
|
|
2945
|
+
restartRequired: true,
|
|
2946
|
+
message: isProfilePinnedByEnv()
|
|
2947
|
+
? `Профиль задан переменной OPENCODE_SCHEDULER_PROFILE=${current}. Перезапустите OpenCode, чтобы применить изменения.`
|
|
2948
|
+
: `Активный профиль: ${sanitizeProfileName(name)}. Перезапустите OpenCode, чтобы применить изменения.`,
|
|
2949
|
+
};
|
|
2950
|
+
} catch (err: any) {
|
|
2951
|
+
return {
|
|
2952
|
+
success: false,
|
|
2953
|
+
current: getProfileName(),
|
|
2954
|
+
restartRequired: false,
|
|
2955
|
+
message: err instanceof Error ? err.message : String(err),
|
|
2956
|
+
};
|
|
2957
|
+
}
|
|
2958
|
+
},
|
|
2959
|
+
create_profile: async (input: unknown) => {
|
|
2960
|
+
const { name, port } = input as { name: string; port?: number };
|
|
2961
|
+
try {
|
|
2962
|
+
const meta = createProfile(name, port);
|
|
2963
|
+
const profile = listProfiles().find((item) => item.name === meta.name);
|
|
2964
|
+
return {
|
|
2965
|
+
success: true,
|
|
2966
|
+
message: `Профиль "${meta.name}" создан (порт дашборда ${meta.port}).`,
|
|
2967
|
+
profile: profile ?? {
|
|
2968
|
+
name: meta.name,
|
|
2969
|
+
dir: getProfileDir(meta.name),
|
|
2970
|
+
port: meta.port,
|
|
2971
|
+
isDefault: meta.name === DEFAULT_PROFILE,
|
|
2972
|
+
active: meta.name === getProfileName(),
|
|
2973
|
+
},
|
|
2974
|
+
};
|
|
2975
|
+
} catch (err: any) {
|
|
2976
|
+
return {
|
|
2977
|
+
success: false,
|
|
2978
|
+
error: err instanceof Error ? err.message : String(err),
|
|
2979
|
+
};
|
|
2980
|
+
}
|
|
2981
|
+
},
|
|
2982
|
+
delete_profile: async (input: unknown) => {
|
|
2983
|
+
const { name } = input as { name: string };
|
|
2984
|
+
try {
|
|
2985
|
+
const removed = deleteProfile(name);
|
|
2986
|
+
return {
|
|
2987
|
+
success: removed,
|
|
2988
|
+
message: removed
|
|
2989
|
+
? `Профиль "${sanitizeProfileName(name)}" удалён вместе с его БД и настройками.`
|
|
2990
|
+
: "Профиль не найден.",
|
|
2991
|
+
};
|
|
2992
|
+
} catch (err: any) {
|
|
2993
|
+
return { success: false, message: err instanceof Error ? err.message : String(err) };
|
|
2994
|
+
}
|
|
2995
|
+
},
|
|
1877
2996
|
get_settings: async () => {
|
|
1878
2997
|
return await loadSettings();
|
|
1879
2998
|
},
|
|
1880
2999
|
save_settings: async (input: unknown) => {
|
|
1881
|
-
const { maxConcurrent, winterMode, notifications } = input as {
|
|
3000
|
+
const { maxConcurrent, winterMode, notifications, history } = input as {
|
|
1882
3001
|
maxConcurrent?: number;
|
|
1883
3002
|
winterMode?: boolean;
|
|
1884
3003
|
notifications?: NotificationSettings;
|
|
3004
|
+
history?: HistorySettings;
|
|
1885
3005
|
};
|
|
1886
3006
|
const current = await loadSettings();
|
|
1887
3007
|
if (
|
|
1888
3008
|
maxConcurrent === undefined &&
|
|
1889
3009
|
winterMode === undefined &&
|
|
1890
|
-
notifications === undefined
|
|
3010
|
+
notifications === undefined &&
|
|
3011
|
+
history === undefined
|
|
1891
3012
|
) {
|
|
1892
3013
|
return {
|
|
1893
3014
|
success: false,
|
|
1894
3015
|
maxConcurrent: current.maxConcurrent,
|
|
1895
3016
|
winterMode: current.winterMode,
|
|
1896
3017
|
notifications: current.notifications,
|
|
3018
|
+
history: current.history,
|
|
1897
3019
|
};
|
|
1898
3020
|
}
|
|
1899
|
-
const settings = await saveSettings({
|
|
3021
|
+
const settings = await saveSettings({
|
|
3022
|
+
maxConcurrent,
|
|
3023
|
+
winterMode,
|
|
3024
|
+
notifications,
|
|
3025
|
+
history,
|
|
3026
|
+
});
|
|
1900
3027
|
return {
|
|
1901
3028
|
success: true,
|
|
1902
3029
|
maxConcurrent: settings.maxConcurrent,
|
|
1903
3030
|
winterMode: settings.winterMode,
|
|
1904
3031
|
notifications: settings.notifications,
|
|
3032
|
+
history: settings.history,
|
|
1905
3033
|
};
|
|
1906
3034
|
},
|
|
1907
3035
|
test_notification: async () => {
|
|
1908
3036
|
return await sendTestNotification();
|
|
1909
3037
|
},
|
|
3038
|
+
send_digest: async () => {
|
|
3039
|
+
// Ручная отправка не сдвигает плановое расписание дайджеста.
|
|
3040
|
+
return await sendDigestNow({ updateLastSentAt: false });
|
|
3041
|
+
},
|
|
1910
3042
|
get_templates: async () => {
|
|
1911
3043
|
try {
|
|
1912
3044
|
return { templates: await loadTemplates() };
|
|
@@ -2019,7 +3151,12 @@ export default Plugin.define({
|
|
|
2019
3151
|
def.allowedTools,
|
|
2020
3152
|
def.deniedTools,
|
|
2021
3153
|
def.matrix,
|
|
2022
|
-
def.matrixParentId
|
|
3154
|
+
def.matrixParentId,
|
|
3155
|
+
"create",
|
|
3156
|
+
def.timezone,
|
|
3157
|
+
def.notBefore,
|
|
3158
|
+
def.notAfter,
|
|
3159
|
+
def.pausedUntil
|
|
2023
3160
|
);
|
|
2024
3161
|
await saveTaskDefinition(def);
|
|
2025
3162
|
imported.push(def.name);
|
|
@@ -2068,10 +3205,12 @@ export default Plugin.define({
|
|
|
2068
3205
|
}
|
|
2069
3206
|
|
|
2070
3207
|
return () => {
|
|
3208
|
+
clearInterval(pausedUntilTimer);
|
|
3209
|
+
clearInterval(notificationTimer);
|
|
2071
3210
|
rpcRegistration.dispose();
|
|
2072
3211
|
registration.dispose();
|
|
2073
3212
|
void skillRegistration?.dispose();
|
|
2074
|
-
void fileWatcherManager.stop();
|
|
3213
|
+
if (fileWatcherManager) void fileWatcherManager.stop();
|
|
2075
3214
|
// При выгрузке плагина обязательно закрываем HTTP-сервер дашборда,
|
|
2076
3215
|
// затем соединение SQLite (чекпойнт WAL выполняется в closeDb).
|
|
2077
3216
|
void closeDashboardServer().finally(() => closeDb());
|
|
@@ -2166,12 +3305,24 @@ async function schedulerCreateTask(
|
|
|
2166
3305
|
matrix?: MatrixConfig,
|
|
2167
3306
|
matrixParentId?: string,
|
|
2168
3307
|
/** create — пересоздать клонов с нуля; sync — только diff (Спринт 17). */
|
|
2169
|
-
matrixMode: "create" | "sync" = "create"
|
|
3308
|
+
matrixMode: "create" | "sync" = "create",
|
|
3309
|
+
/** IANA-зона задачи (Спринт 19). Не системная зона → poll-режим шлюза. */
|
|
3310
|
+
timezone?: string,
|
|
3311
|
+
/** Окно запуска: начало "HH:MM" (вне окна запуск переносится). */
|
|
3312
|
+
notBefore?: string,
|
|
3313
|
+
/** Окончание окна "HH:MM"; может быть меньше notBefore (через полночь). */
|
|
3314
|
+
notAfter?: string,
|
|
3315
|
+
/** Пауза до момента ISO; после него задача возобновляется автоматически. */
|
|
3316
|
+
pausedUntil?: string
|
|
2170
3317
|
): Promise<void> {
|
|
2171
3318
|
const normalizedModel = model?.trim() || undefined;
|
|
2172
3319
|
const normalizedPriority = normalizePriority(priority);
|
|
2173
3320
|
const normalizedBefore = beforeScript?.trim() || undefined;
|
|
2174
3321
|
const normalizedAfter = afterScript?.trim() || undefined;
|
|
3322
|
+
const normalizedTz = timezone?.trim() || undefined;
|
|
3323
|
+
const normalizedNotBefore = notBefore?.trim() || undefined;
|
|
3324
|
+
const normalizedNotAfter = notAfter?.trim() || undefined;
|
|
3325
|
+
const normalizedPausedUntil = pausedUntil?.trim() || undefined;
|
|
2175
3326
|
const normalizedMcpEvent =
|
|
2176
3327
|
mcpEvent && mcpEvent.event?.trim()
|
|
2177
3328
|
? {
|
|
@@ -2262,15 +3413,49 @@ async function schedulerCreateTask(
|
|
|
2262
3413
|
// расписание не используется вовсе.
|
|
2263
3414
|
if (effectiveTriggerType === "cron") {
|
|
2264
3415
|
try {
|
|
2265
|
-
|
|
3416
|
+
// Расширенная грамматика (Спринт 19): диапазоны, списки, шаги,
|
|
3417
|
+
// имена месяцев/дней, @every, L и FRI#3.
|
|
3418
|
+
parseCron(schedule);
|
|
2266
3419
|
} catch (err: any) {
|
|
2267
3420
|
throw new Error(err.message || String(err));
|
|
2268
3421
|
}
|
|
3422
|
+
if (normalizedTz && !isValidIanaTimeZone(normalizedTz)) {
|
|
3423
|
+
throw new Error(
|
|
3424
|
+
`Задача "${name}": неизвестный часовой пояс "${normalizedTz}". ` +
|
|
3425
|
+
`Укажите IANA-зону, например Europe/Moscow.`
|
|
3426
|
+
);
|
|
3427
|
+
}
|
|
3428
|
+
const windowError = validateLaunchWindow(
|
|
3429
|
+
normalizedNotBefore,
|
|
3430
|
+
normalizedNotAfter
|
|
3431
|
+
);
|
|
3432
|
+
if (windowError) {
|
|
3433
|
+
throw new Error(`Задача "${name}": ${windowError}`);
|
|
3434
|
+
}
|
|
2269
3435
|
}
|
|
2270
3436
|
|
|
2271
3437
|
const sanitized = sanitizeName(name);
|
|
2272
3438
|
const lockFile = lockFilePath(sanitized);
|
|
2273
3439
|
const logFile = path.join(LOG_DIR, `${sanitized}.log`);
|
|
3440
|
+
// Шлюз расписания (Спринт 19): нужен только для cron в poll-режиме
|
|
3441
|
+
// (нестандартный cron или чужая IANA-зона) либо при окне запуска.
|
|
3442
|
+
const gate =
|
|
3443
|
+
effectiveTriggerType === "cron"
|
|
3444
|
+
? buildScheduleGate(
|
|
3445
|
+
schedule,
|
|
3446
|
+
normalizedTz,
|
|
3447
|
+
normalizedNotBefore,
|
|
3448
|
+
normalizedNotAfter
|
|
3449
|
+
)
|
|
3450
|
+
: undefined;
|
|
3451
|
+
const wrapperGate = gate
|
|
3452
|
+
? {
|
|
3453
|
+
...gate,
|
|
3454
|
+
gateFile: gatePath,
|
|
3455
|
+
deferFile: `${lockFile}.defer`,
|
|
3456
|
+
forceFile: `${lockFile}.force`,
|
|
3457
|
+
}
|
|
3458
|
+
: undefined;
|
|
2274
3459
|
// Workspace имеет приоритет над workingDirectory: одна задача = один repo
|
|
2275
3460
|
// = один cwd. Мы не угадываем, куда мержить, и не смешиваем контексты.
|
|
2276
3461
|
const normalizedWorkspaceId = workspaceId?.trim() || undefined;
|
|
@@ -2294,6 +3479,13 @@ async function schedulerCreateTask(
|
|
|
2294
3479
|
const effectiveWorkingDirectory =
|
|
2295
3480
|
workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
|
|
2296
3481
|
|
|
3482
|
+
// Спринт 21: env-переменные workspace → отдельный файл, который читает обёртка.
|
|
3483
|
+
// Значения не логируются; в лог попадает только факт загрузки.
|
|
3484
|
+
const taskEnvFile = writeWorkspaceEnvFile(workspace, PLUGIN_DIR, sanitized);
|
|
3485
|
+
if (taskEnvFile) {
|
|
3486
|
+
console.log(`[workspace] Задача "${name}": env-переменные workspace подключены.`);
|
|
3487
|
+
}
|
|
3488
|
+
|
|
2297
3489
|
let promptFile: string;
|
|
2298
3490
|
try {
|
|
2299
3491
|
promptFile = await writePromptFile(sanitized, prompt);
|
|
@@ -2325,7 +3517,9 @@ async function schedulerCreateTask(
|
|
|
2325
3517
|
normalizedAfter,
|
|
2326
3518
|
workspace?.name,
|
|
2327
3519
|
normalizedAllowedTools,
|
|
2328
|
-
normalizedDeniedTools
|
|
3520
|
+
normalizedDeniedTools,
|
|
3521
|
+
wrapperGate,
|
|
3522
|
+
taskEnvFile
|
|
2329
3523
|
);
|
|
2330
3524
|
} else {
|
|
2331
3525
|
wrapperPath = await writeBashWrapper({
|
|
@@ -2344,6 +3538,8 @@ async function schedulerCreateTask(
|
|
|
2344
3538
|
workspaceName: workspace?.name,
|
|
2345
3539
|
allowedTools: normalizedAllowedTools,
|
|
2346
3540
|
deniedTools: normalizedDeniedTools,
|
|
3541
|
+
scheduleGate: wrapperGate,
|
|
3542
|
+
envFile: taskEnvFile,
|
|
2347
3543
|
});
|
|
2348
3544
|
}
|
|
2349
3545
|
} catch (err: any) {
|
|
@@ -2362,6 +3558,9 @@ async function schedulerCreateTask(
|
|
|
2362
3558
|
logFile,
|
|
2363
3559
|
model: normalizedModel,
|
|
2364
3560
|
priority: normalizedPriority,
|
|
3561
|
+
timezone: normalizedTz,
|
|
3562
|
+
notBefore: normalizedNotBefore,
|
|
3563
|
+
notAfter: normalizedNotAfter,
|
|
2365
3564
|
});
|
|
2366
3565
|
} catch (err: any) {
|
|
2367
3566
|
throw new Error(err instanceof Error ? err.message : String(err));
|
|
@@ -2388,6 +3587,10 @@ async function schedulerCreateTask(
|
|
|
2388
3587
|
nextTaskOnError,
|
|
2389
3588
|
triggerType: effectiveTriggerType,
|
|
2390
3589
|
watchPath: normalizedMatrix ? undefined : watchPath,
|
|
3590
|
+
timezone: normalizedTz,
|
|
3591
|
+
notBefore: normalizedNotBefore,
|
|
3592
|
+
notAfter: normalizedNotAfter,
|
|
3593
|
+
pausedUntil: normalizedPausedUntil,
|
|
2391
3594
|
allowedTools: normalizedAllowedTools,
|
|
2392
3595
|
deniedTools: normalizedDeniedTools,
|
|
2393
3596
|
matrix: normalizedMatrix,
|
|
@@ -2444,7 +3647,12 @@ async function schedulerCreateTask(
|
|
|
2444
3647
|
clone.allowedTools,
|
|
2445
3648
|
clone.deniedTools,
|
|
2446
3649
|
undefined,
|
|
2447
|
-
name
|
|
3650
|
+
name,
|
|
3651
|
+
"create",
|
|
3652
|
+
clone.timezone,
|
|
3653
|
+
clone.notBefore,
|
|
3654
|
+
clone.notAfter,
|
|
3655
|
+
clone.pausedUntil
|
|
2448
3656
|
);
|
|
2449
3657
|
};
|
|
2450
3658
|
|
|
@@ -2537,7 +3745,22 @@ async function runTaskEntry(name: string): Promise<{ alreadyRunning: boolean }>
|
|
|
2537
3745
|
await runMatrix(definition);
|
|
2538
3746
|
return { alreadyRunning: false };
|
|
2539
3747
|
}
|
|
2540
|
-
|
|
3748
|
+
|
|
3749
|
+
// Любой запуск через этот вход — «сейчас», а не «по расписанию»:
|
|
3750
|
+
// run_task_now, RPC GUI, файловый триггер, MCP-событие и catch-up.
|
|
3751
|
+
// Маркер снимает проверку cron/окна внутри обёртки (poll-режим), иначе
|
|
3752
|
+
// запуск молча отменялся бы schedule-gate с кодом 3.
|
|
3753
|
+
const forceFile = await requestImmediateRun(name);
|
|
3754
|
+
try {
|
|
3755
|
+
return await scheduler.runTask(name);
|
|
3756
|
+
} catch (err) {
|
|
3757
|
+
// Планировщик не принял запуск — маркер не нужен, иначе он мог бы
|
|
3758
|
+
// «разрешить» следующий плановый тик в обход расписания.
|
|
3759
|
+
await fs.unlink(forceFile).catch(() => {
|
|
3760
|
+
/* не критично */
|
|
3761
|
+
});
|
|
3762
|
+
throw err;
|
|
3763
|
+
}
|
|
2541
3764
|
}
|
|
2542
3765
|
|
|
2543
3766
|
/**
|
|
@@ -2562,7 +3785,39 @@ async function collectTasksView() {
|
|
|
2562
3785
|
const workspaces = listWorkspaces();
|
|
2563
3786
|
const workspaceById = new Map(workspaces.map((workspace) => [workspace.id, workspace]));
|
|
2564
3787
|
|
|
2565
|
-
|
|
3788
|
+
// Счётчики запусков по задачам. Основной источник — таблица metrics
|
|
3789
|
+
// (накопительные итоги, не зависят от retention истории). Для задач, у
|
|
3790
|
+
// которых метрик ещё нет, считаем по загруженной истории.
|
|
3791
|
+
const metricsByName = new Map(
|
|
3792
|
+
getAllMetrics(true).map((row) => [row.taskName.toLowerCase(), row])
|
|
3793
|
+
);
|
|
3794
|
+
const historyCounts = new Map<string, { total: number; success: number; error: number }>();
|
|
3795
|
+
for (const record of history) {
|
|
3796
|
+
const key = record.taskName.toLowerCase();
|
|
3797
|
+
const counts = historyCounts.get(key) ?? { total: 0, success: 0, error: 0 };
|
|
3798
|
+
counts.total += 1;
|
|
3799
|
+
if (record.status === "success") counts.success += 1;
|
|
3800
|
+
else counts.error += 1;
|
|
3801
|
+
historyCounts.set(key, counts);
|
|
3802
|
+
}
|
|
3803
|
+
|
|
3804
|
+
// ОС-планировщик — источник истины о запуске, но определения в БД могут
|
|
3805
|
+
// существовать без задачи в ОС (сбой удаления, миграция, ручная чистка).
|
|
3806
|
+
// Показываем и их, помечая orphaned: раньше такие задачи были невидимы
|
|
3807
|
+
// для list_tasks, хотя dry_run/история их видели.
|
|
3808
|
+
const osNames = new Set(tasks.map((t) => (t.taskName || "").toLowerCase()));
|
|
3809
|
+
const orphanNames = defs
|
|
3810
|
+
.filter((def) => !osNames.has(def.name.toLowerCase()))
|
|
3811
|
+
.map((def) => def.name);
|
|
3812
|
+
const sources: Array<{ task: (typeof tasks)[number]; orphaned: boolean }> = [
|
|
3813
|
+
...tasks.map((task) => ({ task, orphaned: false })),
|
|
3814
|
+
...orphanNames.map((name) => ({
|
|
3815
|
+
task: { taskName: name } as (typeof tasks)[number],
|
|
3816
|
+
orphaned: true,
|
|
3817
|
+
})),
|
|
3818
|
+
];
|
|
3819
|
+
|
|
3820
|
+
return sources.map(({ task: t, orphaned }) => {
|
|
2566
3821
|
// Все бэкенды возвращают короткие имена (без папки планировщика).
|
|
2567
3822
|
const name = t.taskName || "";
|
|
2568
3823
|
|
|
@@ -2586,10 +3841,21 @@ async function collectTasksView() {
|
|
|
2586
3841
|
status = matrixAggregate.status === "running" ? "running" : matrixAggregate.status;
|
|
2587
3842
|
}
|
|
2588
3843
|
|
|
3844
|
+
// Счётчики именно этой задачи (раньше GUI показывал на каждой карточке
|
|
3845
|
+
// общие итоги по всем задачам — отсюда одинаковые 201/130/71).
|
|
3846
|
+
const metricsRow = metricsByName.get(name.toLowerCase());
|
|
3847
|
+
const counts = metricsRow
|
|
3848
|
+
? { total: metricsRow.total, success: metricsRow.success, error: metricsRow.error }
|
|
3849
|
+
: historyCounts.get(name.toLowerCase()) ?? { total: 0, success: 0, error: 0 };
|
|
3850
|
+
|
|
2589
3851
|
return {
|
|
2590
3852
|
name,
|
|
2591
3853
|
schedule: def?.schedule ?? "",
|
|
2592
3854
|
status,
|
|
3855
|
+
orphaned,
|
|
3856
|
+
runsTotal: counts.total,
|
|
3857
|
+
runsSuccess: counts.success,
|
|
3858
|
+
runsError: counts.error,
|
|
2593
3859
|
nextRun: t.nextRunTime ? String(t.nextRunTime) : null,
|
|
2594
3860
|
model: def?.model ?? null,
|
|
2595
3861
|
priority: def?.priority ?? 5,
|
|
@@ -2604,6 +3870,10 @@ async function collectTasksView() {
|
|
|
2604
3870
|
dependsOn: Array.isArray(def?.dependsOn) ? def.dependsOn : [],
|
|
2605
3871
|
triggerType: def?.triggerType ?? "cron",
|
|
2606
3872
|
watchPath: def?.watchPath ?? null,
|
|
3873
|
+
timezone: def?.timezone ?? null,
|
|
3874
|
+
notBefore: def?.notBefore ?? null,
|
|
3875
|
+
notAfter: def?.notAfter ?? null,
|
|
3876
|
+
pausedUntil: def?.pausedUntil ?? null,
|
|
2607
3877
|
workingDirectory: workspace?.path ?? def?.workingDirectory ?? def?.workdir ?? null,
|
|
2608
3878
|
workspaceId: workspace?.id ?? def?.workspaceId ?? null,
|
|
2609
3879
|
workspaceName: workspace?.name ?? null,
|