opencode-windows-scheduler 1.1.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 +45 -1
- package/README.md +13 -3
- package/README.ru.md +13 -3
- package/ROADMAP.md +20 -13
- package/dist/core/analytics.d.ts +10 -0
- package/dist/core/analytics.d.ts.map +1 -1
- package/dist/core/analytics.js +21 -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/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 +8 -0
- package/dist/db/history-repo.d.ts.map +1 -1
- package/dist/db/history-repo.js +13 -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 +1010 -54
- 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 +511 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +190 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +5 -2
- package/dist/settings.d.ts +57 -0
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +118 -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/workspaces.d.ts +43 -0
- package/dist/workspaces.d.ts.map +1 -1
- package/dist/workspaces.js +174 -8
- package/docs/ARCHITECTURE.md +32 -12
- package/docs/FEATURES.md +86 -7
- package/gui-experimental.cjs +4 -2
- package/package.json +6 -2
- package/src/core/analytics.ts +36 -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/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 +23 -0
- package/src/db/schema.ts +14 -0
- package/src/gui.tsx +767 -22
- package/src/index.ts +1226 -52
- package/src/notifications.ts +516 -40
- package/src/profiles.ts +236 -0
- package/src/rpc.ts +201 -2
- package/src/server.ts +5 -2
- package/src/settings.ts +214 -9
- package/src/task-transfer.ts +44 -0
- package/src/types.ts +3 -13
- package/src/workspaces.ts +214 -8
package/dist/index.js
CHANGED
|
@@ -5,9 +5,9 @@ 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, sanitizeName } from "./types.js";
|
|
9
|
-
import {
|
|
10
|
-
import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath } from "./core/ps-wrapper.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";
|
|
10
|
+
import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath, requestImmediateRun } from "./core/ps-wrapper.js";
|
|
11
11
|
import { getSchedulerBackend } from "./core/scheduler/index.js";
|
|
12
12
|
import { SCHEDULER_SKILL_ID, loadSchedulerSkill } from "./skill.js";
|
|
13
13
|
import { getTaskLogs } from "./core/scheduler/logs.js";
|
|
@@ -19,17 +19,19 @@ import { loadHistory, loadMetrics } from "./history.js";
|
|
|
19
19
|
import { loadSettings, saveSettings } from "./settings.js";
|
|
20
20
|
import { runHistoryRetention, maybeRunHistoryRetention } from "./core/retention.js";
|
|
21
21
|
import { buildAnalytics } from "./core/analytics.js";
|
|
22
|
-
import { getHistory } from "./db/history-repo.js";
|
|
23
|
-
import {
|
|
22
|
+
import { getHistory, listRunningRecords } from "./db/history-repo.js";
|
|
23
|
+
import { getAllMetrics } from "./db/metrics-repo.js";
|
|
24
|
+
import { findStuckMatrixClones, maybeSendDigest, notifyStuckMatrix, sendDigestNow, sendTestNotification, } from "./notifications.js";
|
|
24
25
|
import { loadTaskDefinitions, saveTaskDefinition, removeTaskDefinition, buildExportJson, parseImportJson, normalizePriority, } from "./task-transfer.js";
|
|
25
26
|
import { FileWatchManager } from "./core/file-watcher.js";
|
|
26
27
|
import { loadTemplates, saveTemplate, deleteTemplate } from "./templates.js";
|
|
27
28
|
import { startDashboardServer, closeDashboardServer, getDashboardPort } from "./server.js";
|
|
29
|
+
import { DEFAULT_PROFILE, createProfile, deleteProfile, getProfileDir, getProfileName, isProfilePinnedByEnv, listProfiles, sanitizeProfileName, setActiveProfile, } from "./profiles.js";
|
|
28
30
|
import { closeDb, initDb } from "./db/index.js";
|
|
29
31
|
import { migrateJsonToDb } from "./db/migrate.js";
|
|
30
32
|
import { checkJsonBackups, recoverInterruptedRuns } from "./db/recovery.js";
|
|
31
|
-
import { getTask, listMatrixClones } from "./db/tasks-repo.js";
|
|
32
|
-
import { addWorkspace, deleteWorkspace, getWorkspace, listWorkspaces, updateWorkspace, validateWorkspacePath, readGitBranch, } from "./workspaces.js";
|
|
33
|
+
import { getTask, listMatrixClones, saveTask } from "./db/tasks-repo.js";
|
|
34
|
+
import { addWorkspace, deleteWorkspace, getWorkspace, listWorkspaces, updateWorkspace, validateWorkspacePath, readGitBranch, writeWorkspaceEnvFile, maskEnvForLog, } from "./workspaces.js";
|
|
33
35
|
// Путь к вспомогательному node-скрипту записи истории/метрик (dist/core/record-history.js).
|
|
34
36
|
const require = createRequire(import.meta.url);
|
|
35
37
|
const resolvedRecorder = require.resolve("./core/record-history.js");
|
|
@@ -50,6 +52,23 @@ const recorderPath = (() => {
|
|
|
50
52
|
`${distPath}. История/метрики не будут записываться. Выполните npm run build.`);
|
|
51
53
|
return distPath;
|
|
52
54
|
})();
|
|
55
|
+
/**
|
|
56
|
+
* Путь к гейту расписания (dist/core/schedule-gate.js). Обёртка запускает его
|
|
57
|
+
* перед opencode и выходит, если cron не сработал или запуск перенесён.
|
|
58
|
+
*/
|
|
59
|
+
const gatePath = (() => {
|
|
60
|
+
const resolved = require.resolve("./core/schedule-gate.js");
|
|
61
|
+
if (!resolved.endsWith(".ts"))
|
|
62
|
+
return resolved;
|
|
63
|
+
const distPath = resolved
|
|
64
|
+
.replace(/([\\/])src([\\/])/, "$1dist$2")
|
|
65
|
+
.replace(/\.ts$/, ".js");
|
|
66
|
+
if (existsSync(distPath))
|
|
67
|
+
return distPath;
|
|
68
|
+
console.warn("[windows-scheduler] Не найден собранный schedule-gate.js: " +
|
|
69
|
+
`${distPath}. Гейт расписания не будет проверяться. Выполните npm run build.`);
|
|
70
|
+
return distPath;
|
|
71
|
+
})();
|
|
53
72
|
/** Бэкенд планировщика текущей ОС (schtasks / crontab / launchd). */
|
|
54
73
|
const scheduler = getSchedulerBackend();
|
|
55
74
|
/** Per-workspace overrides for matrix clones (Sprint 17). */
|
|
@@ -95,7 +114,19 @@ export const scheduleTaskSchema = z.object({
|
|
|
95
114
|
name: z.string().describe("Unique task name (the plugin prefix is applied automatically)."),
|
|
96
115
|
schedule: z
|
|
97
116
|
.string()
|
|
98
|
-
.describe("
|
|
117
|
+
.describe("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."),
|
|
118
|
+
timezone: z
|
|
119
|
+
.string()
|
|
120
|
+
.optional()
|
|
121
|
+
.describe("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)."),
|
|
122
|
+
notBefore: z
|
|
123
|
+
.string()
|
|
124
|
+
.optional()
|
|
125
|
+
.describe("Launch window start in HH:MM (24h). Together with notAfter: a run outside the window is postponed to the next window opening, not skipped."),
|
|
126
|
+
notAfter: z
|
|
127
|
+
.string()
|
|
128
|
+
.optional()
|
|
129
|
+
.describe("Launch window end in HH:MM (24h). May be earlier than notBefore (window crosses midnight)."),
|
|
99
130
|
prompt: z
|
|
100
131
|
.string()
|
|
101
132
|
.describe("Prompt passed to the agent on every run."),
|
|
@@ -155,6 +186,10 @@ export const scheduleTaskSchema = z.object({
|
|
|
155
186
|
})
|
|
156
187
|
.optional()
|
|
157
188
|
.describe("MCP event trigger: server, event name and an optional filter (key=value or regex)."),
|
|
189
|
+
watchPath: z
|
|
190
|
+
.string()
|
|
191
|
+
.optional()
|
|
192
|
+
.describe("File or directory to watch when triggerType is \"file\". Can be set here or later via update_task."),
|
|
158
193
|
workingDirectory: z
|
|
159
194
|
.string()
|
|
160
195
|
.optional()
|
|
@@ -187,7 +222,19 @@ export const updateTaskSchema = z.object({
|
|
|
187
222
|
schedule: z
|
|
188
223
|
.string()
|
|
189
224
|
.optional()
|
|
190
|
-
.describe("New
|
|
225
|
+
.describe("New cron expression. Keeps the current value when omitted."),
|
|
226
|
+
timezone: z
|
|
227
|
+
.string()
|
|
228
|
+
.optional()
|
|
229
|
+
.describe("New IANA timezone. Empty string clears it (system timezone)."),
|
|
230
|
+
notBefore: z
|
|
231
|
+
.string()
|
|
232
|
+
.optional()
|
|
233
|
+
.describe("New launch window start HH:MM. Empty string clears the window."),
|
|
234
|
+
notAfter: z
|
|
235
|
+
.string()
|
|
236
|
+
.optional()
|
|
237
|
+
.describe("New launch window end HH:MM. Empty string clears the window."),
|
|
191
238
|
prompt: z
|
|
192
239
|
.string()
|
|
193
240
|
.optional()
|
|
@@ -263,6 +310,10 @@ export const updateTaskSchema = z.object({
|
|
|
263
310
|
});
|
|
264
311
|
const pauseTaskSchema = z.object({
|
|
265
312
|
name: z.string().describe("Task name to pause."),
|
|
313
|
+
until: z
|
|
314
|
+
.string()
|
|
315
|
+
.optional()
|
|
316
|
+
.describe("Optional ISO date/time to resume automatically (e.g. 2026-12-01T09:00:00Z). The plugin re-enables the task at that moment."),
|
|
266
317
|
});
|
|
267
318
|
const resumeTaskSchema = z.object({
|
|
268
319
|
name: z.string().describe("Task name to resume."),
|
|
@@ -302,15 +353,152 @@ const manageWorkspacesSchema = z.object({
|
|
|
302
353
|
name: z.string().optional().describe("Workspace display name (add/update)."),
|
|
303
354
|
path: z.string().optional().describe("Absolute workspace path (add/update)."),
|
|
304
355
|
color: z.string().optional().describe("Marker color, e.g. #4f8cff (add/update)."),
|
|
356
|
+
env: z
|
|
357
|
+
.record(z.string(), z.string())
|
|
358
|
+
.nullable()
|
|
359
|
+
.optional()
|
|
360
|
+
.describe("Env-переменные workspace (ключ → значение). Переопределяют значения из envFile; секреты маскируются в логах (add/update)."),
|
|
361
|
+
envFile: z
|
|
362
|
+
.string()
|
|
363
|
+
.nullable()
|
|
364
|
+
.optional()
|
|
365
|
+
.describe("Путь к .env-файлу workspace (add/update, null — очистить)."),
|
|
305
366
|
});
|
|
306
367
|
export const matrixControlSchema = z.object({
|
|
307
368
|
action: z
|
|
308
|
-
.enum(["results", "cancel", "cleanup"])
|
|
309
|
-
.describe("results — aggregate status of a matrix; cancel — cancel pending clones; cleanup — delete orphaned clones and aggregators."),
|
|
369
|
+
.enum(["results", "cancel", "cleanup", "preview"])
|
|
370
|
+
.describe("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."),
|
|
310
371
|
name: z
|
|
311
372
|
.string()
|
|
312
373
|
.optional()
|
|
313
|
-
.describe("Matrix parent name (required for results and cancel)."),
|
|
374
|
+
.describe("Matrix parent name (required for results and cancel; used as clone prefix for preview)."),
|
|
375
|
+
workspaceIds: z
|
|
376
|
+
.array(z.string())
|
|
377
|
+
.optional()
|
|
378
|
+
.describe("Preview only: workspace ids to fan out to (omit for every workspace)."),
|
|
379
|
+
strategy: z
|
|
380
|
+
.enum(["parallel", "sequential"])
|
|
381
|
+
.optional()
|
|
382
|
+
.describe("Preview only: clone execution strategy."),
|
|
383
|
+
failureMode: z
|
|
384
|
+
.enum(["continue", "stop"])
|
|
385
|
+
.optional()
|
|
386
|
+
.describe("Preview only: what to do when one clone fails."),
|
|
387
|
+
aggregation: z
|
|
388
|
+
.enum(["summary", "per-task"])
|
|
389
|
+
.optional()
|
|
390
|
+
.describe("Preview only: how clone results are aggregated."),
|
|
391
|
+
});
|
|
392
|
+
/** get_metrics — общая статистика запусков. */
|
|
393
|
+
export const getMetricsSchema = z.object({});
|
|
394
|
+
/** get_analytics — аналитика за период. */
|
|
395
|
+
export const getAnalyticsSchema = z.object({
|
|
396
|
+
days: z
|
|
397
|
+
.number()
|
|
398
|
+
.int()
|
|
399
|
+
.min(1)
|
|
400
|
+
.max(365)
|
|
401
|
+
.optional()
|
|
402
|
+
.describe("Analysis window in days (default 14)."),
|
|
403
|
+
topLimit: z
|
|
404
|
+
.number()
|
|
405
|
+
.int()
|
|
406
|
+
.min(1)
|
|
407
|
+
.max(50)
|
|
408
|
+
.optional()
|
|
409
|
+
.describe("How many top tasks to include (default 10)."),
|
|
410
|
+
});
|
|
411
|
+
/** manage_settings — глобальные настройки планировщика. */
|
|
412
|
+
export const manageSettingsSchema = z.object({
|
|
413
|
+
action: z
|
|
414
|
+
.enum(["get", "update"])
|
|
415
|
+
.describe("get — current settings; update — merge the provided fields and save."),
|
|
416
|
+
maxConcurrent: z
|
|
417
|
+
.number()
|
|
418
|
+
.int()
|
|
419
|
+
.min(1)
|
|
420
|
+
.max(16)
|
|
421
|
+
.optional()
|
|
422
|
+
.describe("How many task runs may execute at the same time."),
|
|
423
|
+
winterMode: z
|
|
424
|
+
.boolean()
|
|
425
|
+
.optional()
|
|
426
|
+
.describe("Winter mode: gentler scheduling of deferred runs."),
|
|
427
|
+
notifications: z
|
|
428
|
+
.any()
|
|
429
|
+
.optional()
|
|
430
|
+
.describe("Notification settings patch (enabled, onlyOnError, webhook, templates, filters, matrix, digest)."),
|
|
431
|
+
history: z
|
|
432
|
+
.object({
|
|
433
|
+
retentionDays: z.number().int().min(1).max(3650).optional(),
|
|
434
|
+
maxRecords: z.number().int().min(100).max(1000000).optional(),
|
|
435
|
+
})
|
|
436
|
+
.optional()
|
|
437
|
+
.describe("History retention policy."),
|
|
438
|
+
});
|
|
439
|
+
/** manage_templates — пользовательские шаблоны задач. */
|
|
440
|
+
export const manageTemplatesSchema = z.object({
|
|
441
|
+
action: z
|
|
442
|
+
.enum(["list", "save", "delete"])
|
|
443
|
+
.describe("list — all templates; save — create or update (id omitted = create); delete — remove by id."),
|
|
444
|
+
id: z.string().optional().describe("Template id for update/delete."),
|
|
445
|
+
name: z.string().optional().describe("Template name."),
|
|
446
|
+
prompt: z.string().optional().describe("Prompt text stored in the template."),
|
|
447
|
+
schedule: z.string().optional().describe("Cron expression."),
|
|
448
|
+
timeoutSeconds: z.number().int().positive().optional(),
|
|
449
|
+
model: z.string().optional(),
|
|
450
|
+
priority: z.number().int().min(0).max(10).optional(),
|
|
451
|
+
retryCount: z.number().int().min(0).optional(),
|
|
452
|
+
retryDelay: z.number().int().min(0).optional(),
|
|
453
|
+
qualityGate: z.string().optional(),
|
|
454
|
+
beforeScript: z.string().optional(),
|
|
455
|
+
afterScript: z.string().optional(),
|
|
456
|
+
nextTaskOnSuccess: z.string().optional(),
|
|
457
|
+
nextTaskOnError: z.string().optional(),
|
|
458
|
+
dependsOn: z.array(z.string()).optional(),
|
|
459
|
+
triggerType: z.enum(["cron", "file", "mcp-event"]).optional(),
|
|
460
|
+
mcpEvent: z
|
|
461
|
+
.object({
|
|
462
|
+
server: z.string(),
|
|
463
|
+
event: z.string(),
|
|
464
|
+
filter: z.string().optional(),
|
|
465
|
+
})
|
|
466
|
+
.optional(),
|
|
467
|
+
watchPath: z.string().optional(),
|
|
468
|
+
workingDirectory: z.string().optional(),
|
|
469
|
+
allowedTools: z.array(z.string()).optional(),
|
|
470
|
+
deniedTools: z.array(z.string()).optional(),
|
|
471
|
+
});
|
|
472
|
+
/** manage_profiles — изолированные профили планировщика. */
|
|
473
|
+
export const manageProfilesSchema = z.object({
|
|
474
|
+
action: z
|
|
475
|
+
.enum(["list", "create", "switch", "delete"])
|
|
476
|
+
.describe("list — profiles; create — new profile; switch — make active (restart required); delete — remove profile data."),
|
|
477
|
+
name: z.string().optional().describe("Profile name (required for create/switch/delete)."),
|
|
478
|
+
port: z.number().int().min(1).max(65535).optional().describe("Dashboard port for a new profile."),
|
|
479
|
+
});
|
|
480
|
+
/** transfer_tasks — экспорт и импорт задач. */
|
|
481
|
+
export const transferTasksSchema = z.object({
|
|
482
|
+
action: z.enum(["export", "import"]).describe("export — JSON snapshot; import — recreate tasks from a snapshot."),
|
|
483
|
+
data: z.string().optional().describe("JSON produced by export (required for import)."),
|
|
484
|
+
});
|
|
485
|
+
/** send_notification — проверка уведомлений и дайджест. */
|
|
486
|
+
export const sendNotificationSchema = z.object({
|
|
487
|
+
action: z
|
|
488
|
+
.enum(["test", "digest"])
|
|
489
|
+
.describe("test — send a test message through the configured channel; digest — send the digest now."),
|
|
490
|
+
});
|
|
491
|
+
/** get_dashboard_info — сведения о панели управления. */
|
|
492
|
+
export const getDashboardInfoSchema = z.object({});
|
|
493
|
+
/** cleanup_history — удаление старой истории. */
|
|
494
|
+
export const cleanupHistorySchema = z.object({
|
|
495
|
+
retentionDays: z.number().int().min(1).max(3650).optional().describe("Override the retention window."),
|
|
496
|
+
maxRecords: z.number().int().min(100).max(1000000).optional().describe("Override the record cap."),
|
|
497
|
+
});
|
|
498
|
+
/** emit_event — запуск задач по MCP-событию. */
|
|
499
|
+
export const emitEventSchema = z.object({
|
|
500
|
+
eventName: z.string().min(1).describe("Event name, for example 'deploy.finished'."),
|
|
501
|
+
payload: z.any().optional().describe("Event payload passed to trigger filters."),
|
|
314
502
|
});
|
|
315
503
|
/**
|
|
316
504
|
* Директория проекта, в которой запущен OpenCode. Используется как рабочая
|
|
@@ -339,9 +527,9 @@ function wrapExecute(fn) {
|
|
|
339
527
|
}
|
|
340
528
|
/** schedule_task — создаёт задачу в schtasks через общий schedulerCreateTask. */
|
|
341
529
|
const scheduleTaskExecute = wrapExecute(async (args) => {
|
|
342
|
-
const { name, schedule, prompt, timeoutSeconds, model, priority, beforeScript, afterScript, qualityGate, dependsOn, retryCount, retryDelay, nextTaskOnSuccess, nextTaskOnError, triggerType, mcpEvent, workingDirectory, workspaceId, allowedTools, deniedTools, matrix, } = args;
|
|
530
|
+
const { name, schedule, prompt, timeoutSeconds, model, priority, beforeScript, afterScript, qualityGate, dependsOn, retryCount, retryDelay, nextTaskOnSuccess, nextTaskOnError, triggerType, mcpEvent, watchPath, workingDirectory, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, } = args;
|
|
343
531
|
try {
|
|
344
|
-
await schedulerCreateTask(name, schedule, prompt, timeoutSeconds, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType,
|
|
532
|
+
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);
|
|
345
533
|
}
|
|
346
534
|
catch (err) {
|
|
347
535
|
return {
|
|
@@ -351,6 +539,9 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
|
|
|
351
539
|
}),
|
|
352
540
|
};
|
|
353
541
|
}
|
|
542
|
+
// Новый файловый триггер должен начать работать сразу, без перезапуска
|
|
543
|
+
// OpenCode: пересобираем набор watcher-ов после создания задачи.
|
|
544
|
+
await refreshFileTriggers();
|
|
354
545
|
const workspace = workspaceId ? getWorkspace(workspaceId) : undefined;
|
|
355
546
|
const effectiveWorkdir = workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
|
|
356
547
|
return {
|
|
@@ -372,6 +563,9 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
|
|
|
372
563
|
nextTaskOnSuccess: nextTaskOnSuccess?.trim() || null,
|
|
373
564
|
nextTaskOnError: nextTaskOnError?.trim() || null,
|
|
374
565
|
triggerType: triggerType ?? "cron",
|
|
566
|
+
timezone: timezone?.trim() || null,
|
|
567
|
+
notBefore: notBefore?.trim() || null,
|
|
568
|
+
notAfter: notAfter?.trim() || null,
|
|
375
569
|
mcpEvent: mcpEvent ?? null,
|
|
376
570
|
workingDirectory: effectiveWorkdir,
|
|
377
571
|
workspaceId: workspace?.id ?? null,
|
|
@@ -428,7 +622,7 @@ async function cancelMatrixRun(name) {
|
|
|
428
622
|
}
|
|
429
623
|
// Возвращаем placeholder-задачу, чтобы следующая fan-out-волна работала.
|
|
430
624
|
try {
|
|
431
|
-
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);
|
|
625
|
+
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);
|
|
432
626
|
}
|
|
433
627
|
catch (err) {
|
|
434
628
|
warnings.push(`${clone.name}: не удалось пересоздать — ${err instanceof Error ? err.message : String(err)}`);
|
|
@@ -491,6 +685,20 @@ async function deleteTaskWithFamily(name) {
|
|
|
491
685
|
throw new Error(guard);
|
|
492
686
|
const plan = planMatrixFamilyDelete(trimmed);
|
|
493
687
|
const removed = [];
|
|
688
|
+
// Отличаем реальное удаление от «удаления пустоты»: раньше инструмент
|
|
689
|
+
// отвечал success даже на имя, которого никогда не существовало.
|
|
690
|
+
let existed = Boolean(getTask(trimmed));
|
|
691
|
+
if (!existed) {
|
|
692
|
+
try {
|
|
693
|
+
const osTasks = await scheduler.listTasks();
|
|
694
|
+
existed = osTasks.some((task) => task.taskName.toLowerCase() === trimmed.toLowerCase());
|
|
695
|
+
}
|
|
696
|
+
catch {
|
|
697
|
+
// ОС-планировщик недоступен — довольствуемся данными БД.
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
if (plan && plan.children.length > 0)
|
|
701
|
+
existed = true;
|
|
494
702
|
if (plan) {
|
|
495
703
|
for (const child of plan.children) {
|
|
496
704
|
try {
|
|
@@ -515,13 +723,23 @@ async function deleteTaskWithFamily(name) {
|
|
|
515
723
|
catch {
|
|
516
724
|
// Определения могло уже не быть — задача всё равно удалена из ОС.
|
|
517
725
|
}
|
|
518
|
-
return { removed };
|
|
726
|
+
return { removed, existed };
|
|
519
727
|
}
|
|
520
728
|
/** delete_task — удаление задачи по имени (/f) */
|
|
521
729
|
const deleteTaskExecute = wrapExecute(async (args) => {
|
|
522
730
|
const { name } = args;
|
|
523
731
|
try {
|
|
524
|
-
const { removed } = await deleteTaskWithFamily(name);
|
|
732
|
+
const { removed, existed } = await deleteTaskWithFamily(name);
|
|
733
|
+
// Убираем watcher удалённой задачи, не дожидаясь перезапуска плагина.
|
|
734
|
+
await refreshFileTriggers();
|
|
735
|
+
if (!existed && removed.length === 0) {
|
|
736
|
+
return {
|
|
737
|
+
content: JSON.stringify({
|
|
738
|
+
success: false,
|
|
739
|
+
error: `Задача "${name}" не найдена — удалять нечего.`,
|
|
740
|
+
}),
|
|
741
|
+
};
|
|
742
|
+
}
|
|
525
743
|
return {
|
|
526
744
|
content: JSON.stringify({
|
|
527
745
|
success: true,
|
|
@@ -545,7 +763,7 @@ const runTaskNowExecute = wrapExecute(async (args) => {
|
|
|
545
763
|
const { name } = args;
|
|
546
764
|
let alreadyRunning = false;
|
|
547
765
|
try {
|
|
548
|
-
const result = await
|
|
766
|
+
const result = await runTaskEntry(name);
|
|
549
767
|
alreadyRunning = result.alreadyRunning;
|
|
550
768
|
}
|
|
551
769
|
catch (err) {
|
|
@@ -617,6 +835,9 @@ async function updateTaskFromInput(input) {
|
|
|
617
835
|
const schedule = clearableString(input.schedule ?? input.newSchedule, previous.schedule);
|
|
618
836
|
const prompt = clearableString(input.prompt ?? input.newPrompt, previous.prompt);
|
|
619
837
|
const triggerType = input.triggerType ?? previous.triggerType ?? "cron";
|
|
838
|
+
const timezone = clearableString(input.timezone, previous.timezone);
|
|
839
|
+
const notBefore = clearableString(input.notBefore, previous.notBefore);
|
|
840
|
+
const notAfter = clearableString(input.notAfter, previous.notAfter);
|
|
620
841
|
if (triggerType === "cron" && !schedule) {
|
|
621
842
|
return {
|
|
622
843
|
success: false,
|
|
@@ -637,11 +858,14 @@ async function updateTaskFromInput(input) {
|
|
|
637
858
|
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,
|
|
638
859
|
// Если задача была матрицей — синхронизируем клонов, а не
|
|
639
860
|
// пересоздаём их с нуля (Спринт 17).
|
|
640
|
-
matrixWas && matrixNext ? "sync" : "create");
|
|
861
|
+
matrixWas && matrixNext ? "sync" : "create", timezone, notBefore, notAfter, previous.pausedUntil);
|
|
641
862
|
// Матрица отключена при обновлении — убираем клонов и агрегатор.
|
|
642
863
|
if (matrixWas && !matrixNext) {
|
|
643
864
|
await removeMatrixChildrenFromScheduler(name);
|
|
644
865
|
}
|
|
866
|
+
// Пересоздание могло изменить triggerType/watchPath — сразу
|
|
867
|
+
// пересобираем набор файловых watcher-ов.
|
|
868
|
+
await refreshFileTriggers();
|
|
645
869
|
return { success: true, message: `Задача "${name}" обновлена.` };
|
|
646
870
|
}
|
|
647
871
|
catch (err) {
|
|
@@ -660,7 +884,7 @@ const updateTaskExecute = wrapExecute(async (args) => {
|
|
|
660
884
|
* Пауза/возобновление задачи. Для матрицы операция применяется ко всем
|
|
661
885
|
* клонам: сам родитель никогда не выполняется.
|
|
662
886
|
*/
|
|
663
|
-
async function pauseOrResumeTask(name, paused) {
|
|
887
|
+
async function pauseOrResumeTask(name, paused, until) {
|
|
664
888
|
const trimmed = name.trim();
|
|
665
889
|
const definition = getTask(trimmed);
|
|
666
890
|
if (!definition) {
|
|
@@ -671,6 +895,28 @@ async function pauseOrResumeTask(name, paused) {
|
|
|
671
895
|
warnings: [],
|
|
672
896
|
};
|
|
673
897
|
}
|
|
898
|
+
// Пауза до даты (Спринт 19): проверяем ISO-момент до каких-либо изменений.
|
|
899
|
+
let pausedUntil;
|
|
900
|
+
if (paused && until?.trim()) {
|
|
901
|
+
const parsed = Date.parse(until.trim());
|
|
902
|
+
if (Number.isNaN(parsed)) {
|
|
903
|
+
return {
|
|
904
|
+
success: false,
|
|
905
|
+
message: `Задача "${trimmed}": некорректная дата паузы "${until}". Нужен ISO-момент, например 2026-12-01T09:00:00Z.`,
|
|
906
|
+
affected: [],
|
|
907
|
+
warnings: [],
|
|
908
|
+
};
|
|
909
|
+
}
|
|
910
|
+
if (parsed <= Date.now()) {
|
|
911
|
+
return {
|
|
912
|
+
success: false,
|
|
913
|
+
message: `Задача "${trimmed}": дата паузы уже прошла.`,
|
|
914
|
+
affected: [],
|
|
915
|
+
warnings: [],
|
|
916
|
+
};
|
|
917
|
+
}
|
|
918
|
+
pausedUntil = new Date(parsed).toISOString();
|
|
919
|
+
}
|
|
674
920
|
const targets = definition.matrix
|
|
675
921
|
? listMatrixClones(trimmed).map((clone) => clone.name)
|
|
676
922
|
: [trimmed];
|
|
@@ -698,11 +944,31 @@ async function pauseOrResumeTask(name, paused) {
|
|
|
698
944
|
warnings.push(`${target}: ${err instanceof Error ? err.message : String(err)}`);
|
|
699
945
|
}
|
|
700
946
|
}
|
|
947
|
+
// Фиксируем (или снимаем) автопродолжение в определении задачи. У матрицы
|
|
948
|
+
// родитель хранит pausedUntil за всех клонов — их включает авто-resume.
|
|
949
|
+
const definitionUpdates = paused
|
|
950
|
+
? pausedUntil
|
|
951
|
+
? { pausedUntil }
|
|
952
|
+
: undefined
|
|
953
|
+
: definition.pausedUntil
|
|
954
|
+
? { pausedUntil: undefined }
|
|
955
|
+
: undefined;
|
|
956
|
+
if (definitionUpdates && affected.length > 0) {
|
|
957
|
+
try {
|
|
958
|
+
saveTask({ ...definition, ...definitionUpdates });
|
|
959
|
+
}
|
|
960
|
+
catch (err) {
|
|
961
|
+
warnings.push(`не удалось сохранить автопродолжение: ${err instanceof Error ? err.message : String(err)}`);
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
const untilText = pausedUntil
|
|
965
|
+
? ` до ${new Date(pausedUntil).toLocaleString()}`
|
|
966
|
+
: "";
|
|
701
967
|
const verb = paused ? "поставлена на паузу" : "возобновлена";
|
|
702
968
|
const message = definition.matrix
|
|
703
|
-
? `Матрица "${trimmed}" ${verb}: ${affected.length} из ${targets.length} клонов.` +
|
|
969
|
+
? `Матрица "${trimmed}" ${verb}${untilText}: ${affected.length} из ${targets.length} клонов.` +
|
|
704
970
|
(warnings.length > 0 ? ` Ошибки: ${warnings.join("; ")}.` : "")
|
|
705
|
-
: `Задача "${trimmed}" ${verb}.` +
|
|
971
|
+
: `Задача "${trimmed}" ${verb}${untilText}.` +
|
|
706
972
|
(warnings.length > 0 ? ` Ошибка: ${warnings.join("; ")}.` : "");
|
|
707
973
|
return {
|
|
708
974
|
success: warnings.length === 0,
|
|
@@ -712,13 +978,90 @@ async function pauseOrResumeTask(name, paused) {
|
|
|
712
978
|
};
|
|
713
979
|
}
|
|
714
980
|
const pauseTaskExecute = wrapExecute(async (args) => {
|
|
715
|
-
const result = await pauseOrResumeTask(args.name, true);
|
|
981
|
+
const result = await pauseOrResumeTask(args.name, true, args.until);
|
|
716
982
|
return { content: JSON.stringify(result) };
|
|
717
983
|
});
|
|
718
984
|
const resumeTaskExecute = wrapExecute(async (args) => {
|
|
719
985
|
const result = await pauseOrResumeTask(args.name, false);
|
|
720
986
|
return { content: JSON.stringify(result) };
|
|
721
987
|
});
|
|
988
|
+
/** Периодичность проверки автопродолжения задач (Спринт 19). */
|
|
989
|
+
const PAUSED_UNTIL_CHECK_MS = 5 * 60 * 1000;
|
|
990
|
+
/** Период проверки дайджеста и зависших матриц (Спринт 20). */
|
|
991
|
+
const NOTIFICATION_CHECK_MS = 60 * 1000;
|
|
992
|
+
/**
|
|
993
|
+
* Спринт 19: автопродолжение задач, поставленных на паузу до даты.
|
|
994
|
+
* Включает задачу в планировщике ОС и снимает `pausedUntil` из определения.
|
|
995
|
+
* Клоны матрицы не обрабатываются отдельно — за них отвечает родитель.
|
|
996
|
+
*/
|
|
997
|
+
async function resumeExpiredPauses() {
|
|
998
|
+
const now = Date.now();
|
|
999
|
+
const definitions = await loadTaskDefinitions();
|
|
1000
|
+
for (const definition of definitions) {
|
|
1001
|
+
if (!definition.pausedUntil)
|
|
1002
|
+
continue;
|
|
1003
|
+
if (definition.matrixParentId)
|
|
1004
|
+
continue;
|
|
1005
|
+
const untilMs = Date.parse(definition.pausedUntil);
|
|
1006
|
+
if (!Number.isFinite(untilMs) || untilMs > now)
|
|
1007
|
+
continue;
|
|
1008
|
+
try {
|
|
1009
|
+
const targets = definition.matrix
|
|
1010
|
+
? listMatrixClones(definition.name).map((clone) => clone.name)
|
|
1011
|
+
: [definition.name];
|
|
1012
|
+
for (const target of targets) {
|
|
1013
|
+
await scheduler.resumeTask(target);
|
|
1014
|
+
}
|
|
1015
|
+
await saveTaskDefinition({ ...definition, pausedUntil: undefined });
|
|
1016
|
+
console.log(`[windows-scheduler] Автопродолжение: задача "${definition.name}" включена (пауза истекла).`);
|
|
1017
|
+
}
|
|
1018
|
+
catch (err) {
|
|
1019
|
+
console.error(`[windows-scheduler] Не удалось автопродолжить задачу "${definition.name}": ${err instanceof Error ? err.message : String(err)}`);
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
/** Уже отправленные уведомления о зависших клонах (id записи истории). */
|
|
1024
|
+
const notifiedStuckRecords = new Set();
|
|
1025
|
+
/**
|
|
1026
|
+
* Детектор зависших матриц (Спринт 20): клоны, которые выполняются дольше
|
|
1027
|
+
* `notifications.matrix.stuckAfterMinutes`. Каждый запуск уведомляется один раз.
|
|
1028
|
+
*/
|
|
1029
|
+
async function checkStuckMatrices() {
|
|
1030
|
+
const settings = await loadSettings();
|
|
1031
|
+
const config = settings.notifications;
|
|
1032
|
+
if (!config?.enabled)
|
|
1033
|
+
return;
|
|
1034
|
+
const matrix = config.matrix;
|
|
1035
|
+
if (!matrix?.enabled)
|
|
1036
|
+
return;
|
|
1037
|
+
const threshold = matrix.stuckAfterMinutes;
|
|
1038
|
+
if (!Number.isFinite(threshold) || threshold <= 0)
|
|
1039
|
+
return;
|
|
1040
|
+
const running = listRunningRecords();
|
|
1041
|
+
if (running.length === 0) {
|
|
1042
|
+
notifiedStuckRecords.clear();
|
|
1043
|
+
return;
|
|
1044
|
+
}
|
|
1045
|
+
// Снимаем отметки с завершившихся записей, чтобы Set не рос бесконечно.
|
|
1046
|
+
const runningIds = new Set(running.map((record) => record.id));
|
|
1047
|
+
for (const id of notifiedStuckRecords) {
|
|
1048
|
+
if (!runningIds.has(id))
|
|
1049
|
+
notifiedStuckRecords.delete(id);
|
|
1050
|
+
}
|
|
1051
|
+
const parentByClone = new Map();
|
|
1052
|
+
for (const definition of await loadTaskDefinitions()) {
|
|
1053
|
+
if (definition.matrixParentId) {
|
|
1054
|
+
parentByClone.set(definition.name.toLowerCase(), definition.matrixParentId);
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
const stuck = findStuckMatrixClones(running, parentByClone, new Date(), threshold);
|
|
1058
|
+
for (const item of stuck) {
|
|
1059
|
+
if (notifiedStuckRecords.has(item.id))
|
|
1060
|
+
continue;
|
|
1061
|
+
notifiedStuckRecords.add(item.id);
|
|
1062
|
+
await notifyStuckMatrix(item);
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
722
1065
|
/** get_history — история запусков с фильтрами по задаче и статусу. */
|
|
723
1066
|
const getHistoryExecute = wrapExecute(async (args) => {
|
|
724
1067
|
const limit = Math.max(1, Math.min(args.limit ?? 20, 200));
|
|
@@ -783,6 +1126,23 @@ const dryRunExecute = wrapExecute(async (args) => {
|
|
|
783
1126
|
}),
|
|
784
1127
|
};
|
|
785
1128
|
});
|
|
1129
|
+
/**
|
|
1130
|
+
* Перегенерирует env-файлы всех задач, привязанных к workspace (Спринт 21).
|
|
1131
|
+
* Обёртки читают env-файл при запуске, поэтому перезапуск задач не нужен.
|
|
1132
|
+
*/
|
|
1133
|
+
async function refreshWorkspaceEnvFiles(workspaceId) {
|
|
1134
|
+
const workspace = getWorkspace(workspaceId);
|
|
1135
|
+
if (!workspace)
|
|
1136
|
+
return 0;
|
|
1137
|
+
let refreshed = 0;
|
|
1138
|
+
for (const task of await loadTaskDefinitions()) {
|
|
1139
|
+
if (task.workspaceId !== workspaceId)
|
|
1140
|
+
continue;
|
|
1141
|
+
writeWorkspaceEnvFile(workspace, PLUGIN_DIR, sanitizeName(task.name));
|
|
1142
|
+
refreshed += 1;
|
|
1143
|
+
}
|
|
1144
|
+
return refreshed;
|
|
1145
|
+
}
|
|
786
1146
|
/** manage_workspaces — CRUD multi-repo workspace-ов. */
|
|
787
1147
|
const manageWorkspacesExecute = wrapExecute(async (args) => {
|
|
788
1148
|
try {
|
|
@@ -790,6 +1150,7 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
|
|
|
790
1150
|
case "list": {
|
|
791
1151
|
const workspaces = listWorkspaces().map((workspace) => ({
|
|
792
1152
|
...workspace,
|
|
1153
|
+
env: maskEnvForLog(workspace.env),
|
|
793
1154
|
gitBranch: readGitBranch(workspace.path) ?? null,
|
|
794
1155
|
}));
|
|
795
1156
|
return {
|
|
@@ -813,12 +1174,15 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
|
|
|
813
1174
|
name: args.name,
|
|
814
1175
|
path: args.path,
|
|
815
1176
|
color: args.color,
|
|
1177
|
+
env: args.env,
|
|
1178
|
+
envFile: args.envFile,
|
|
816
1179
|
});
|
|
817
1180
|
return {
|
|
818
1181
|
content: JSON.stringify({
|
|
819
1182
|
success: true,
|
|
820
1183
|
workspace: {
|
|
821
1184
|
...workspace,
|
|
1185
|
+
env: maskEnvForLog(workspace.env),
|
|
822
1186
|
gitBranch: readGitBranch(workspace.path) ?? null,
|
|
823
1187
|
},
|
|
824
1188
|
}),
|
|
@@ -837,6 +1201,8 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
|
|
|
837
1201
|
name: args.name,
|
|
838
1202
|
path: args.path,
|
|
839
1203
|
color: args.color,
|
|
1204
|
+
env: args.env,
|
|
1205
|
+
envFile: args.envFile,
|
|
840
1206
|
});
|
|
841
1207
|
if (!workspace) {
|
|
842
1208
|
return {
|
|
@@ -846,11 +1212,16 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
|
|
|
846
1212
|
}),
|
|
847
1213
|
};
|
|
848
1214
|
}
|
|
1215
|
+
// Env-файлы уже созданных задач перегенерируются сразу: обёртки читают
|
|
1216
|
+
// файл при запуске, поэтому ждать обновления задачи не нужно.
|
|
1217
|
+
const refreshedTasks = await refreshWorkspaceEnvFiles(workspace.id);
|
|
849
1218
|
return {
|
|
850
1219
|
content: JSON.stringify({
|
|
851
1220
|
success: true,
|
|
1221
|
+
refreshedTasks,
|
|
852
1222
|
workspace: {
|
|
853
1223
|
...workspace,
|
|
1224
|
+
env: maskEnvForLog(workspace.env),
|
|
854
1225
|
gitBranch: readGitBranch(workspace.path) ?? null,
|
|
855
1226
|
},
|
|
856
1227
|
}),
|
|
@@ -886,8 +1257,31 @@ const manageWorkspacesExecute = wrapExecute(async (args) => {
|
|
|
886
1257
|
};
|
|
887
1258
|
}
|
|
888
1259
|
});
|
|
889
|
-
/** matrix_control — результаты,
|
|
1260
|
+
/** matrix_control — результаты, отмена, очистка и предпросмотр матриц. */
|
|
890
1261
|
const matrixControlExecute = wrapExecute(async (args) => {
|
|
1262
|
+
if (args.action === "preview") {
|
|
1263
|
+
const clones = expandMatrixTask({
|
|
1264
|
+
name: (args.name ?? "").trim() || "task",
|
|
1265
|
+
schedule: "* * * * *",
|
|
1266
|
+
prompt: "preview",
|
|
1267
|
+
matrix: {
|
|
1268
|
+
workspaceIds: Array.isArray(args.workspaceIds) ? args.workspaceIds : [],
|
|
1269
|
+
strategy: args.strategy,
|
|
1270
|
+
failureMode: args.failureMode,
|
|
1271
|
+
aggregation: args.aggregation,
|
|
1272
|
+
},
|
|
1273
|
+
});
|
|
1274
|
+
return {
|
|
1275
|
+
content: JSON.stringify({
|
|
1276
|
+
success: true,
|
|
1277
|
+
clones: clones.map((clone) => ({
|
|
1278
|
+
name: clone.name,
|
|
1279
|
+
workspaceId: clone.workspaceId ?? "",
|
|
1280
|
+
workspaceName: clone.workspaceId ? getWorkspace(clone.workspaceId)?.name ?? null : null,
|
|
1281
|
+
})),
|
|
1282
|
+
}),
|
|
1283
|
+
};
|
|
1284
|
+
}
|
|
891
1285
|
if (args.action === "cleanup") {
|
|
892
1286
|
const removed = await cleanupOrphanedMatrixTasks();
|
|
893
1287
|
return {
|
|
@@ -942,6 +1336,270 @@ const matrixControlExecute = wrapExecute(async (args) => {
|
|
|
942
1336
|
};
|
|
943
1337
|
}
|
|
944
1338
|
});
|
|
1339
|
+
/** get_metrics — суммарная статистика запусков. */
|
|
1340
|
+
const getMetricsExecute = wrapExecute(async () => {
|
|
1341
|
+
const metrics = await loadMetrics();
|
|
1342
|
+
return { content: JSON.stringify({ success: true, metrics }) };
|
|
1343
|
+
});
|
|
1344
|
+
/** get_analytics — аналитика запусков и стоимости за период. */
|
|
1345
|
+
const getAnalyticsExecute = wrapExecute(async (args) => {
|
|
1346
|
+
const windowDays = Math.min(365, Math.max(1, Math.floor(Number(args.days) || 14)));
|
|
1347
|
+
const records = getHistory(null, 20000);
|
|
1348
|
+
const definitions = await loadTaskDefinitions();
|
|
1349
|
+
const report = buildAnalytics(records, {
|
|
1350
|
+
days: windowDays,
|
|
1351
|
+
topLimit: Math.max(1, Math.floor(Number(args.topLimit) || 10)),
|
|
1352
|
+
tasks: definitions.map((definition) => ({
|
|
1353
|
+
name: definition.name,
|
|
1354
|
+
matrixParentId: definition.matrixParentId,
|
|
1355
|
+
})),
|
|
1356
|
+
});
|
|
1357
|
+
return { content: JSON.stringify({ success: true, report }) };
|
|
1358
|
+
});
|
|
1359
|
+
/** manage_settings — чтение и изменение глобальных настроек. */
|
|
1360
|
+
const manageSettingsExecute = wrapExecute(async (args) => {
|
|
1361
|
+
const current = await loadSettings();
|
|
1362
|
+
if (args.action === "get") {
|
|
1363
|
+
return { content: JSON.stringify({ success: true, settings: current }) };
|
|
1364
|
+
}
|
|
1365
|
+
if (args.maxConcurrent === undefined &&
|
|
1366
|
+
args.winterMode === undefined &&
|
|
1367
|
+
args.notifications === undefined &&
|
|
1368
|
+
args.history === undefined) {
|
|
1369
|
+
return {
|
|
1370
|
+
content: JSON.stringify({
|
|
1371
|
+
success: false,
|
|
1372
|
+
error: "Для action=update передайте хотя бы одно поле: maxConcurrent, winterMode, notifications или history.",
|
|
1373
|
+
settings: current,
|
|
1374
|
+
}),
|
|
1375
|
+
};
|
|
1376
|
+
}
|
|
1377
|
+
const settings = await saveSettings({
|
|
1378
|
+
maxConcurrent: args.maxConcurrent,
|
|
1379
|
+
winterMode: args.winterMode,
|
|
1380
|
+
notifications: args.notifications,
|
|
1381
|
+
history: args.history,
|
|
1382
|
+
});
|
|
1383
|
+
return { content: JSON.stringify({ success: true, settings }) };
|
|
1384
|
+
});
|
|
1385
|
+
/** manage_templates — список, сохранение и удаление шаблонов задач. */
|
|
1386
|
+
const manageTemplatesExecute = wrapExecute(async (args) => {
|
|
1387
|
+
if (args.action === "list") {
|
|
1388
|
+
return { content: JSON.stringify({ success: true, templates: await loadTemplates() }) };
|
|
1389
|
+
}
|
|
1390
|
+
if (args.action === "delete") {
|
|
1391
|
+
const id = args.id?.trim();
|
|
1392
|
+
if (!id) {
|
|
1393
|
+
return { content: JSON.stringify({ success: false, error: "Для action=delete нужен id шаблона." }) };
|
|
1394
|
+
}
|
|
1395
|
+
const before = await loadTemplates();
|
|
1396
|
+
const existed = before.some((template) => template.id === id);
|
|
1397
|
+
await deleteTemplate(id);
|
|
1398
|
+
return {
|
|
1399
|
+
content: JSON.stringify({
|
|
1400
|
+
success: existed,
|
|
1401
|
+
message: existed ? `Шаблон ${id} удалён.` : `Шаблон ${id} не найден.`,
|
|
1402
|
+
}),
|
|
1403
|
+
};
|
|
1404
|
+
}
|
|
1405
|
+
const { action, ...fields } = args;
|
|
1406
|
+
if (!fields.name?.trim() || !fields.prompt?.trim()) {
|
|
1407
|
+
return {
|
|
1408
|
+
content: JSON.stringify({
|
|
1409
|
+
success: false,
|
|
1410
|
+
error: "Для action=save нужны непустые name и prompt.",
|
|
1411
|
+
}),
|
|
1412
|
+
};
|
|
1413
|
+
}
|
|
1414
|
+
const template = await saveTemplate(fields);
|
|
1415
|
+
return { content: JSON.stringify({ success: true, template }) };
|
|
1416
|
+
});
|
|
1417
|
+
/** manage_profiles — список, создание, переключение и удаление профилей. */
|
|
1418
|
+
const manageProfilesExecute = wrapExecute(async (args) => {
|
|
1419
|
+
if (args.action === "list") {
|
|
1420
|
+
return {
|
|
1421
|
+
content: JSON.stringify({
|
|
1422
|
+
success: true,
|
|
1423
|
+
current: getProfileName(),
|
|
1424
|
+
pinnedByEnv: isProfilePinnedByEnv(),
|
|
1425
|
+
profiles: listProfiles(),
|
|
1426
|
+
}),
|
|
1427
|
+
};
|
|
1428
|
+
}
|
|
1429
|
+
const name = args.name?.trim();
|
|
1430
|
+
if (!name) {
|
|
1431
|
+
return {
|
|
1432
|
+
content: JSON.stringify({
|
|
1433
|
+
success: false,
|
|
1434
|
+
error: `Для action=${args.action} нужно имя профиля.`,
|
|
1435
|
+
}),
|
|
1436
|
+
};
|
|
1437
|
+
}
|
|
1438
|
+
if (args.action === "create") {
|
|
1439
|
+
const meta = createProfile(name, args.port);
|
|
1440
|
+
const profile = listProfiles().find((item) => item.name === meta.name);
|
|
1441
|
+
return {
|
|
1442
|
+
content: JSON.stringify({
|
|
1443
|
+
success: true,
|
|
1444
|
+
message: `Профиль "${meta.name}" создан (порт дашборда ${meta.port}).`,
|
|
1445
|
+
profile: profile ?? {
|
|
1446
|
+
name: meta.name,
|
|
1447
|
+
dir: getProfileDir(meta.name),
|
|
1448
|
+
port: meta.port,
|
|
1449
|
+
isDefault: meta.name === DEFAULT_PROFILE,
|
|
1450
|
+
active: meta.name === getProfileName(),
|
|
1451
|
+
},
|
|
1452
|
+
}),
|
|
1453
|
+
};
|
|
1454
|
+
}
|
|
1455
|
+
if (args.action === "switch") {
|
|
1456
|
+
setActiveProfile(name);
|
|
1457
|
+
const current = getProfileName();
|
|
1458
|
+
return {
|
|
1459
|
+
content: JSON.stringify({
|
|
1460
|
+
success: true,
|
|
1461
|
+
current,
|
|
1462
|
+
restartRequired: true,
|
|
1463
|
+
message: isProfilePinnedByEnv()
|
|
1464
|
+
? `Профиль задан переменной OPENCODE_SCHEDULER_PROFILE=${current}. Перезапустите OpenCode.`
|
|
1465
|
+
: `Активный профиль: ${sanitizeProfileName(name)}. Перезапустите OpenCode, чтобы применить изменения.`,
|
|
1466
|
+
}),
|
|
1467
|
+
};
|
|
1468
|
+
}
|
|
1469
|
+
const removed = deleteProfile(name);
|
|
1470
|
+
return {
|
|
1471
|
+
content: JSON.stringify({
|
|
1472
|
+
success: removed,
|
|
1473
|
+
message: removed
|
|
1474
|
+
? `Профиль "${sanitizeProfileName(name)}" удалён вместе с его БД и настройками.`
|
|
1475
|
+
: "Профиль не найден.",
|
|
1476
|
+
}),
|
|
1477
|
+
};
|
|
1478
|
+
});
|
|
1479
|
+
/** transfer_tasks — экспорт и импорт задач. */
|
|
1480
|
+
const transferTasksExecute = wrapExecute(async (args) => {
|
|
1481
|
+
if (args.action === "export") {
|
|
1482
|
+
const tasks = await scheduler.listTasks();
|
|
1483
|
+
const { data, count } = await buildExportJson(tasks.map((task) => ({ ...task, name: task.taskName || "" })));
|
|
1484
|
+
return { content: JSON.stringify({ success: true, data, count }) };
|
|
1485
|
+
}
|
|
1486
|
+
if (!args.data) {
|
|
1487
|
+
return { content: JSON.stringify({ success: false, error: "Для action=import нужны данные экспорта." }) };
|
|
1488
|
+
}
|
|
1489
|
+
const parsed = parseImportJson(args.data);
|
|
1490
|
+
if (parsed.tasks.length === 0) {
|
|
1491
|
+
return {
|
|
1492
|
+
content: JSON.stringify({
|
|
1493
|
+
success: false,
|
|
1494
|
+
error: "В данных нет задач для импорта.",
|
|
1495
|
+
errors: parsed.errors,
|
|
1496
|
+
}),
|
|
1497
|
+
};
|
|
1498
|
+
}
|
|
1499
|
+
const imported = [];
|
|
1500
|
+
const errors = [...parsed.errors];
|
|
1501
|
+
for (const def of parsed.tasks) {
|
|
1502
|
+
try {
|
|
1503
|
+
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);
|
|
1504
|
+
await saveTaskDefinition(def);
|
|
1505
|
+
imported.push(def.name);
|
|
1506
|
+
}
|
|
1507
|
+
catch (err) {
|
|
1508
|
+
errors.push(`${def.name}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
await refreshFileTriggers();
|
|
1512
|
+
return {
|
|
1513
|
+
content: JSON.stringify({ success: errors.length === 0, imported, errors }),
|
|
1514
|
+
};
|
|
1515
|
+
});
|
|
1516
|
+
/** send_notification — тестовое уведомление или дайджест. */
|
|
1517
|
+
const sendNotificationExecute = wrapExecute(async (args) => {
|
|
1518
|
+
const result = args.action === "test"
|
|
1519
|
+
? await sendTestNotification()
|
|
1520
|
+
: await sendDigestNow({ updateLastSentAt: false });
|
|
1521
|
+
return { content: JSON.stringify(result) };
|
|
1522
|
+
});
|
|
1523
|
+
/** get_dashboard_info — порт дашборда, платформа и активный профиль. */
|
|
1524
|
+
const getDashboardInfoExecute = wrapExecute(async () => {
|
|
1525
|
+
const port = getDashboardPort();
|
|
1526
|
+
return {
|
|
1527
|
+
content: JSON.stringify({
|
|
1528
|
+
success: true,
|
|
1529
|
+
port,
|
|
1530
|
+
url: port ? `http://127.0.0.1:${port}` : null,
|
|
1531
|
+
platform: scheduler.platform,
|
|
1532
|
+
title: scheduler.title,
|
|
1533
|
+
profile: getProfileName(),
|
|
1534
|
+
}),
|
|
1535
|
+
};
|
|
1536
|
+
});
|
|
1537
|
+
/** cleanup_history — удаление старых записей истории. */
|
|
1538
|
+
const cleanupHistoryExecute = wrapExecute(async (args) => {
|
|
1539
|
+
const report = await runHistoryRetention({
|
|
1540
|
+
retentionDays: args.retentionDays,
|
|
1541
|
+
maxRecords: args.maxRecords,
|
|
1542
|
+
});
|
|
1543
|
+
return {
|
|
1544
|
+
content: JSON.stringify({
|
|
1545
|
+
success: true,
|
|
1546
|
+
message: report.skipped
|
|
1547
|
+
? report.skipped
|
|
1548
|
+
: `Удалено ${report.deleted} записей (по возрасту: ${report.deletedByAge}, по лимиту: ${report.deletedByCount}), осталось ${report.kept}.`,
|
|
1549
|
+
report,
|
|
1550
|
+
}),
|
|
1551
|
+
};
|
|
1552
|
+
});
|
|
1553
|
+
/** emit_event — запуск задач, подписанных на MCP-событие. */
|
|
1554
|
+
const emitEventExecute = wrapExecute(async (args) => {
|
|
1555
|
+
const eventName = args.eventName?.trim();
|
|
1556
|
+
if (!eventName) {
|
|
1557
|
+
return { content: JSON.stringify({ success: false, error: "Не передано имя события." }) };
|
|
1558
|
+
}
|
|
1559
|
+
const payload = args.payload ?? {};
|
|
1560
|
+
const definitions = await loadTaskDefinitions();
|
|
1561
|
+
const matched = definitions
|
|
1562
|
+
.filter((def) => def.triggerType === "mcp-event" &&
|
|
1563
|
+
def.mcpEvent?.event?.toLowerCase() === eventName.toLowerCase() &&
|
|
1564
|
+
matchesEventFilter(def.mcpEvent?.filter, payload))
|
|
1565
|
+
.sort((a, b) => (normalizePriority(b.priority) ?? 0) - (normalizePriority(a.priority) ?? 0));
|
|
1566
|
+
const triggered = [];
|
|
1567
|
+
for (const def of matched) {
|
|
1568
|
+
try {
|
|
1569
|
+
await runTaskEntry(def.name);
|
|
1570
|
+
triggered.push(def.name);
|
|
1571
|
+
}
|
|
1572
|
+
catch (err) {
|
|
1573
|
+
console.error(`[windows-scheduler] emit_event: не удалось запустить ${def.name}:`, err);
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
return {
|
|
1577
|
+
content: JSON.stringify({
|
|
1578
|
+
success: true,
|
|
1579
|
+
message: triggered.length > 0
|
|
1580
|
+
? `Запущено задач: ${triggered.length}.`
|
|
1581
|
+
: `Нет задач, подписанных на событие "${eventName}".`,
|
|
1582
|
+
triggered,
|
|
1583
|
+
}),
|
|
1584
|
+
};
|
|
1585
|
+
});
|
|
1586
|
+
/**
|
|
1587
|
+
* Менеджер файловых триггеров живёт на уровне модуля, чтобы его можно было
|
|
1588
|
+
* обновлять после создания/изменения/удаления задачи. Раньше refresh()
|
|
1589
|
+
* вызывался только при старте плагина, из-за чего новые watchPath начинали
|
|
1590
|
+
* работать лишь после перезапуска OpenCode.
|
|
1591
|
+
*/
|
|
1592
|
+
let fileWatcherManager = null;
|
|
1593
|
+
async function refreshFileTriggers() {
|
|
1594
|
+
if (!fileWatcherManager)
|
|
1595
|
+
return;
|
|
1596
|
+
try {
|
|
1597
|
+
await fileWatcherManager.refresh();
|
|
1598
|
+
}
|
|
1599
|
+
catch (err) {
|
|
1600
|
+
console.error(`[windows-scheduler] Не удалось обновить файловые триггеры: ${err instanceof Error ? err.message : String(err)}`);
|
|
1601
|
+
}
|
|
1602
|
+
}
|
|
945
1603
|
export default Plugin.define({
|
|
946
1604
|
id: "opencode-windows-scheduler",
|
|
947
1605
|
setup: async (ctx) => {
|
|
@@ -978,6 +1636,28 @@ export default Plugin.define({
|
|
|
978
1636
|
.catch((err) => {
|
|
979
1637
|
console.error(`[retention] Не удалось очистить историю: ${err instanceof Error ? err.message : String(err)}`);
|
|
980
1638
|
});
|
|
1639
|
+
// Спринт 19: автопродолжение задач, поставленных на паузу до даты.
|
|
1640
|
+
// Проверяем сразу при старте и далее раз в 5 минут, пока плагин жив.
|
|
1641
|
+
void resumeExpiredPauses().catch((err) => {
|
|
1642
|
+
console.error(`[windows-scheduler] Не удалось проверить автопродолжение: ${err instanceof Error ? err.message : String(err)}`);
|
|
1643
|
+
});
|
|
1644
|
+
const pausedUntilTimer = setInterval(() => {
|
|
1645
|
+
void resumeExpiredPauses().catch((err) => {
|
|
1646
|
+
console.error(`[windows-scheduler] Не удалось проверить автопродолжение: ${err instanceof Error ? err.message : String(err)}`);
|
|
1647
|
+
});
|
|
1648
|
+
}, PAUSED_UNTIL_CHECK_MS);
|
|
1649
|
+
pausedUntilTimer.unref?.();
|
|
1650
|
+
// Спринт 20: дайджест и детектор зависших матриц. Проверяем сразу при
|
|
1651
|
+
// старте и далее раз в минуту; таймер не держит процесс Node живым.
|
|
1652
|
+
const notificationTimer = setInterval(() => {
|
|
1653
|
+
void maybeSendDigest().catch(() => undefined);
|
|
1654
|
+
void checkStuckMatrices().catch((err) => {
|
|
1655
|
+
console.error(`[windows-scheduler] Детектор зависших матриц: ${err instanceof Error ? err.message : String(err)}`);
|
|
1656
|
+
});
|
|
1657
|
+
}, NOTIFICATION_CHECK_MS);
|
|
1658
|
+
notificationTimer.unref?.();
|
|
1659
|
+
void maybeSendDigest().catch(() => undefined);
|
|
1660
|
+
void checkStuckMatrices().catch(() => undefined);
|
|
981
1661
|
// Инициализация блокировок: создаём директорию и очищаем зависшие lock-файлы (>24 ч).
|
|
982
1662
|
const lockManager = new LockManager(LOCK_DIR);
|
|
983
1663
|
await lockManager.initialize();
|
|
@@ -998,20 +1678,23 @@ export default Plugin.define({
|
|
|
998
1678
|
continue;
|
|
999
1679
|
if (!def.schedule)
|
|
1000
1680
|
continue;
|
|
1001
|
-
|
|
1002
|
-
if (
|
|
1681
|
+
// Задача на паузе до даты — её включит авто-продолжение.
|
|
1682
|
+
if (def.pausedUntil)
|
|
1683
|
+
continue;
|
|
1684
|
+
const prev = prevRun(def.schedule, now, def.timezone);
|
|
1685
|
+
if (!prev)
|
|
1003
1686
|
continue;
|
|
1004
|
-
const ageMs = now.getTime() -
|
|
1687
|
+
const ageMs = now.getTime() - prev.getTime();
|
|
1005
1688
|
if (ageMs < catchUpThresholdMs)
|
|
1006
1689
|
continue;
|
|
1007
1690
|
// Есть ли запись в истории после предполагаемого времени запуска?
|
|
1008
1691
|
const ranAfter = history.some((r) => r.taskName.toLowerCase() === def.name.toLowerCase() &&
|
|
1009
|
-
new Date(r.startedAt).getTime() >=
|
|
1692
|
+
new Date(r.startedAt).getTime() >= prev.getTime());
|
|
1010
1693
|
if (ranAfter)
|
|
1011
1694
|
continue;
|
|
1012
1695
|
// Запускаем задачу и пишем в лог.
|
|
1013
1696
|
try {
|
|
1014
|
-
await
|
|
1697
|
+
await runTaskEntry(def.name);
|
|
1015
1698
|
console.log(`[windows-scheduler] Запущено восстановление пропущенной задачи "${def.name}" (последний срабатывал ~${Math.round(ageMs / 1000)} с назад).`);
|
|
1016
1699
|
}
|
|
1017
1700
|
catch (err) {
|
|
@@ -1025,16 +1708,16 @@ export default Plugin.define({
|
|
|
1025
1708
|
})();
|
|
1026
1709
|
// Файловые триггеры (File Watchers): задачи с triggerType === "file"
|
|
1027
1710
|
// запускаются при изменении watchPath через chokidar (с дебаунсом).
|
|
1028
|
-
|
|
1711
|
+
fileWatcherManager = new FileWatchManager(async (taskName) => {
|
|
1029
1712
|
try {
|
|
1030
|
-
await
|
|
1713
|
+
await runTaskEntry(taskName);
|
|
1031
1714
|
console.log(`[windows-scheduler] Запуск задачи "${taskName}" по изменению отслеживаемого файла.`);
|
|
1032
1715
|
}
|
|
1033
1716
|
catch (err) {
|
|
1034
1717
|
console.error(`[windows-scheduler] Не удалось запустить задачу "${taskName}" по файловому триггеру: ${err instanceof Error ? err.message : String(err)}`);
|
|
1035
1718
|
}
|
|
1036
1719
|
});
|
|
1037
|
-
void
|
|
1720
|
+
void refreshFileTriggers();
|
|
1038
1721
|
const registration = await ctx.tool.transform((editor) => {
|
|
1039
1722
|
// editor.add регистрирует новые инструменты плагина с codemode: true,
|
|
1040
1723
|
// чтобы они были видны в Code Mode. Встроенные schedule_* отключены
|
|
@@ -1126,10 +1809,80 @@ export default Plugin.define({
|
|
|
1126
1809
|
editor.add({
|
|
1127
1810
|
name: "matrix_control",
|
|
1128
1811
|
input: matrixControlSchema,
|
|
1129
|
-
description: "Matrix lifecycle: results (aggregate status/counters of a matrix), cancel (cancel pending clones, stop running ones)
|
|
1812
|
+
description: "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).",
|
|
1130
1813
|
options: { codemode: true },
|
|
1131
1814
|
execute: matrixControlExecute,
|
|
1132
1815
|
});
|
|
1816
|
+
editor.add({
|
|
1817
|
+
name: "get_metrics",
|
|
1818
|
+
input: getMetricsSchema,
|
|
1819
|
+
description: "Returns aggregate run metrics: total runs, successes and failures across all tasks.",
|
|
1820
|
+
options: { codemode: true },
|
|
1821
|
+
execute: getMetricsExecute,
|
|
1822
|
+
});
|
|
1823
|
+
editor.add({
|
|
1824
|
+
name: "get_analytics",
|
|
1825
|
+
input: getAnalyticsSchema,
|
|
1826
|
+
description: "Returns an analytics report for a period: run counts, success rate, duration, tokens and cost, plus top tasks.",
|
|
1827
|
+
options: { codemode: true },
|
|
1828
|
+
execute: getAnalyticsExecute,
|
|
1829
|
+
});
|
|
1830
|
+
editor.add({
|
|
1831
|
+
name: "manage_settings",
|
|
1832
|
+
input: manageSettingsSchema,
|
|
1833
|
+
description: "Reads or updates global scheduler settings: maxConcurrent, winterMode, notifications (webhook, filters, matrix alerts, digest) and history retention. Updates are merged into the current settings.",
|
|
1834
|
+
options: { codemode: true },
|
|
1835
|
+
execute: manageSettingsExecute,
|
|
1836
|
+
});
|
|
1837
|
+
editor.add({
|
|
1838
|
+
name: "manage_templates",
|
|
1839
|
+
input: manageTemplatesSchema,
|
|
1840
|
+
description: "Lists, saves or deletes reusable task templates (prompt, schedule, retries, Quality Gate, chains, triggers, tool restrictions).",
|
|
1841
|
+
options: { codemode: true },
|
|
1842
|
+
execute: manageTemplatesExecute,
|
|
1843
|
+
});
|
|
1844
|
+
editor.add({
|
|
1845
|
+
name: "manage_profiles",
|
|
1846
|
+
input: manageProfilesSchema,
|
|
1847
|
+
description: "Lists, creates, switches or deletes isolated scheduler profiles (separate database, settings and dashboard port). Switching requires an OpenCode restart.",
|
|
1848
|
+
options: { codemode: true },
|
|
1849
|
+
execute: manageProfilesExecute,
|
|
1850
|
+
});
|
|
1851
|
+
editor.add({
|
|
1852
|
+
name: "transfer_tasks",
|
|
1853
|
+
input: transferTasksSchema,
|
|
1854
|
+
description: "Exports all tasks as a portable JSON snapshot or imports tasks from such a snapshot, recreating them in the OS scheduler.",
|
|
1855
|
+
options: { codemode: true },
|
|
1856
|
+
execute: transferTasksExecute,
|
|
1857
|
+
});
|
|
1858
|
+
editor.add({
|
|
1859
|
+
name: "send_notification",
|
|
1860
|
+
input: sendNotificationSchema,
|
|
1861
|
+
description: "Sends a test notification through the configured channel or sends the digest immediately.",
|
|
1862
|
+
options: { codemode: true },
|
|
1863
|
+
execute: sendNotificationExecute,
|
|
1864
|
+
});
|
|
1865
|
+
editor.add({
|
|
1866
|
+
name: "get_dashboard_info",
|
|
1867
|
+
input: getDashboardInfoSchema,
|
|
1868
|
+
description: "Returns dashboard port and URL, OS platform, scheduler title and the active profile.",
|
|
1869
|
+
options: { codemode: true },
|
|
1870
|
+
execute: getDashboardInfoExecute,
|
|
1871
|
+
});
|
|
1872
|
+
editor.add({
|
|
1873
|
+
name: "cleanup_history",
|
|
1874
|
+
input: cleanupHistorySchema,
|
|
1875
|
+
description: "Deletes old run history by age and/or record cap, using the stored retention policy unless overridden.",
|
|
1876
|
+
options: { codemode: true },
|
|
1877
|
+
execute: cleanupHistoryExecute,
|
|
1878
|
+
});
|
|
1879
|
+
editor.add({
|
|
1880
|
+
name: "emit_event",
|
|
1881
|
+
input: emitEventSchema,
|
|
1882
|
+
description: "Emits an MCP event: every task with triggerType 'mcp-event' matching the event name (and filter) is started in priority order.",
|
|
1883
|
+
options: { codemode: true },
|
|
1884
|
+
execute: emitEventExecute,
|
|
1885
|
+
});
|
|
1133
1886
|
});
|
|
1134
1887
|
// Нативный скилл плагина: агент видит краткое описание в списке доступных
|
|
1135
1888
|
// скиллов и подгружает инструкцию только когда задача действительно про
|
|
@@ -1162,9 +1915,9 @@ export default Plugin.define({
|
|
|
1162
1915
|
},
|
|
1163
1916
|
create_task: async (input) => {
|
|
1164
1917
|
console.log("[windows-scheduler] create_task input:", input);
|
|
1165
|
-
const { name, schedule, prompt, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, dependsOn, triggerType, watchPath, workingDirectory, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, } = input;
|
|
1918
|
+
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, } = input;
|
|
1166
1919
|
try {
|
|
1167
|
-
await schedulerCreateTask(name, schedule, prompt, undefined, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix);
|
|
1920
|
+
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);
|
|
1168
1921
|
return { success: true, message: `Задача "${name}" успешно создана.` };
|
|
1169
1922
|
}
|
|
1170
1923
|
catch (err) {
|
|
@@ -1279,7 +2032,7 @@ export default Plugin.define({
|
|
|
1279
2032
|
const triggered = [];
|
|
1280
2033
|
for (const def of matched) {
|
|
1281
2034
|
try {
|
|
1282
|
-
await
|
|
2035
|
+
await runTaskEntry(def.name);
|
|
1283
2036
|
triggered.push(def.name);
|
|
1284
2037
|
console.log(`[windows-scheduler] Запуск задачи "${def.name}" по MCP-событию "${normalized}".`);
|
|
1285
2038
|
}
|
|
@@ -1294,8 +2047,8 @@ export default Plugin.define({
|
|
|
1294
2047
|
};
|
|
1295
2048
|
},
|
|
1296
2049
|
pause_task: async (input) => {
|
|
1297
|
-
const { name } = input;
|
|
1298
|
-
const result = await pauseOrResumeTask(name, true);
|
|
2050
|
+
const { name, until } = input;
|
|
2051
|
+
const result = await pauseOrResumeTask(name, true, until);
|
|
1299
2052
|
return { success: result.success, message: result.message };
|
|
1300
2053
|
},
|
|
1301
2054
|
resume_task: async (input) => {
|
|
@@ -1315,8 +2068,9 @@ export default Plugin.define({
|
|
|
1315
2068
|
return { success: true, logs: result.logs };
|
|
1316
2069
|
},
|
|
1317
2070
|
get_history: async (input) => {
|
|
1318
|
-
const { limit } = input;
|
|
1319
|
-
const
|
|
2071
|
+
const { limit, taskName } = input;
|
|
2072
|
+
const filter = taskName?.trim().toLowerCase();
|
|
2073
|
+
const records = (await loadHistory()).filter((record) => !filter || record.taskName.toLowerCase() === filter);
|
|
1320
2074
|
return { records: records.slice(0, limit ?? 10) };
|
|
1321
2075
|
},
|
|
1322
2076
|
get_metrics: async () => {
|
|
@@ -1479,15 +2233,23 @@ export default Plugin.define({
|
|
|
1479
2233
|
return {
|
|
1480
2234
|
workspaces: listWorkspaces().map((workspace) => ({
|
|
1481
2235
|
...workspace,
|
|
2236
|
+
env: maskEnvForLog(workspace.env),
|
|
1482
2237
|
gitBranch: readGitBranch(workspace.path) ?? null,
|
|
1483
2238
|
})),
|
|
1484
2239
|
};
|
|
1485
2240
|
},
|
|
1486
2241
|
add_workspace: async (input) => {
|
|
1487
2242
|
try {
|
|
1488
|
-
const { name, path: workspacePath, color } = input;
|
|
1489
|
-
const workspace = addWorkspace({ name, path: workspacePath, color });
|
|
1490
|
-
return {
|
|
2243
|
+
const { name, path: workspacePath, color, env, envFile } = input;
|
|
2244
|
+
const workspace = addWorkspace({ name, path: workspacePath, color, env, envFile });
|
|
2245
|
+
return {
|
|
2246
|
+
success: true,
|
|
2247
|
+
workspace: {
|
|
2248
|
+
...workspace,
|
|
2249
|
+
env: maskEnvForLog(workspace.env),
|
|
2250
|
+
gitBranch: readGitBranch(workspace.path) ?? null,
|
|
2251
|
+
},
|
|
2252
|
+
};
|
|
1491
2253
|
}
|
|
1492
2254
|
catch (err) {
|
|
1493
2255
|
return { success: false, error: err instanceof Error ? err.message : String(err) };
|
|
@@ -1495,12 +2257,21 @@ export default Plugin.define({
|
|
|
1495
2257
|
},
|
|
1496
2258
|
update_workspace: async (input) => {
|
|
1497
2259
|
try {
|
|
1498
|
-
const { id, name, path: workspacePath, color } = input;
|
|
1499
|
-
const workspace = updateWorkspace(id, { name, path: workspacePath, color });
|
|
2260
|
+
const { id, name, path: workspacePath, color, env, envFile } = input;
|
|
2261
|
+
const workspace = updateWorkspace(id, { name, path: workspacePath, color, env, envFile });
|
|
1500
2262
|
if (!workspace) {
|
|
1501
2263
|
return { success: false, error: "Workspace не найден." };
|
|
1502
2264
|
}
|
|
1503
|
-
|
|
2265
|
+
// env-файлы существующих задач перегенерируются сразу (Спринт 21).
|
|
2266
|
+
await refreshWorkspaceEnvFiles(workspace.id);
|
|
2267
|
+
return {
|
|
2268
|
+
success: true,
|
|
2269
|
+
workspace: {
|
|
2270
|
+
...workspace,
|
|
2271
|
+
env: maskEnvForLog(workspace.env),
|
|
2272
|
+
gitBranch: readGitBranch(workspace.path) ?? null,
|
|
2273
|
+
},
|
|
2274
|
+
};
|
|
1504
2275
|
}
|
|
1505
2276
|
catch (err) {
|
|
1506
2277
|
return { success: false, error: err instanceof Error ? err.message : String(err) };
|
|
@@ -1521,6 +2292,75 @@ export default Plugin.define({
|
|
|
1521
2292
|
return { success: false, message: err instanceof Error ? err.message : String(err) };
|
|
1522
2293
|
}
|
|
1523
2294
|
},
|
|
2295
|
+
get_profiles: async () => {
|
|
2296
|
+
return {
|
|
2297
|
+
current: getProfileName(),
|
|
2298
|
+
pinnedByEnv: isProfilePinnedByEnv(),
|
|
2299
|
+
profiles: listProfiles(),
|
|
2300
|
+
};
|
|
2301
|
+
},
|
|
2302
|
+
set_profile: async (input) => {
|
|
2303
|
+
const { name } = input;
|
|
2304
|
+
try {
|
|
2305
|
+
setActiveProfile(name);
|
|
2306
|
+
const current = getProfileName();
|
|
2307
|
+
return {
|
|
2308
|
+
success: true,
|
|
2309
|
+
current,
|
|
2310
|
+
restartRequired: true,
|
|
2311
|
+
message: isProfilePinnedByEnv()
|
|
2312
|
+
? `Профиль задан переменной OPENCODE_SCHEDULER_PROFILE=${current}. Перезапустите OpenCode, чтобы применить изменения.`
|
|
2313
|
+
: `Активный профиль: ${sanitizeProfileName(name)}. Перезапустите OpenCode, чтобы применить изменения.`,
|
|
2314
|
+
};
|
|
2315
|
+
}
|
|
2316
|
+
catch (err) {
|
|
2317
|
+
return {
|
|
2318
|
+
success: false,
|
|
2319
|
+
current: getProfileName(),
|
|
2320
|
+
restartRequired: false,
|
|
2321
|
+
message: err instanceof Error ? err.message : String(err),
|
|
2322
|
+
};
|
|
2323
|
+
}
|
|
2324
|
+
},
|
|
2325
|
+
create_profile: async (input) => {
|
|
2326
|
+
const { name, port } = input;
|
|
2327
|
+
try {
|
|
2328
|
+
const meta = createProfile(name, port);
|
|
2329
|
+
const profile = listProfiles().find((item) => item.name === meta.name);
|
|
2330
|
+
return {
|
|
2331
|
+
success: true,
|
|
2332
|
+
message: `Профиль "${meta.name}" создан (порт дашборда ${meta.port}).`,
|
|
2333
|
+
profile: profile ?? {
|
|
2334
|
+
name: meta.name,
|
|
2335
|
+
dir: getProfileDir(meta.name),
|
|
2336
|
+
port: meta.port,
|
|
2337
|
+
isDefault: meta.name === DEFAULT_PROFILE,
|
|
2338
|
+
active: meta.name === getProfileName(),
|
|
2339
|
+
},
|
|
2340
|
+
};
|
|
2341
|
+
}
|
|
2342
|
+
catch (err) {
|
|
2343
|
+
return {
|
|
2344
|
+
success: false,
|
|
2345
|
+
error: err instanceof Error ? err.message : String(err),
|
|
2346
|
+
};
|
|
2347
|
+
}
|
|
2348
|
+
},
|
|
2349
|
+
delete_profile: async (input) => {
|
|
2350
|
+
const { name } = input;
|
|
2351
|
+
try {
|
|
2352
|
+
const removed = deleteProfile(name);
|
|
2353
|
+
return {
|
|
2354
|
+
success: removed,
|
|
2355
|
+
message: removed
|
|
2356
|
+
? `Профиль "${sanitizeProfileName(name)}" удалён вместе с его БД и настройками.`
|
|
2357
|
+
: "Профиль не найден.",
|
|
2358
|
+
};
|
|
2359
|
+
}
|
|
2360
|
+
catch (err) {
|
|
2361
|
+
return { success: false, message: err instanceof Error ? err.message : String(err) };
|
|
2362
|
+
}
|
|
2363
|
+
},
|
|
1524
2364
|
get_settings: async () => {
|
|
1525
2365
|
return await loadSettings();
|
|
1526
2366
|
},
|
|
@@ -1556,6 +2396,10 @@ export default Plugin.define({
|
|
|
1556
2396
|
test_notification: async () => {
|
|
1557
2397
|
return await sendTestNotification();
|
|
1558
2398
|
},
|
|
2399
|
+
send_digest: async () => {
|
|
2400
|
+
// Ручная отправка не сдвигает плановое расписание дайджеста.
|
|
2401
|
+
return await sendDigestNow({ updateLastSentAt: false });
|
|
2402
|
+
},
|
|
1559
2403
|
get_templates: async () => {
|
|
1560
2404
|
try {
|
|
1561
2405
|
return { templates: await loadTemplates() };
|
|
@@ -1643,7 +2487,7 @@ export default Plugin.define({
|
|
|
1643
2487
|
const errors = [...parsed.errors];
|
|
1644
2488
|
for (const def of parsed.tasks) {
|
|
1645
2489
|
try {
|
|
1646
|
-
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);
|
|
2490
|
+
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);
|
|
1647
2491
|
await saveTaskDefinition(def);
|
|
1648
2492
|
imported.push(def.name);
|
|
1649
2493
|
}
|
|
@@ -1683,10 +2527,13 @@ export default Plugin.define({
|
|
|
1683
2527
|
console.log(`[windows-scheduler] Открыть дашборд в браузере: http://localhost:${dashboard.port}`);
|
|
1684
2528
|
}
|
|
1685
2529
|
return () => {
|
|
2530
|
+
clearInterval(pausedUntilTimer);
|
|
2531
|
+
clearInterval(notificationTimer);
|
|
1686
2532
|
rpcRegistration.dispose();
|
|
1687
2533
|
registration.dispose();
|
|
1688
2534
|
void skillRegistration?.dispose();
|
|
1689
|
-
|
|
2535
|
+
if (fileWatcherManager)
|
|
2536
|
+
void fileWatcherManager.stop();
|
|
1690
2537
|
// При выгрузке плагина обязательно закрываем HTTP-сервер дашборда,
|
|
1691
2538
|
// затем соединение SQLite (чекпойнт WAL выполняется в closeDb).
|
|
1692
2539
|
void closeDashboardServer().finally(() => closeDb());
|
|
@@ -1744,11 +2591,23 @@ function resolveMatrixExtraConfig(name, matrix, ids) {
|
|
|
1744
2591
|
*/
|
|
1745
2592
|
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,
|
|
1746
2593
|
/** create — пересоздать клонов с нуля; sync — только diff (Спринт 17). */
|
|
1747
|
-
matrixMode = "create"
|
|
2594
|
+
matrixMode = "create",
|
|
2595
|
+
/** IANA-зона задачи (Спринт 19). Не системная зона → poll-режим шлюза. */
|
|
2596
|
+
timezone,
|
|
2597
|
+
/** Окно запуска: начало "HH:MM" (вне окна запуск переносится). */
|
|
2598
|
+
notBefore,
|
|
2599
|
+
/** Окончание окна "HH:MM"; может быть меньше notBefore (через полночь). */
|
|
2600
|
+
notAfter,
|
|
2601
|
+
/** Пауза до момента ISO; после него задача возобновляется автоматически. */
|
|
2602
|
+
pausedUntil) {
|
|
1748
2603
|
const normalizedModel = model?.trim() || undefined;
|
|
1749
2604
|
const normalizedPriority = normalizePriority(priority);
|
|
1750
2605
|
const normalizedBefore = beforeScript?.trim() || undefined;
|
|
1751
2606
|
const normalizedAfter = afterScript?.trim() || undefined;
|
|
2607
|
+
const normalizedTz = timezone?.trim() || undefined;
|
|
2608
|
+
const normalizedNotBefore = notBefore?.trim() || undefined;
|
|
2609
|
+
const normalizedNotAfter = notAfter?.trim() || undefined;
|
|
2610
|
+
const normalizedPausedUntil = pausedUntil?.trim() || undefined;
|
|
1752
2611
|
const normalizedMcpEvent = mcpEvent && mcpEvent.event?.trim()
|
|
1753
2612
|
? {
|
|
1754
2613
|
server: mcpEvent.server?.trim() || "",
|
|
@@ -1823,15 +2682,38 @@ matrixMode = "create") {
|
|
|
1823
2682
|
// расписание не используется вовсе.
|
|
1824
2683
|
if (effectiveTriggerType === "cron") {
|
|
1825
2684
|
try {
|
|
1826
|
-
|
|
2685
|
+
// Расширенная грамматика (Спринт 19): диапазоны, списки, шаги,
|
|
2686
|
+
// имена месяцев/дней, @every, L и FRI#3.
|
|
2687
|
+
parseCron(schedule);
|
|
1827
2688
|
}
|
|
1828
2689
|
catch (err) {
|
|
1829
2690
|
throw new Error(err.message || String(err));
|
|
1830
2691
|
}
|
|
2692
|
+
if (normalizedTz && !isValidIanaTimeZone(normalizedTz)) {
|
|
2693
|
+
throw new Error(`Задача "${name}": неизвестный часовой пояс "${normalizedTz}". ` +
|
|
2694
|
+
`Укажите IANA-зону, например Europe/Moscow.`);
|
|
2695
|
+
}
|
|
2696
|
+
const windowError = validateLaunchWindow(normalizedNotBefore, normalizedNotAfter);
|
|
2697
|
+
if (windowError) {
|
|
2698
|
+
throw new Error(`Задача "${name}": ${windowError}`);
|
|
2699
|
+
}
|
|
1831
2700
|
}
|
|
1832
2701
|
const sanitized = sanitizeName(name);
|
|
1833
2702
|
const lockFile = lockFilePath(sanitized);
|
|
1834
2703
|
const logFile = path.join(LOG_DIR, `${sanitized}.log`);
|
|
2704
|
+
// Шлюз расписания (Спринт 19): нужен только для cron в poll-режиме
|
|
2705
|
+
// (нестандартный cron или чужая IANA-зона) либо при окне запуска.
|
|
2706
|
+
const gate = effectiveTriggerType === "cron"
|
|
2707
|
+
? buildScheduleGate(schedule, normalizedTz, normalizedNotBefore, normalizedNotAfter)
|
|
2708
|
+
: undefined;
|
|
2709
|
+
const wrapperGate = gate
|
|
2710
|
+
? {
|
|
2711
|
+
...gate,
|
|
2712
|
+
gateFile: gatePath,
|
|
2713
|
+
deferFile: `${lockFile}.defer`,
|
|
2714
|
+
forceFile: `${lockFile}.force`,
|
|
2715
|
+
}
|
|
2716
|
+
: undefined;
|
|
1835
2717
|
// Workspace имеет приоритет над workingDirectory: одна задача = один repo
|
|
1836
2718
|
// = один cwd. Мы не угадываем, куда мержить, и не смешиваем контексты.
|
|
1837
2719
|
const normalizedWorkspaceId = workspaceId?.trim() || undefined;
|
|
@@ -1852,6 +2734,12 @@ matrixMode = "create") {
|
|
|
1852
2734
|
}
|
|
1853
2735
|
}
|
|
1854
2736
|
const effectiveWorkingDirectory = workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
|
|
2737
|
+
// Спринт 21: env-переменные workspace → отдельный файл, который читает обёртка.
|
|
2738
|
+
// Значения не логируются; в лог попадает только факт загрузки.
|
|
2739
|
+
const taskEnvFile = writeWorkspaceEnvFile(workspace, PLUGIN_DIR, sanitized);
|
|
2740
|
+
if (taskEnvFile) {
|
|
2741
|
+
console.log(`[workspace] Задача "${name}": env-переменные workspace подключены.`);
|
|
2742
|
+
}
|
|
1855
2743
|
let promptFile;
|
|
1856
2744
|
try {
|
|
1857
2745
|
promptFile = await writePromptFile(sanitized, prompt);
|
|
@@ -1868,7 +2756,7 @@ matrixMode = "create") {
|
|
|
1868
2756
|
try {
|
|
1869
2757
|
if (scheduler.platform === "win32") {
|
|
1870
2758
|
await ensureWrapper();
|
|
1871
|
-
wrapperPath = await writeWrapperCmd(sanitized, name, promptFile, timeoutSeconds ?? 3600, lockFile, effectiveWorkingDirectory, logFile, recorderPath, qualityGate, normalizedModel, normalizedBefore, normalizedAfter, workspace?.name, normalizedAllowedTools, normalizedDeniedTools);
|
|
2759
|
+
wrapperPath = await writeWrapperCmd(sanitized, name, promptFile, timeoutSeconds ?? 3600, lockFile, effectiveWorkingDirectory, logFile, recorderPath, qualityGate, normalizedModel, normalizedBefore, normalizedAfter, workspace?.name, normalizedAllowedTools, normalizedDeniedTools, wrapperGate, taskEnvFile);
|
|
1872
2760
|
}
|
|
1873
2761
|
else {
|
|
1874
2762
|
wrapperPath = await writeBashWrapper({
|
|
@@ -1887,6 +2775,8 @@ matrixMode = "create") {
|
|
|
1887
2775
|
workspaceName: workspace?.name,
|
|
1888
2776
|
allowedTools: normalizedAllowedTools,
|
|
1889
2777
|
deniedTools: normalizedDeniedTools,
|
|
2778
|
+
scheduleGate: wrapperGate,
|
|
2779
|
+
envFile: taskEnvFile,
|
|
1890
2780
|
});
|
|
1891
2781
|
}
|
|
1892
2782
|
}
|
|
@@ -1905,6 +2795,9 @@ matrixMode = "create") {
|
|
|
1905
2795
|
logFile,
|
|
1906
2796
|
model: normalizedModel,
|
|
1907
2797
|
priority: normalizedPriority,
|
|
2798
|
+
timezone: normalizedTz,
|
|
2799
|
+
notBefore: normalizedNotBefore,
|
|
2800
|
+
notAfter: normalizedNotAfter,
|
|
1908
2801
|
});
|
|
1909
2802
|
}
|
|
1910
2803
|
catch (err) {
|
|
@@ -1931,6 +2824,10 @@ matrixMode = "create") {
|
|
|
1931
2824
|
nextTaskOnError,
|
|
1932
2825
|
triggerType: effectiveTriggerType,
|
|
1933
2826
|
watchPath: normalizedMatrix ? undefined : watchPath,
|
|
2827
|
+
timezone: normalizedTz,
|
|
2828
|
+
notBefore: normalizedNotBefore,
|
|
2829
|
+
notAfter: normalizedNotAfter,
|
|
2830
|
+
pausedUntil: normalizedPausedUntil,
|
|
1934
2831
|
allowedTools: normalizedAllowedTools,
|
|
1935
2832
|
deniedTools: normalizedDeniedTools,
|
|
1936
2833
|
matrix: normalizedMatrix,
|
|
@@ -1959,7 +2856,7 @@ matrixMode = "create") {
|
|
|
1959
2856
|
// с нуля, а синхронизируются с новым определением; выполняющиеся — не трогаем.
|
|
1960
2857
|
if (normalizedMatrix) {
|
|
1961
2858
|
const createClone = async (clone) => {
|
|
1962
|
-
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);
|
|
2859
|
+
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);
|
|
1963
2860
|
};
|
|
1964
2861
|
const removeChild = async (child) => {
|
|
1965
2862
|
try {
|
|
@@ -2030,7 +2927,22 @@ async function runTaskEntry(name) {
|
|
|
2030
2927
|
await runMatrix(definition);
|
|
2031
2928
|
return { alreadyRunning: false };
|
|
2032
2929
|
}
|
|
2033
|
-
|
|
2930
|
+
// Любой запуск через этот вход — «сейчас», а не «по расписанию»:
|
|
2931
|
+
// run_task_now, RPC GUI, файловый триггер, MCP-событие и catch-up.
|
|
2932
|
+
// Маркер снимает проверку cron/окна внутри обёртки (poll-режим), иначе
|
|
2933
|
+
// запуск молча отменялся бы schedule-gate с кодом 3.
|
|
2934
|
+
const forceFile = await requestImmediateRun(name);
|
|
2935
|
+
try {
|
|
2936
|
+
return await scheduler.runTask(name);
|
|
2937
|
+
}
|
|
2938
|
+
catch (err) {
|
|
2939
|
+
// Планировщик не принял запуск — маркер не нужен, иначе он мог бы
|
|
2940
|
+
// «разрешить» следующий плановый тик в обход расписания.
|
|
2941
|
+
await fs.unlink(forceFile).catch(() => {
|
|
2942
|
+
/* не критично */
|
|
2943
|
+
});
|
|
2944
|
+
throw err;
|
|
2945
|
+
}
|
|
2034
2946
|
}
|
|
2035
2947
|
/**
|
|
2036
2948
|
* Собирает задачи плагина в формате, который отдают оба потребителя:
|
|
@@ -2051,7 +2963,37 @@ async function collectTasksView() {
|
|
|
2051
2963
|
const defs = await loadTaskDefinitions();
|
|
2052
2964
|
const workspaces = listWorkspaces();
|
|
2053
2965
|
const workspaceById = new Map(workspaces.map((workspace) => [workspace.id, workspace]));
|
|
2054
|
-
|
|
2966
|
+
// Счётчики запусков по задачам. Основной источник — таблица metrics
|
|
2967
|
+
// (накопительные итоги, не зависят от retention истории). Для задач, у
|
|
2968
|
+
// которых метрик ещё нет, считаем по загруженной истории.
|
|
2969
|
+
const metricsByName = new Map(getAllMetrics(true).map((row) => [row.taskName.toLowerCase(), row]));
|
|
2970
|
+
const historyCounts = new Map();
|
|
2971
|
+
for (const record of history) {
|
|
2972
|
+
const key = record.taskName.toLowerCase();
|
|
2973
|
+
const counts = historyCounts.get(key) ?? { total: 0, success: 0, error: 0 };
|
|
2974
|
+
counts.total += 1;
|
|
2975
|
+
if (record.status === "success")
|
|
2976
|
+
counts.success += 1;
|
|
2977
|
+
else
|
|
2978
|
+
counts.error += 1;
|
|
2979
|
+
historyCounts.set(key, counts);
|
|
2980
|
+
}
|
|
2981
|
+
// ОС-планировщик — источник истины о запуске, но определения в БД могут
|
|
2982
|
+
// существовать без задачи в ОС (сбой удаления, миграция, ручная чистка).
|
|
2983
|
+
// Показываем и их, помечая orphaned: раньше такие задачи были невидимы
|
|
2984
|
+
// для list_tasks, хотя dry_run/история их видели.
|
|
2985
|
+
const osNames = new Set(tasks.map((t) => (t.taskName || "").toLowerCase()));
|
|
2986
|
+
const orphanNames = defs
|
|
2987
|
+
.filter((def) => !osNames.has(def.name.toLowerCase()))
|
|
2988
|
+
.map((def) => def.name);
|
|
2989
|
+
const sources = [
|
|
2990
|
+
...tasks.map((task) => ({ task, orphaned: false })),
|
|
2991
|
+
...orphanNames.map((name) => ({
|
|
2992
|
+
task: { taskName: name },
|
|
2993
|
+
orphaned: true,
|
|
2994
|
+
})),
|
|
2995
|
+
];
|
|
2996
|
+
return sources.map(({ task: t, orphaned }) => {
|
|
2055
2997
|
// Все бэкенды возвращают короткие имена (без папки планировщика).
|
|
2056
2998
|
const name = t.taskName || "";
|
|
2057
2999
|
// Приоритет 1: статус, который сообщает планировщик ОС.
|
|
@@ -2071,10 +3013,20 @@ async function collectTasksView() {
|
|
|
2071
3013
|
if (matrixAggregate && matrixAggregate.status !== "empty") {
|
|
2072
3014
|
status = matrixAggregate.status === "running" ? "running" : matrixAggregate.status;
|
|
2073
3015
|
}
|
|
3016
|
+
// Счётчики именно этой задачи (раньше GUI показывал на каждой карточке
|
|
3017
|
+
// общие итоги по всем задачам — отсюда одинаковые 201/130/71).
|
|
3018
|
+
const metricsRow = metricsByName.get(name.toLowerCase());
|
|
3019
|
+
const counts = metricsRow
|
|
3020
|
+
? { total: metricsRow.total, success: metricsRow.success, error: metricsRow.error }
|
|
3021
|
+
: historyCounts.get(name.toLowerCase()) ?? { total: 0, success: 0, error: 0 };
|
|
2074
3022
|
return {
|
|
2075
3023
|
name,
|
|
2076
3024
|
schedule: def?.schedule ?? "",
|
|
2077
3025
|
status,
|
|
3026
|
+
orphaned,
|
|
3027
|
+
runsTotal: counts.total,
|
|
3028
|
+
runsSuccess: counts.success,
|
|
3029
|
+
runsError: counts.error,
|
|
2078
3030
|
nextRun: t.nextRunTime ? String(t.nextRunTime) : null,
|
|
2079
3031
|
model: def?.model ?? null,
|
|
2080
3032
|
priority: def?.priority ?? 5,
|
|
@@ -2089,6 +3041,10 @@ async function collectTasksView() {
|
|
|
2089
3041
|
dependsOn: Array.isArray(def?.dependsOn) ? def.dependsOn : [],
|
|
2090
3042
|
triggerType: def?.triggerType ?? "cron",
|
|
2091
3043
|
watchPath: def?.watchPath ?? null,
|
|
3044
|
+
timezone: def?.timezone ?? null,
|
|
3045
|
+
notBefore: def?.notBefore ?? null,
|
|
3046
|
+
notAfter: def?.notAfter ?? null,
|
|
3047
|
+
pausedUntil: def?.pausedUntil ?? null,
|
|
2092
3048
|
workingDirectory: workspace?.path ?? def?.workingDirectory ?? def?.workdir ?? null,
|
|
2093
3049
|
workspaceId: workspace?.id ?? def?.workspaceId ?? null,
|
|
2094
3050
|
workspaceName: workspace?.name ?? null,
|