opencode-windows-scheduler 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/CHANGELOG.md +60 -1
  2. package/README.md +18 -8
  3. package/README.ru.md +13 -3
  4. package/ROADMAP-STRATEGY.md +2 -2
  5. package/ROADMAP.md +51 -18
  6. package/dist/core/analytics.d.ts +10 -0
  7. package/dist/core/analytics.d.ts.map +1 -1
  8. package/dist/core/analytics.js +21 -0
  9. package/dist/core/dry-run.d.ts +18 -1
  10. package/dist/core/dry-run.d.ts.map +1 -1
  11. package/dist/core/dry-run.js +49 -3
  12. package/dist/core/matrix.d.ts.map +1 -1
  13. package/dist/core/matrix.js +10 -0
  14. package/dist/core/one-shot.d.ts +62 -0
  15. package/dist/core/one-shot.d.ts.map +1 -0
  16. package/dist/core/one-shot.js +126 -0
  17. package/dist/core/otel.d.ts +4 -0
  18. package/dist/core/otel.d.ts.map +1 -0
  19. package/dist/core/otel.js +98 -0
  20. package/dist/core/prometheus.d.ts +23 -0
  21. package/dist/core/prometheus.d.ts.map +1 -0
  22. package/dist/core/prometheus.js +146 -0
  23. package/dist/core/ps-wrapper.d.ts +36 -2
  24. package/dist/core/ps-wrapper.d.ts.map +1 -1
  25. package/dist/core/ps-wrapper.js +124 -4
  26. package/dist/core/record-history.d.ts.map +1 -1
  27. package/dist/core/record-history.js +9 -0
  28. package/dist/core/schedule-gate.d.ts +2 -0
  29. package/dist/core/schedule-gate.d.ts.map +1 -0
  30. package/dist/core/schedule-gate.js +182 -0
  31. package/dist/core/schedule-v2.d.ts +88 -0
  32. package/dist/core/schedule-v2.d.ts.map +1 -0
  33. package/dist/core/schedule-v2.js +496 -0
  34. package/dist/core/scheduler/linux.d.ts +12 -3
  35. package/dist/core/scheduler/linux.d.ts.map +1 -1
  36. package/dist/core/scheduler/linux.js +80 -3
  37. package/dist/core/scheduler/mac.d.ts.map +1 -1
  38. package/dist/core/scheduler/mac.js +17 -3
  39. package/dist/core/scheduler/posix.d.ts.map +1 -1
  40. package/dist/core/scheduler/posix.js +3 -0
  41. package/dist/core/scheduler/registry.d.ts +4 -0
  42. package/dist/core/scheduler/registry.d.ts.map +1 -1
  43. package/dist/core/scheduler/types.d.ts +20 -3
  44. package/dist/core/scheduler/types.d.ts.map +1 -1
  45. package/dist/core/scheduler/windows.d.ts.map +1 -1
  46. package/dist/core/scheduler/windows.js +23 -2
  47. package/dist/core/session.d.ts +34 -0
  48. package/dist/core/session.d.ts.map +1 -0
  49. package/dist/core/session.js +105 -0
  50. package/dist/core/structured-log.d.ts +84 -0
  51. package/dist/core/structured-log.d.ts.map +1 -0
  52. package/dist/core/structured-log.js +137 -0
  53. package/dist/core/wrappers/bash.d.ts +24 -0
  54. package/dist/core/wrappers/bash.d.ts.map +1 -1
  55. package/dist/core/wrappers/bash.js +70 -3
  56. package/dist/db/history-repo.d.ts +8 -0
  57. package/dist/db/history-repo.d.ts.map +1 -1
  58. package/dist/db/history-repo.js +76 -6
  59. package/dist/db/metrics-repo.d.ts +3 -0
  60. package/dist/db/metrics-repo.d.ts.map +1 -1
  61. package/dist/db/metrics-repo.js +16 -8
  62. package/dist/db/migrate.d.ts.map +1 -1
  63. package/dist/db/migrate.js +8 -1
  64. package/dist/db/schema.d.ts +1 -1
  65. package/dist/db/schema.d.ts.map +1 -1
  66. package/dist/db/schema.js +19 -0
  67. package/dist/gui-experimental.cjs +1 -0
  68. package/dist/history.d.ts +7 -0
  69. package/dist/history.d.ts.map +1 -1
  70. package/dist/history.js +13 -0
  71. package/dist/index.d.ts +137 -1
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +1323 -78
  74. package/dist/integrations.d.ts +64 -0
  75. package/dist/integrations.d.ts.map +1 -0
  76. package/dist/integrations.js +205 -0
  77. package/dist/notifications.d.ts +112 -6
  78. package/dist/notifications.d.ts.map +1 -1
  79. package/dist/notifications.js +396 -34
  80. package/dist/profiles.d.ts +60 -0
  81. package/dist/profiles.d.ts.map +1 -0
  82. package/dist/profiles.js +209 -0
  83. package/dist/rpc.d.ts +592 -4
  84. package/dist/rpc.d.ts.map +1 -1
  85. package/dist/rpc.js +233 -6
  86. package/dist/server.d.ts +2 -0
  87. package/dist/server.d.ts.map +1 -1
  88. package/dist/server.js +473 -58
  89. package/dist/settings.d.ts +95 -0
  90. package/dist/settings.d.ts.map +1 -1
  91. package/dist/settings.js +186 -8
  92. package/dist/shared/jobs-view.d.ts +43 -5
  93. package/dist/shared/jobs-view.d.ts.map +1 -1
  94. package/dist/shared/jobs-view.js +125 -7
  95. package/dist/task-transfer.d.ts +32 -3
  96. package/dist/task-transfer.d.ts.map +1 -1
  97. package/dist/task-transfer.js +101 -3
  98. package/dist/types.d.ts.map +1 -1
  99. package/dist/types.js +3 -11
  100. package/dist/workspaces.d.ts +43 -0
  101. package/dist/workspaces.d.ts.map +1 -1
  102. package/dist/workspaces.js +174 -8
  103. package/docs/ARCHITECTURE.md +32 -12
  104. package/docs/FEATURES.md +186 -10
  105. package/gui-experimental.cjs +4 -2
  106. package/package.json +15 -2
  107. package/scripts/demo-dashboard.mjs +12 -2
  108. package/src/core/analytics.ts +36 -0
  109. package/src/core/dry-run.ts +65 -4
  110. package/src/core/matrix.ts +10 -0
  111. package/src/core/one-shot.ts +173 -0
  112. package/src/core/otel.ts +128 -0
  113. package/src/core/prometheus.ts +215 -0
  114. package/src/core/ps-wrapper.ts +144 -4
  115. package/src/core/record-history.ts +13 -0
  116. package/src/core/schedule-gate.ts +213 -0
  117. package/src/core/schedule-v2.ts +533 -0
  118. package/src/core/scheduler/linux.ts +90 -3
  119. package/src/core/scheduler/mac.ts +35 -4
  120. package/src/core/scheduler/posix.ts +3 -0
  121. package/src/core/scheduler/registry.ts +4 -0
  122. package/src/core/scheduler/types.ts +20 -3
  123. package/src/core/scheduler/windows.ts +24 -2
  124. package/src/core/session.ts +115 -0
  125. package/src/core/structured-log.ts +205 -0
  126. package/src/core/wrappers/bash.ts +98 -2
  127. package/src/db/history-repo.ts +90 -7
  128. package/src/db/metrics-repo.ts +19 -7
  129. package/src/db/migrate.ts +7 -1
  130. package/src/db/schema.ts +25 -0
  131. package/src/gui.tsx +3832 -2868
  132. package/src/history.ts +17 -0
  133. package/src/index.ts +1670 -117
  134. package/src/integrations.ts +253 -0
  135. package/src/notifications.ts +516 -40
  136. package/src/profiles.ts +236 -0
  137. package/src/rpc.ts +244 -6
  138. package/src/server.ts +506 -58
  139. package/src/settings.ts +336 -9
  140. package/src/shared/jobs-view.ts +158 -8
  141. package/src/task-transfer.ts +151 -5
  142. package/src/tui.tsx +290 -14
  143. package/src/types.ts +3 -13
  144. package/src/workspaces.ts +214 -8
package/src/index.ts CHANGED
@@ -7,8 +7,18 @@ 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 { convertCronToSchTasks, previousRunTime } from "./core/cron-to-schtasks.js";
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 {
12
+ buildLaunchdOneShotCleanup,
13
+ normalizeOneShotRunAt,
14
+ } from "./core/one-shot.js";
15
+ import {
16
+ generateSessionId,
17
+ normalizeSessionMode,
18
+ preservedSessionRunCount,
19
+ type SessionMode,
20
+ } from "./core/session.js";
21
+ import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath, requestImmediateRun } from "./core/ps-wrapper.js";
12
22
  import { getSchedulerBackend } from "./core/scheduler/index.js";
13
23
  import { SCHEDULER_SKILL_ID, loadSchedulerSkill } from "./skill.js";
14
24
  import { getTaskLogs } from "./core/scheduler/logs.js";
@@ -27,13 +37,24 @@ import {
27
37
  syncMatrixFamily,
28
38
  } from "./core/matrix.js";
29
39
  import { SchedulerRpc } from "./rpc.js";
30
- import { loadHistory, loadMetrics } from "./history.js";
40
+ import { latestHistoryByTask, loadHistory, loadMetrics } from "./history.js";
31
41
  import { loadSettings, saveSettings } from "./settings.js";
32
- import type { HistorySettings, NotificationSettings } from "./settings.js";
42
+ import type {
43
+ HistorySettings,
44
+ IntegrationSettings,
45
+ NotificationSettings,
46
+ } from "./settings.js";
33
47
  import { runHistoryRetention, maybeRunHistoryRetention } from "./core/retention.js";
34
48
  import { buildAnalytics } from "./core/analytics.js";
35
- import { getHistory } from "./db/history-repo.js";
36
- import { sendTestNotification } from "./notifications.js";
49
+ import { getHistory, listRunningRecords } from "./db/history-repo.js";
50
+ import { getAllMetrics } from "./db/metrics-repo.js";
51
+ import {
52
+ findStuckMatrixClones,
53
+ maybeSendDigest,
54
+ notifyStuckMatrix,
55
+ sendDigestNow,
56
+ sendTestNotification,
57
+ } from "./notifications.js";
37
58
  import {
38
59
  loadTaskDefinitions,
39
60
  saveTaskDefinition,
@@ -52,10 +73,21 @@ import type {
52
73
  import { loadTemplates, saveTemplate, deleteTemplate } from "./templates.js";
53
74
  import type { TaskTemplate } from "./templates.js";
54
75
  import { startDashboardServer, closeDashboardServer, getDashboardPort } from "./server.js";
76
+ import {
77
+ DEFAULT_PROFILE,
78
+ createProfile,
79
+ deleteProfile,
80
+ getProfileDir,
81
+ getProfileName,
82
+ isProfilePinnedByEnv,
83
+ listProfiles,
84
+ sanitizeProfileName,
85
+ setActiveProfile,
86
+ } from "./profiles.js";
55
87
  import { closeDb, initDb } from "./db/index.js";
56
88
  import { migrateJsonToDb } from "./db/migrate.js";
57
89
  import { checkJsonBackups, recoverInterruptedRuns } from "./db/recovery.js";
58
- import { getTask, listMatrixClones } from "./db/tasks-repo.js";
90
+ import { getTask, listMatrixClones, saveTask } from "./db/tasks-repo.js";
59
91
  import {
60
92
  addWorkspace,
61
93
  deleteWorkspace,
@@ -64,6 +96,8 @@ import {
64
96
  updateWorkspace,
65
97
  validateWorkspacePath,
66
98
  readGitBranch,
99
+ writeWorkspaceEnvFile,
100
+ maskEnvForLog,
67
101
  } from "./workspaces.js";
68
102
 
69
103
  // Путь к вспомогательному node-скрипту записи истории/метрик (dist/core/record-history.js).
@@ -88,6 +122,24 @@ const recorderPath = (() => {
88
122
  return distPath;
89
123
  })();
90
124
 
125
+ /**
126
+ * Путь к гейту расписания (dist/core/schedule-gate.js). Обёртка запускает его
127
+ * перед opencode и выходит, если cron не сработал или запуск перенесён.
128
+ */
129
+ const gatePath = (() => {
130
+ const resolved = require.resolve("./core/schedule-gate.js");
131
+ if (!resolved.endsWith(".ts")) return resolved;
132
+ const distPath = resolved
133
+ .replace(/([\\/])src([\\/])/, "$1dist$2")
134
+ .replace(/\.ts$/, ".js");
135
+ if (existsSync(distPath)) return distPath;
136
+ console.warn(
137
+ "[windows-scheduler] Не найден собранный schedule-gate.js: " +
138
+ `${distPath}. Гейт расписания не будет проверяться. Выполните npm run build.`
139
+ );
140
+ return distPath;
141
+ })();
142
+
91
143
  /** Бэкенд планировщика текущей ОС (schtasks / crontab / launchd). */
92
144
  const scheduler = getSchedulerBackend();
93
145
 
@@ -148,9 +200,55 @@ export const scheduleTaskSchema = z.object({
148
200
  name: z.string().describe("Unique task name (the plugin prefix is applied automatically)."),
149
201
  schedule: z
150
202
  .string()
203
+ .optional()
204
+ .describe(
205
+ "Cron expression (5 fields: minute hour day-of-month month day-of-week). Required for triggerType=cron; ignored for file/mcp-event. 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."
206
+ ),
207
+ runAt: z
208
+ .string()
209
+ .optional()
210
+ .describe(
211
+ "Absolute one-shot start time in ISO-8601 (e.g. 2026-12-01T09:00:00Z). Requires triggerType=once; mutually exclusive with delaySeconds (runAt wins)."
212
+ ),
213
+ delaySeconds: z
214
+ .number()
215
+ .int()
216
+ .positive()
217
+ .optional()
218
+ .describe(
219
+ "One-shot delay in seconds from now. Requires triggerType=once. Convenient alternative to runAt."
220
+ ),
221
+ session: z
222
+ .enum(["new", "reuse", "last"])
223
+ .optional()
224
+ .describe(
225
+ "OpenCode session mode for the task: new (default, fresh session per run), reuse (keep a persistent session stored on the task — sessionId is auto-generated), last (continue the latest session via --continue)."
226
+ ),
227
+ sessionMaxRuns: z
228
+ .number()
229
+ .int()
230
+ .min(1)
231
+ .max(10000)
232
+ .optional()
233
+ .describe(
234
+ "Only for session=reuse: how many runs the reused session survives before it is deleted and a fresh one is created. Unset/0 — no limit."
235
+ ),
236
+ timezone: z
237
+ .string()
238
+ .optional()
239
+ .describe(
240
+ "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)."
241
+ ),
242
+ notBefore: z
243
+ .string()
244
+ .optional()
151
245
  .describe(
152
- "5-field cron expression (minute hour day-of-month month day-of-week). Supported patterns: * * * * *, */N * * * *, M H * * *, M H * * D."
246
+ "Launch window start in HH:MM (24h). Together with notAfter: a run outside the window is postponed to the next window opening, not skipped."
153
247
  ),
248
+ notAfter: z
249
+ .string()
250
+ .optional()
251
+ .describe("Launch window end in HH:MM (24h). May be earlier than notBefore (window crosses midnight)."),
154
252
  prompt: z
155
253
  .string()
156
254
  .describe("Prompt passed to the agent on every run."),
@@ -209,9 +307,11 @@ export const scheduleTaskSchema = z.object({
209
307
  .optional()
210
308
  .describe("Compensation/rollback task started after a failed run."),
211
309
  triggerType: z
212
- .enum(["cron", "file", "mcp-event"])
310
+ .enum(["cron", "file", "mcp-event", "once"])
213
311
  .optional()
214
- .describe("Trigger type: cron (default), file or mcp-event."),
312
+ .describe(
313
+ "Trigger type: cron (default), file, mcp-event or once (single run at runAt/delaySeconds)."
314
+ ),
215
315
  mcpEvent: z
216
316
  .object({
217
317
  server: z.string(),
@@ -222,6 +322,12 @@ export const scheduleTaskSchema = z.object({
222
322
  .describe(
223
323
  "MCP event trigger: server, event name and an optional filter (key=value or regex)."
224
324
  ),
325
+ watchPath: z
326
+ .string()
327
+ .optional()
328
+ .describe(
329
+ "File or directory to watch when triggerType is \"file\". Can be set here or later via update_task."
330
+ ),
225
331
  workingDirectory: z
226
332
  .string()
227
333
  .optional()
@@ -251,6 +357,40 @@ export const scheduleTaskSchema = z.object({
251
357
  .describe(
252
358
  "Matrix fan-out: the task becomes a template that is expanded into clones, one per workspace. The parent never runs itself. Cannot be combined with workspaceId."
253
359
  ),
360
+ }).superRefine((value, ctx) => {
361
+ const trigger = value.triggerType ?? "cron";
362
+ if (trigger === "cron" && !value.schedule?.trim()) {
363
+ ctx.addIssue({
364
+ code: z.ZodIssueCode.custom,
365
+ path: ["schedule"],
366
+ message: "Для triggerType=cron нужно cron-выражение schedule.",
367
+ });
368
+ }
369
+ if (
370
+ trigger === "once" &&
371
+ !value.runAt &&
372
+ value.delaySeconds === undefined
373
+ ) {
374
+ ctx.addIssue({
375
+ code: z.ZodIssueCode.custom,
376
+ path: ["runAt"],
377
+ message: "Для triggerType=once нужен runAt (ISO-8601) или delaySeconds.",
378
+ });
379
+ }
380
+ if (trigger === "once" && value.matrix) {
381
+ ctx.addIssue({
382
+ code: z.ZodIssueCode.custom,
383
+ path: ["matrix"],
384
+ message: "One-shot нельзя комбинировать с matrix: матрица запускается только вручную.",
385
+ });
386
+ }
387
+ if (trigger !== "once" && (value.runAt || value.delaySeconds !== undefined)) {
388
+ ctx.addIssue({
389
+ code: z.ZodIssueCode.custom,
390
+ path: ["runAt"],
391
+ message: "runAt/delaySeconds допустимы только при triggerType=once.",
392
+ });
393
+ }
254
394
  });
255
395
 
256
396
  const listTasksSchema = z.object({});
@@ -268,7 +408,48 @@ export const updateTaskSchema = z.object({
268
408
  schedule: z
269
409
  .string()
270
410
  .optional()
271
- .describe("New 5-field cron expression. Keeps the current value when omitted."),
411
+ .describe("New cron expression. Keeps the current value when omitted."),
412
+ runAt: z
413
+ .string()
414
+ .optional()
415
+ .describe(
416
+ "New one-shot time in ISO-8601. Requires triggerType=once. Empty string clears it."
417
+ ),
418
+ delaySeconds: z
419
+ .number()
420
+ .int()
421
+ .positive()
422
+ .optional()
423
+ .describe(
424
+ "New one-shot delay in seconds from now. Requires triggerType=once."
425
+ ),
426
+ session: z
427
+ .enum(["new", "reuse", "last"])
428
+ .optional()
429
+ .describe(
430
+ "OpenCode session mode for the task: new (fresh session per run), reuse (keep a persistent session stored on the task — sessionId is auto-generated), last (continue the latest session via --continue)."
431
+ ),
432
+ sessionMaxRuns: z
433
+ .number()
434
+ .int()
435
+ .min(1)
436
+ .max(10000)
437
+ .optional()
438
+ .describe(
439
+ "Only for session=reuse: how many runs the reused session survives before it is deleted and a fresh one is created. Unset/0 — no limit."
440
+ ),
441
+ timezone: z
442
+ .string()
443
+ .optional()
444
+ .describe("New IANA timezone. Empty string clears it (system timezone)."),
445
+ notBefore: z
446
+ .string()
447
+ .optional()
448
+ .describe("New launch window start HH:MM. Empty string clears the window."),
449
+ notAfter: z
450
+ .string()
451
+ .optional()
452
+ .describe("New launch window end HH:MM. Empty string clears the window."),
272
453
  prompt: z
273
454
  .string()
274
455
  .optional()
@@ -306,7 +487,7 @@ export const updateTaskSchema = z.object({
306
487
  .optional()
307
488
  .describe("New error-chain task. Empty string clears it."),
308
489
  triggerType: z
309
- .enum(["cron", "file", "mcp-event"])
490
+ .enum(["cron", "file", "mcp-event", "once"])
310
491
  .optional()
311
492
  .describe("New trigger type."),
312
493
  mcpEvent: z
@@ -343,10 +524,35 @@ export const updateTaskSchema = z.object({
343
524
  .describe(
344
525
  "New matrix configuration. Pass null to turn the matrix off (clones and aggregator are removed)."
345
526
  ),
527
+ }).superRefine((value, ctx) => {
528
+ if (
529
+ value.triggerType !== undefined &&
530
+ value.triggerType !== "once" &&
531
+ (value.runAt || value.delaySeconds !== undefined)
532
+ ) {
533
+ ctx.addIssue({
534
+ code: z.ZodIssueCode.custom,
535
+ path: ["runAt"],
536
+ message: "runAt/delaySeconds допустимы только при triggerType=once.",
537
+ });
538
+ }
539
+ if (value.triggerType === "once" && value.matrix) {
540
+ ctx.addIssue({
541
+ code: z.ZodIssueCode.custom,
542
+ path: ["matrix"],
543
+ message: "One-shot нельзя комбинировать с matrix.",
544
+ });
545
+ }
346
546
  });
347
547
 
348
548
  const pauseTaskSchema = z.object({
349
549
  name: z.string().describe("Task name to pause."),
550
+ until: z
551
+ .string()
552
+ .optional()
553
+ .describe(
554
+ "Optional ISO date/time to resume automatically (e.g. 2026-12-01T09:00:00Z). The plugin re-enables the task at that moment."
555
+ ),
350
556
  });
351
557
 
352
558
  const resumeTaskSchema = z.object({
@@ -393,18 +599,173 @@ const manageWorkspacesSchema = z.object({
393
599
  name: z.string().optional().describe("Workspace display name (add/update)."),
394
600
  path: z.string().optional().describe("Absolute workspace path (add/update)."),
395
601
  color: z.string().optional().describe("Marker color, e.g. #4f8cff (add/update)."),
602
+ env: z
603
+ .record(z.string(), z.string())
604
+ .nullable()
605
+ .optional()
606
+ .describe(
607
+ "Env-переменные workspace (ключ → значение). Переопределяют значения из envFile; секреты маскируются в логах (add/update)."
608
+ ),
609
+ envFile: z
610
+ .string()
611
+ .nullable()
612
+ .optional()
613
+ .describe("Путь к .env-файлу workspace (add/update, null — очистить)."),
396
614
  });
397
615
 
398
616
  export const matrixControlSchema = z.object({
399
617
  action: z
400
- .enum(["results", "cancel", "cleanup"])
618
+ .enum(["results", "cancel", "cleanup", "preview"])
401
619
  .describe(
402
- "results — aggregate status of a matrix; cancel — cancel pending clones; cleanup — delete orphaned clones and aggregators."
620
+ "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."
403
621
  ),
404
622
  name: z
405
623
  .string()
406
624
  .optional()
407
- .describe("Matrix parent name (required for results and cancel)."),
625
+ .describe("Matrix parent name (required for results and cancel; used as clone prefix for preview)."),
626
+ workspaceIds: z
627
+ .array(z.string())
628
+ .optional()
629
+ .describe("Preview only: workspace ids to fan out to (omit for every workspace)."),
630
+ strategy: z
631
+ .enum(["parallel", "sequential"])
632
+ .optional()
633
+ .describe("Preview only: clone execution strategy."),
634
+ failureMode: z
635
+ .enum(["continue", "stop"])
636
+ .optional()
637
+ .describe("Preview only: what to do when one clone fails."),
638
+ aggregation: z
639
+ .enum(["summary", "per-task"])
640
+ .optional()
641
+ .describe("Preview only: how clone results are aggregated."),
642
+ });
643
+
644
+ /** get_metrics — общая статистика запусков. */
645
+ export const getMetricsSchema = z.object({});
646
+
647
+ /** get_analytics — аналитика за период. */
648
+ export const getAnalyticsSchema = z.object({
649
+ days: z
650
+ .number()
651
+ .int()
652
+ .min(1)
653
+ .max(365)
654
+ .optional()
655
+ .describe("Analysis window in days (default 14)."),
656
+ topLimit: z
657
+ .number()
658
+ .int()
659
+ .min(1)
660
+ .max(50)
661
+ .optional()
662
+ .describe("How many top tasks to include (default 10)."),
663
+ });
664
+
665
+ /** manage_settings — глобальные настройки планировщика. */
666
+ export const manageSettingsSchema = z.object({
667
+ action: z
668
+ .enum(["get", "update"])
669
+ .describe("get — current settings; update — merge the provided fields and save."),
670
+ maxConcurrent: z
671
+ .number()
672
+ .int()
673
+ .min(1)
674
+ .max(16)
675
+ .optional()
676
+ .describe("How many task runs may execute at the same time."),
677
+ winterMode: z
678
+ .boolean()
679
+ .optional()
680
+ .describe("Winter mode: gentler scheduling of deferred runs."),
681
+ notifications: z
682
+ .any()
683
+ .optional()
684
+ .describe("Notification settings patch (enabled, onlyOnError, webhook, templates, filters, matrix, digest)."),
685
+ history: z
686
+ .object({
687
+ retentionDays: z.number().int().min(1).max(3650).optional(),
688
+ maxRecords: z.number().int().min(100).max(1000000).optional(),
689
+ })
690
+ .optional()
691
+ .describe("History retention policy."),
692
+ integrations: z
693
+ .any()
694
+ .optional()
695
+ .describe(
696
+ "Integration settings patch (hooks: enabled, token, secret, requireSignature, maxBodyBytes, timestampToleranceSeconds)."
697
+ ),
698
+ });
699
+
700
+ /** manage_templates — пользовательские шаблоны задач. */
701
+ export const manageTemplatesSchema = z.object({
702
+ action: z
703
+ .enum(["list", "save", "delete"])
704
+ .describe("list — all templates; save — create or update (id omitted = create); delete — remove by id."),
705
+ id: z.string().optional().describe("Template id for update/delete."),
706
+ name: z.string().optional().describe("Template name."),
707
+ prompt: z.string().optional().describe("Prompt text stored in the template."),
708
+ schedule: z.string().optional().describe("Cron expression."),
709
+ timeoutSeconds: z.number().int().positive().optional(),
710
+ model: z.string().optional(),
711
+ priority: z.number().int().min(0).max(10).optional(),
712
+ retryCount: z.number().int().min(0).optional(),
713
+ retryDelay: z.number().int().min(0).optional(),
714
+ qualityGate: z.string().optional(),
715
+ beforeScript: z.string().optional(),
716
+ afterScript: z.string().optional(),
717
+ nextTaskOnSuccess: z.string().optional(),
718
+ nextTaskOnError: z.string().optional(),
719
+ dependsOn: z.array(z.string()).optional(),
720
+ triggerType: z.enum(["cron", "file", "mcp-event"]).optional(),
721
+ mcpEvent: z
722
+ .object({
723
+ server: z.string(),
724
+ event: z.string(),
725
+ filter: z.string().optional(),
726
+ })
727
+ .optional(),
728
+ watchPath: z.string().optional(),
729
+ workingDirectory: z.string().optional(),
730
+ allowedTools: z.array(z.string()).optional(),
731
+ deniedTools: z.array(z.string()).optional(),
732
+ });
733
+
734
+ /** manage_profiles — изолированные профили планировщика. */
735
+ export const manageProfilesSchema = z.object({
736
+ action: z
737
+ .enum(["list", "create", "switch", "delete"])
738
+ .describe("list — profiles; create — new profile; switch — make active (restart required); delete — remove profile data."),
739
+ name: z.string().optional().describe("Profile name (required for create/switch/delete)."),
740
+ port: z.number().int().min(1).max(65535).optional().describe("Dashboard port for a new profile."),
741
+ });
742
+
743
+ /** transfer_tasks — экспорт и импорт задач. */
744
+ export const transferTasksSchema = z.object({
745
+ action: z.enum(["export", "import"]).describe("export — JSON snapshot; import — recreate tasks from a snapshot."),
746
+ data: z.string().optional().describe("JSON produced by export (required for import)."),
747
+ });
748
+
749
+ /** send_notification — проверка уведомлений и дайджест. */
750
+ export const sendNotificationSchema = z.object({
751
+ action: z
752
+ .enum(["test", "digest"])
753
+ .describe("test — send a test message through the configured channel; digest — send the digest now."),
754
+ });
755
+
756
+ /** get_dashboard_info — сведения о панели управления. */
757
+ export const getDashboardInfoSchema = z.object({});
758
+
759
+ /** cleanup_history — удаление старой истории. */
760
+ export const cleanupHistorySchema = z.object({
761
+ retentionDays: z.number().int().min(1).max(3650).optional().describe("Override the retention window."),
762
+ maxRecords: z.number().int().min(100).max(1000000).optional().describe("Override the record cap."),
763
+ });
764
+
765
+ /** emit_event — запуск задач по MCP-событию. */
766
+ export const emitEventSchema = z.object({
767
+ eventName: z.string().min(1).describe("Event name, for example 'deploy.finished'."),
768
+ payload: z.any().optional().describe("Event payload passed to trigger filters."),
408
769
  });
409
770
 
410
771
  type ScheduleArgs = z.infer<typeof scheduleTaskSchema>;
@@ -419,6 +780,16 @@ type TaskLogsArgs = z.infer<typeof getTaskLogsSchema>;
419
780
  type DryRunArgs = z.infer<typeof dryRunSchema>;
420
781
  type WorkspacesArgs = z.infer<typeof manageWorkspacesSchema>;
421
782
  type MatrixControlArgs = z.infer<typeof matrixControlSchema>;
783
+ type MetricsArgs = z.infer<typeof getMetricsSchema>;
784
+ type AnalyticsArgs = z.infer<typeof getAnalyticsSchema>;
785
+ type SettingsArgs = z.infer<typeof manageSettingsSchema>;
786
+ type TemplatesArgs = z.infer<typeof manageTemplatesSchema>;
787
+ type ProfilesArgs = z.infer<typeof manageProfilesSchema>;
788
+ type TransferArgs = z.infer<typeof transferTasksSchema>;
789
+ type NotificationArgs = z.infer<typeof sendNotificationSchema>;
790
+ type DashboardInfoArgs = z.infer<typeof getDashboardInfoSchema>;
791
+ type CleanupHistoryArgs = z.infer<typeof cleanupHistorySchema>;
792
+ type EmitEventArgs = z.infer<typeof emitEventSchema>;
422
793
 
423
794
  /**
424
795
  * Директория проекта, в которой запущен OpenCode. Используется как рабочая
@@ -453,6 +824,8 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
453
824
  const {
454
825
  name,
455
826
  schedule,
827
+ runAt,
828
+ delaySeconds,
456
829
  prompt,
457
830
  timeoutSeconds,
458
831
  model,
@@ -467,17 +840,41 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
467
840
  nextTaskOnError,
468
841
  triggerType,
469
842
  mcpEvent,
843
+ watchPath,
470
844
  workingDirectory,
471
845
  workspaceId,
472
846
  allowedTools,
473
847
  deniedTools,
474
848
  matrix,
849
+ timezone,
850
+ notBefore,
851
+ notAfter,
852
+ session,
853
+ sessionMaxRuns,
475
854
  } = args;
476
855
 
856
+ let effectiveRunAt: string | undefined;
857
+ if ((triggerType ?? "cron") === "once") {
858
+ const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
859
+ if (!normalized.ok) {
860
+ return {
861
+ content: JSON.stringify({ success: false, error: normalized.error }),
862
+ };
863
+ }
864
+ effectiveRunAt = normalized.runAt;
865
+ }
866
+
867
+ // Спринт 24: режим сессии. По умолчанию "new" (старое поведение).
868
+ // sessionId пользователя никогда не принимаем — он создаётся автоматически.
869
+ const effectiveSession: "new" | "reuse" | "last" =
870
+ normalizeSessionMode(session) ?? "new";
871
+ const effectiveSessionId =
872
+ effectiveSession === "reuse" ? generateSessionId() : undefined;
873
+
477
874
  try {
478
875
  await schedulerCreateTask(
479
876
  name,
480
- schedule,
877
+ schedule ?? "",
481
878
  prompt,
482
879
  timeoutSeconds,
483
880
  workingDirectory,
@@ -487,7 +884,7 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
487
884
  nextTaskOnSuccess,
488
885
  nextTaskOnError,
489
886
  triggerType,
490
- undefined,
887
+ watchPath,
491
888
  dependsOn,
492
889
  model,
493
890
  priority,
@@ -497,7 +894,17 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
497
894
  workspaceId,
498
895
  allowedTools,
499
896
  deniedTools,
500
- matrix
897
+ matrix,
898
+ undefined,
899
+ "create",
900
+ timezone,
901
+ notBefore,
902
+ notAfter,
903
+ undefined,
904
+ effectiveRunAt,
905
+ effectiveSession,
906
+ effectiveSessionId,
907
+ sessionMaxRuns
501
908
  );
502
909
  } catch (err: any) {
503
910
  return {
@@ -508,6 +915,10 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
508
915
  };
509
916
  }
510
917
 
918
+ // Новый файловый триггер должен начать работать сразу, без перезапуска
919
+ // OpenCode: пересобираем набор watcher-ов после создания задачи.
920
+ await refreshFileTriggers();
921
+
511
922
  const workspace = workspaceId ? getWorkspace(workspaceId) : undefined;
512
923
  const effectiveWorkdir =
513
924
  workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
@@ -530,6 +941,13 @@ const scheduleTaskExecute = wrapExecute<ScheduleArgs>(async (args) => {
530
941
  nextTaskOnSuccess: nextTaskOnSuccess?.trim() || null,
531
942
  nextTaskOnError: nextTaskOnError?.trim() || null,
532
943
  triggerType: triggerType ?? "cron",
944
+ runAt: effectiveRunAt ?? null,
945
+ session: effectiveSession,
946
+ sessionId: effectiveSessionId ?? null,
947
+ sessionMaxRuns: sessionMaxRuns ?? null,
948
+ timezone: timezone?.trim() || null,
949
+ notBefore: notBefore?.trim() || null,
950
+ notAfter: notAfter?.trim() || null,
533
951
  mcpEvent: mcpEvent ?? null,
534
952
  workingDirectory: effectiveWorkdir,
535
953
  workspaceId: workspace?.id ?? null,
@@ -625,7 +1043,12 @@ async function cancelMatrixRun(
625
1043
  clone.allowedTools,
626
1044
  clone.deniedTools,
627
1045
  undefined,
628
- definition.name
1046
+ definition.name,
1047
+ "create",
1048
+ clone.timezone,
1049
+ clone.notBefore,
1050
+ clone.notAfter,
1051
+ clone.pausedUntil
629
1052
  );
630
1053
  } catch (err: any) {
631
1054
  warnings.push(
@@ -695,7 +1118,7 @@ async function cleanupOrphanedMatrixTasks(): Promise<string[]> {
695
1118
  */
696
1119
  async function deleteTaskWithFamily(
697
1120
  name: string
698
- ): Promise<{ removed: string[] }> {
1121
+ ): Promise<{ removed: string[]; existed: boolean }> {
699
1122
  const trimmed = name.trim();
700
1123
  const guard = getMatrixDeletionGuard(trimmed);
701
1124
  if (guard) throw new Error(guard);
@@ -703,6 +1126,21 @@ async function deleteTaskWithFamily(
703
1126
  const plan = planMatrixFamilyDelete(trimmed);
704
1127
  const removed: string[] = [];
705
1128
 
1129
+ // Отличаем реальное удаление от «удаления пустоты»: раньше инструмент
1130
+ // отвечал success даже на имя, которого никогда не существовало.
1131
+ let existed = Boolean(getTask(trimmed));
1132
+ if (!existed) {
1133
+ try {
1134
+ const osTasks = await scheduler.listTasks();
1135
+ existed = osTasks.some(
1136
+ (task) => task.taskName.toLowerCase() === trimmed.toLowerCase()
1137
+ );
1138
+ } catch {
1139
+ // ОС-планировщик недоступен — довольствуемся данными БД.
1140
+ }
1141
+ }
1142
+ if (plan && plan.children.length > 0) existed = true;
1143
+
706
1144
  if (plan) {
707
1145
  for (const child of plan.children) {
708
1146
  try {
@@ -726,7 +1164,7 @@ async function deleteTaskWithFamily(
726
1164
  // Определения могло уже не быть — задача всё равно удалена из ОС.
727
1165
  }
728
1166
 
729
- return { removed };
1167
+ return { removed, existed };
730
1168
  }
731
1169
 
732
1170
  /** delete_task — удаление задачи по имени (/f) */
@@ -734,7 +1172,17 @@ const deleteTaskExecute = wrapExecute<DeleteArgs>(async (args) => {
734
1172
  const { name } = args;
735
1173
 
736
1174
  try {
737
- const { removed } = await deleteTaskWithFamily(name);
1175
+ const { removed, existed } = await deleteTaskWithFamily(name);
1176
+ // Убираем watcher удалённой задачи, не дожидаясь перезапуска плагина.
1177
+ await refreshFileTriggers();
1178
+ if (!existed && removed.length === 0) {
1179
+ return {
1180
+ content: JSON.stringify({
1181
+ success: false,
1182
+ error: `Задача "${name}" не найдена — удалять нечего.`,
1183
+ }),
1184
+ };
1185
+ }
738
1186
  return {
739
1187
  content: JSON.stringify({
740
1188
  success: true,
@@ -760,7 +1208,7 @@ const runTaskNowExecute = wrapExecute<RunNowArgs>(async (args) => {
760
1208
 
761
1209
  let alreadyRunning = false;
762
1210
  try {
763
- const result = await scheduler.runTask(name);
1211
+ const result = await runTaskEntry(name);
764
1212
  alreadyRunning = result.alreadyRunning;
765
1213
  } catch (err: any) {
766
1214
  return {
@@ -842,6 +1290,9 @@ async function updateTaskFromInput(
842
1290
  const schedule = clearableString(input.schedule ?? input.newSchedule, previous.schedule);
843
1291
  const prompt = clearableString(input.prompt ?? input.newPrompt, previous.prompt);
844
1292
  const triggerType = input.triggerType ?? previous.triggerType ?? "cron";
1293
+ const timezone = clearableString(input.timezone, previous.timezone);
1294
+ const notBefore = clearableString(input.notBefore, previous.notBefore);
1295
+ const notAfter = clearableString(input.notAfter, previous.notAfter);
845
1296
 
846
1297
  if (triggerType === "cron" && !schedule) {
847
1298
  return {
@@ -856,16 +1307,81 @@ async function updateTaskFromInput(
856
1307
  };
857
1308
  }
858
1309
 
1310
+ // One-shot: без нового runAt/delaySeconds сохраняем прежнее время.
1311
+ // При смене триггера на once время обязательно, иначе задача не запустится.
1312
+ let runAt: string | undefined;
1313
+ if (triggerType === "once") {
1314
+ const candidateRunAt =
1315
+ input.runAt !== undefined
1316
+ ? input.runAt
1317
+ : input.delaySeconds !== undefined
1318
+ ? undefined
1319
+ : previous.runAt;
1320
+ const normalized = normalizeOneShotRunAt({
1321
+ runAt: candidateRunAt,
1322
+ delaySeconds: input.delaySeconds,
1323
+ });
1324
+ if (!normalized.ok) {
1325
+ return {
1326
+ success: false,
1327
+ message: `Задача "${name}": ${normalized.error}`,
1328
+ };
1329
+ }
1330
+ runAt = normalized.runAt;
1331
+ }
1332
+
1333
+ // Спринт 24: режим сессии. Без новых session/sessionMaxRuns сохраняем прежние.
1334
+ // sessionId пользователя не принимаем — генерируем сами при переходе на reuse.
1335
+ let session: "new" | "reuse" | "last" = "new";
1336
+ if (input.session !== undefined) {
1337
+ const normalizedSession = normalizeSessionMode(input.session);
1338
+ if (!normalizedSession) {
1339
+ return {
1340
+ success: false,
1341
+ message: `Задача "${name}": неизвестный режим сессии "${String(input.session)}".`,
1342
+ };
1343
+ }
1344
+ session = normalizedSession;
1345
+ } else if (previous.session) {
1346
+ session = previous.session;
1347
+ }
1348
+ const sessionMaxRuns =
1349
+ input.sessionMaxRuns !== undefined ? input.sessionMaxRuns : previous.sessionMaxRuns;
1350
+ if (
1351
+ sessionMaxRuns !== undefined &&
1352
+ (!Number.isInteger(sessionMaxRuns) || sessionMaxRuns < 1)
1353
+ ) {
1354
+ return {
1355
+ success: false,
1356
+ message: `Задача "${name}": sessionMaxRuns должен быть целым числом ≥ 1.`,
1357
+ };
1358
+ }
1359
+ let sessionId = previous.sessionId;
1360
+ if (session === "reuse" && !sessionId) {
1361
+ sessionId = generateSessionId();
1362
+ }
1363
+ if (session !== "reuse") {
1364
+ sessionId = undefined;
1365
+ }
1366
+
859
1367
  const matrixWas = previous.matrix;
860
1368
  const matrixNext =
861
1369
  input.matrix === undefined ? matrixWas : input.matrix ?? undefined;
1370
+ if (triggerType === "once" && matrixNext) {
1371
+ return {
1372
+ success: false,
1373
+ message:
1374
+ `Задача "${name}": one-shot нельзя комбинировать с matrix. ` +
1375
+ `Запустите матрицу вручную или используйте cron/file-триггер.`,
1376
+ };
1377
+ }
862
1378
 
863
1379
  try {
864
1380
  // Обновление = пересоздание в планировщике с сохранением старых значений.
865
1381
  await scheduler.deleteTask(name);
866
1382
  await schedulerCreateTask(
867
1383
  name,
868
- schedule ?? "* * * * *",
1384
+ schedule ?? "",
869
1385
  prompt,
870
1386
  input.timeoutSeconds ?? previous.timeoutSeconds,
871
1387
  clearableString(input.workingDirectory, previous.workingDirectory),
@@ -889,7 +1405,15 @@ async function updateTaskFromInput(
889
1405
  undefined,
890
1406
  // Если задача была матрицей — синхронизируем клонов, а не
891
1407
  // пересоздаём их с нуля (Спринт 17).
892
- matrixWas && matrixNext ? "sync" : "create"
1408
+ matrixWas && matrixNext ? "sync" : "create",
1409
+ timezone,
1410
+ notBefore,
1411
+ notAfter,
1412
+ previous.pausedUntil,
1413
+ runAt,
1414
+ session,
1415
+ sessionId,
1416
+ sessionMaxRuns
893
1417
  );
894
1418
 
895
1419
  // Матрица отключена при обновлении — убираем клонов и агрегатор.
@@ -897,6 +1421,10 @@ async function updateTaskFromInput(
897
1421
  await removeMatrixChildrenFromScheduler(name);
898
1422
  }
899
1423
 
1424
+ // Пересоздание могло изменить triggerType/watchPath — сразу
1425
+ // пересобираем набор файловых watcher-ов.
1426
+ await refreshFileTriggers();
1427
+
900
1428
  return { success: true, message: `Задача "${name}" обновлена.` };
901
1429
  } catch (err: any) {
902
1430
  return {
@@ -918,7 +1446,8 @@ const updateTaskExecute = wrapExecute<UpdateArgs>(async (args) => {
918
1446
  */
919
1447
  async function pauseOrResumeTask(
920
1448
  name: string,
921
- paused: boolean
1449
+ paused: boolean,
1450
+ until?: string
922
1451
  ): Promise<{ success: boolean; message: string; affected: string[]; warnings: string[] }> {
923
1452
  const trimmed = name.trim();
924
1453
  const definition = getTask(trimmed);
@@ -931,6 +1460,29 @@ async function pauseOrResumeTask(
931
1460
  };
932
1461
  }
933
1462
 
1463
+ // Пауза до даты (Спринт 19): проверяем ISO-момент до каких-либо изменений.
1464
+ let pausedUntil: string | undefined;
1465
+ if (paused && until?.trim()) {
1466
+ const parsed = Date.parse(until.trim());
1467
+ if (Number.isNaN(parsed)) {
1468
+ return {
1469
+ success: false,
1470
+ message: `Задача "${trimmed}": некорректная дата паузы "${until}". Нужен ISO-момент, например 2026-12-01T09:00:00Z.`,
1471
+ affected: [],
1472
+ warnings: [],
1473
+ };
1474
+ }
1475
+ if (parsed <= Date.now()) {
1476
+ return {
1477
+ success: false,
1478
+ message: `Задача "${trimmed}": дата паузы уже прошла.`,
1479
+ affected: [],
1480
+ warnings: [],
1481
+ };
1482
+ }
1483
+ pausedUntil = new Date(parsed).toISOString();
1484
+ }
1485
+
934
1486
  const targets = definition.matrix
935
1487
  ? listMatrixClones(trimmed).map((clone) => clone.name)
936
1488
  : [trimmed];
@@ -960,11 +1512,35 @@ async function pauseOrResumeTask(
960
1512
  }
961
1513
  }
962
1514
 
1515
+ // Фиксируем (или снимаем) автопродолжение в определении задачи. У матрицы
1516
+ // родитель хранит pausedUntil за всех клонов — их включает авто-resume.
1517
+ const definitionUpdates = paused
1518
+ ? pausedUntil
1519
+ ? { pausedUntil }
1520
+ : undefined
1521
+ : definition.pausedUntil
1522
+ ? { pausedUntil: undefined }
1523
+ : undefined;
1524
+ if (definitionUpdates && affected.length > 0) {
1525
+ try {
1526
+ saveTask({ ...definition, ...definitionUpdates });
1527
+ } catch (err: any) {
1528
+ warnings.push(
1529
+ `не удалось сохранить автопродолжение: ${
1530
+ err instanceof Error ? err.message : String(err)
1531
+ }`
1532
+ );
1533
+ }
1534
+ }
1535
+
1536
+ const untilText = pausedUntil
1537
+ ? ` до ${new Date(pausedUntil).toLocaleString()}`
1538
+ : "";
963
1539
  const verb = paused ? "поставлена на паузу" : "возобновлена";
964
1540
  const message = definition.matrix
965
- ? `Матрица "${trimmed}" ${verb}: ${affected.length} из ${targets.length} клонов.` +
1541
+ ? `Матрица "${trimmed}" ${verb}${untilText}: ${affected.length} из ${targets.length} клонов.` +
966
1542
  (warnings.length > 0 ? ` Ошибки: ${warnings.join("; ")}.` : "")
967
- : `Задача "${trimmed}" ${verb}.` +
1543
+ : `Задача "${trimmed}" ${verb}${untilText}.` +
968
1544
  (warnings.length > 0 ? ` Ошибка: ${warnings.join("; ")}.` : "");
969
1545
 
970
1546
  return {
@@ -976,7 +1552,7 @@ async function pauseOrResumeTask(
976
1552
  }
977
1553
 
978
1554
  const pauseTaskExecute = wrapExecute<PauseArgs>(async (args) => {
979
- const result = await pauseOrResumeTask(args.name, true);
1555
+ const result = await pauseOrResumeTask(args.name, true, args.until);
980
1556
  return { content: JSON.stringify(result) };
981
1557
  });
982
1558
 
@@ -985,6 +1561,88 @@ const resumeTaskExecute = wrapExecute<ResumeArgs>(async (args) => {
985
1561
  return { content: JSON.stringify(result) };
986
1562
  });
987
1563
 
1564
+ /** Периодичность проверки автопродолжения задач (Спринт 19). */
1565
+ const PAUSED_UNTIL_CHECK_MS = 5 * 60 * 1000;
1566
+ /** Период проверки дайджеста и зависших матриц (Спринт 20). */
1567
+ const NOTIFICATION_CHECK_MS = 60 * 1000;
1568
+
1569
+ /**
1570
+ * Спринт 19: автопродолжение задач, поставленных на паузу до даты.
1571
+ * Включает задачу в планировщике ОС и снимает `pausedUntil` из определения.
1572
+ * Клоны матрицы не обрабатываются отдельно — за них отвечает родитель.
1573
+ */
1574
+ async function resumeExpiredPauses(): Promise<void> {
1575
+ const now = Date.now();
1576
+ const definitions = await loadTaskDefinitions();
1577
+ for (const definition of definitions) {
1578
+ if (!definition.pausedUntil) continue;
1579
+ if (definition.matrixParentId) continue;
1580
+ const untilMs = Date.parse(definition.pausedUntil);
1581
+ if (!Number.isFinite(untilMs) || untilMs > now) continue;
1582
+
1583
+ try {
1584
+ const targets = definition.matrix
1585
+ ? listMatrixClones(definition.name).map((clone) => clone.name)
1586
+ : [definition.name];
1587
+ for (const target of targets) {
1588
+ await scheduler.resumeTask(target);
1589
+ }
1590
+ await saveTaskDefinition({ ...definition, pausedUntil: undefined });
1591
+ console.log(
1592
+ `[windows-scheduler] Автопродолжение: задача "${definition.name}" включена (пауза истекла).`
1593
+ );
1594
+ } catch (err: any) {
1595
+ console.error(
1596
+ `[windows-scheduler] Не удалось автопродолжить задачу "${definition.name}": ${
1597
+ err instanceof Error ? err.message : String(err)
1598
+ }`
1599
+ );
1600
+ }
1601
+ }
1602
+ }
1603
+
1604
+ /** Уже отправленные уведомления о зависших клонах (id записи истории). */
1605
+ const notifiedStuckRecords = new Set<number>();
1606
+
1607
+ /**
1608
+ * Детектор зависших матриц (Спринт 20): клоны, которые выполняются дольше
1609
+ * `notifications.matrix.stuckAfterMinutes`. Каждый запуск уведомляется один раз.
1610
+ */
1611
+ async function checkStuckMatrices(): Promise<void> {
1612
+ const settings = await loadSettings();
1613
+ const config = settings.notifications;
1614
+ if (!config?.enabled) return;
1615
+ const matrix = config.matrix;
1616
+ if (!matrix?.enabled) return;
1617
+ const threshold = matrix.stuckAfterMinutes;
1618
+ if (!Number.isFinite(threshold) || threshold <= 0) return;
1619
+
1620
+ const running = listRunningRecords();
1621
+ if (running.length === 0) {
1622
+ notifiedStuckRecords.clear();
1623
+ return;
1624
+ }
1625
+ // Снимаем отметки с завершившихся записей, чтобы Set не рос бесконечно.
1626
+ const runningIds = new Set(running.map((record) => record.id));
1627
+ for (const id of notifiedStuckRecords) {
1628
+ if (!runningIds.has(id)) notifiedStuckRecords.delete(id);
1629
+ }
1630
+
1631
+ const parentByClone = new Map<string, string>();
1632
+ for (const definition of await loadTaskDefinitions()) {
1633
+ if (definition.matrixParentId) {
1634
+ parentByClone.set(definition.name.toLowerCase(), definition.matrixParentId);
1635
+ }
1636
+ }
1637
+
1638
+ const stuck = findStuckMatrixClones(running, parentByClone, new Date(), threshold);
1639
+ for (const item of stuck) {
1640
+ if (notifiedStuckRecords.has(item.id)) continue;
1641
+ notifiedStuckRecords.add(item.id);
1642
+ await notifyStuckMatrix(item);
1643
+ }
1644
+ }
1645
+
988
1646
  /** get_history — история запусков с фильтрами по задаче и статусу. */
989
1647
  const getHistoryExecute = wrapExecute<HistoryArgs>(async (args) => {
990
1648
  const limit = Math.max(1, Math.min(args.limit ?? 20, 200));
@@ -1057,6 +1715,22 @@ const dryRunExecute = wrapExecute<DryRunArgs>(async (args) => {
1057
1715
  };
1058
1716
  });
1059
1717
 
1718
+ /**
1719
+ * Перегенерирует env-файлы всех задач, привязанных к workspace (Спринт 21).
1720
+ * Обёртки читают env-файл при запуске, поэтому перезапуск задач не нужен.
1721
+ */
1722
+ async function refreshWorkspaceEnvFiles(workspaceId: string): Promise<number> {
1723
+ const workspace = getWorkspace(workspaceId);
1724
+ if (!workspace) return 0;
1725
+ let refreshed = 0;
1726
+ for (const task of await loadTaskDefinitions()) {
1727
+ if (task.workspaceId !== workspaceId) continue;
1728
+ writeWorkspaceEnvFile(workspace, PLUGIN_DIR, sanitizeName(task.name));
1729
+ refreshed += 1;
1730
+ }
1731
+ return refreshed;
1732
+ }
1733
+
1060
1734
  /** manage_workspaces — CRUD multi-repo workspace-ов. */
1061
1735
  const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
1062
1736
  try {
@@ -1064,6 +1738,7 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
1064
1738
  case "list": {
1065
1739
  const workspaces = listWorkspaces().map((workspace) => ({
1066
1740
  ...workspace,
1741
+ env: maskEnvForLog(workspace.env),
1067
1742
  gitBranch: readGitBranch(workspace.path) ?? null,
1068
1743
  }));
1069
1744
  return {
@@ -1087,12 +1762,15 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
1087
1762
  name: args.name,
1088
1763
  path: args.path,
1089
1764
  color: args.color,
1765
+ env: args.env,
1766
+ envFile: args.envFile,
1090
1767
  });
1091
1768
  return {
1092
1769
  content: JSON.stringify({
1093
1770
  success: true,
1094
1771
  workspace: {
1095
1772
  ...workspace,
1773
+ env: maskEnvForLog(workspace.env),
1096
1774
  gitBranch: readGitBranch(workspace.path) ?? null,
1097
1775
  },
1098
1776
  }),
@@ -1111,6 +1789,8 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
1111
1789
  name: args.name,
1112
1790
  path: args.path,
1113
1791
  color: args.color,
1792
+ env: args.env,
1793
+ envFile: args.envFile,
1114
1794
  });
1115
1795
  if (!workspace) {
1116
1796
  return {
@@ -1120,11 +1800,16 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
1120
1800
  }),
1121
1801
  };
1122
1802
  }
1803
+ // Env-файлы уже созданных задач перегенерируются сразу: обёртки читают
1804
+ // файл при запуске, поэтому ждать обновления задачи не нужно.
1805
+ const refreshedTasks = await refreshWorkspaceEnvFiles(workspace.id);
1123
1806
  return {
1124
1807
  content: JSON.stringify({
1125
1808
  success: true,
1809
+ refreshedTasks,
1126
1810
  workspace: {
1127
1811
  ...workspace,
1812
+ env: maskEnvForLog(workspace.env),
1128
1813
  gitBranch: readGitBranch(workspace.path) ?? null,
1129
1814
  },
1130
1815
  }),
@@ -1158,66 +1843,422 @@ const manageWorkspacesExecute = wrapExecute<WorkspacesArgs>(async (args) => {
1158
1843
  }),
1159
1844
  };
1160
1845
  }
1161
- });
1846
+ });
1847
+
1848
+ /** matrix_control — результаты, отмена, очистка и предпросмотр матриц. */
1849
+ const matrixControlExecute = wrapExecute<MatrixControlArgs>(async (args) => {
1850
+ if (args.action === "preview") {
1851
+ const clones = expandMatrixTask({
1852
+ name: (args.name ?? "").trim() || "task",
1853
+ schedule: "* * * * *",
1854
+ prompt: "preview",
1855
+ matrix: {
1856
+ workspaceIds: Array.isArray(args.workspaceIds) ? args.workspaceIds : [],
1857
+ strategy: args.strategy,
1858
+ failureMode: args.failureMode,
1859
+ aggregation: args.aggregation,
1860
+ },
1861
+ } as any);
1862
+ return {
1863
+ content: JSON.stringify({
1864
+ success: true,
1865
+ clones: clones.map((clone) => ({
1866
+ name: clone.name,
1867
+ workspaceId: clone.workspaceId ?? "",
1868
+ workspaceName: clone.workspaceId ? getWorkspace(clone.workspaceId)?.name ?? null : null,
1869
+ })),
1870
+ }),
1871
+ };
1872
+ }
1873
+
1874
+ if (args.action === "cleanup") {
1875
+ const removed = await cleanupOrphanedMatrixTasks();
1876
+ return {
1877
+ content: JSON.stringify({
1878
+ success: true,
1879
+ message:
1880
+ removed.length > 0
1881
+ ? `Удалено осиротевших задач: ${removed.length}.`
1882
+ : "Осиротевших задач не найдено.",
1883
+ removed,
1884
+ }),
1885
+ };
1886
+ }
1887
+
1888
+ const name = args.name?.trim();
1889
+ if (!name) {
1890
+ return {
1891
+ content: JSON.stringify({
1892
+ success: false,
1893
+ error: `Для action=${args.action} нужен name матрицы.`,
1894
+ }),
1895
+ };
1896
+ }
1897
+
1898
+ if (args.action === "cancel") {
1899
+ try {
1900
+ const result = await cancelMatrixRun(name);
1901
+ return {
1902
+ content: JSON.stringify({
1903
+ success: true,
1904
+ message: result.message,
1905
+ cancelled: result.cancelled,
1906
+ }),
1907
+ };
1908
+ } catch (err: any) {
1909
+ return {
1910
+ content: JSON.stringify({
1911
+ success: false,
1912
+ error: err instanceof Error ? err.message : String(err),
1913
+ }),
1914
+ };
1915
+ }
1916
+ }
1917
+
1918
+ try {
1919
+ const report = aggregateMatrixResults(name);
1920
+ return { content: JSON.stringify({ success: true, report }) };
1921
+ } catch (err: any) {
1922
+ return {
1923
+ content: JSON.stringify({
1924
+ success: false,
1925
+ error: err instanceof Error ? err.message : String(err),
1926
+ }),
1927
+ };
1928
+ }
1929
+ });
1930
+
1931
+ /** get_metrics — суммарная статистика запусков. */
1932
+ const getMetricsExecute = wrapExecute<MetricsArgs>(async () => {
1933
+ const metrics = await loadMetrics();
1934
+ return { content: JSON.stringify({ success: true, metrics }) };
1935
+ });
1936
+
1937
+ /** get_analytics — аналитика запусков и стоимости за период. */
1938
+ const getAnalyticsExecute = wrapExecute<AnalyticsArgs>(async (args) => {
1939
+ const windowDays = Math.min(365, Math.max(1, Math.floor(Number(args.days) || 14)));
1940
+ const records = getHistory(null, 20000);
1941
+ const definitions = await loadTaskDefinitions();
1942
+ const report = buildAnalytics(records, {
1943
+ days: windowDays,
1944
+ topLimit: Math.max(1, Math.floor(Number(args.topLimit) || 10)),
1945
+ tasks: definitions.map((definition) => ({
1946
+ name: definition.name,
1947
+ matrixParentId: definition.matrixParentId,
1948
+ })),
1949
+ });
1950
+ return { content: JSON.stringify({ success: true, report }) };
1951
+ });
1952
+
1953
+ /** manage_settings — чтение и изменение глобальных настроек. */
1954
+ const manageSettingsExecute = wrapExecute<SettingsArgs>(async (args) => {
1955
+ const current = await loadSettings();
1956
+ if (args.action === "get") {
1957
+ return { content: JSON.stringify({ success: true, settings: current }) };
1958
+ }
1959
+
1960
+ if (
1961
+ args.maxConcurrent === undefined &&
1962
+ args.winterMode === undefined &&
1963
+ args.notifications === undefined &&
1964
+ args.history === undefined &&
1965
+ args.integrations === undefined
1966
+ ) {
1967
+ return {
1968
+ content: JSON.stringify({
1969
+ success: false,
1970
+ error:
1971
+ "Для action=update передайте хотя бы одно поле: maxConcurrent, winterMode, notifications, history или integrations.",
1972
+ settings: current,
1973
+ }),
1974
+ };
1975
+ }
1976
+
1977
+ const settings = await saveSettings({
1978
+ maxConcurrent: args.maxConcurrent,
1979
+ winterMode: args.winterMode,
1980
+ notifications: args.notifications as NotificationSettings | undefined,
1981
+ history: args.history as HistorySettings | undefined,
1982
+ integrations: args.integrations as IntegrationSettings | undefined,
1983
+ });
1984
+ return { content: JSON.stringify({ success: true, settings }) };
1985
+ });
1986
+
1987
+ /** manage_templates — список, сохранение и удаление шаблонов задач. */
1988
+ const manageTemplatesExecute = wrapExecute<TemplatesArgs>(async (args) => {
1989
+ if (args.action === "list") {
1990
+ return { content: JSON.stringify({ success: true, templates: await loadTemplates() }) };
1991
+ }
1992
+
1993
+ if (args.action === "delete") {
1994
+ const id = args.id?.trim();
1995
+ if (!id) {
1996
+ return { content: JSON.stringify({ success: false, error: "Для action=delete нужен id шаблона." }) };
1997
+ }
1998
+ const before = await loadTemplates();
1999
+ const existed = before.some((template) => template.id === id);
2000
+ await deleteTemplate(id);
2001
+ return {
2002
+ content: JSON.stringify({
2003
+ success: existed,
2004
+ message: existed ? `Шаблон ${id} удалён.` : `Шаблон ${id} не найден.`,
2005
+ }),
2006
+ };
2007
+ }
2008
+
2009
+ const { action, ...fields } = args;
2010
+ if (!fields.name?.trim() || !fields.prompt?.trim()) {
2011
+ return {
2012
+ content: JSON.stringify({
2013
+ success: false,
2014
+ error: "Для action=save нужны непустые name и prompt.",
2015
+ }),
2016
+ };
2017
+ }
2018
+ const template = await saveTemplate(fields as Omit<TaskTemplate, "id"> & { id?: string });
2019
+ return { content: JSON.stringify({ success: true, template }) };
2020
+ });
2021
+
2022
+ /** manage_profiles — список, создание, переключение и удаление профилей. */
2023
+ const manageProfilesExecute = wrapExecute<ProfilesArgs>(async (args) => {
2024
+ if (args.action === "list") {
2025
+ return {
2026
+ content: JSON.stringify({
2027
+ success: true,
2028
+ current: getProfileName(),
2029
+ pinnedByEnv: isProfilePinnedByEnv(),
2030
+ profiles: listProfiles(),
2031
+ }),
2032
+ };
2033
+ }
2034
+
2035
+ const name = args.name?.trim();
2036
+ if (!name) {
2037
+ return {
2038
+ content: JSON.stringify({
2039
+ success: false,
2040
+ error: `Для action=${args.action} нужно имя профиля.`,
2041
+ }),
2042
+ };
2043
+ }
2044
+
2045
+ if (args.action === "create") {
2046
+ const meta = createProfile(name, args.port);
2047
+ const profile = listProfiles().find((item) => item.name === meta.name);
2048
+ return {
2049
+ content: JSON.stringify({
2050
+ success: true,
2051
+ message: `Профиль "${meta.name}" создан (порт дашборда ${meta.port}).`,
2052
+ profile: profile ?? {
2053
+ name: meta.name,
2054
+ dir: getProfileDir(meta.name),
2055
+ port: meta.port,
2056
+ isDefault: meta.name === DEFAULT_PROFILE,
2057
+ active: meta.name === getProfileName(),
2058
+ },
2059
+ }),
2060
+ };
2061
+ }
1162
2062
 
1163
- /** matrix_control — результаты, отмена и очистка матриц. */
1164
- const matrixControlExecute = wrapExecute<MatrixControlArgs>(async (args) => {
1165
- if (args.action === "cleanup") {
1166
- const removed = await cleanupOrphanedMatrixTasks();
2063
+ if (args.action === "switch") {
2064
+ setActiveProfile(name);
2065
+ const current = getProfileName();
1167
2066
  return {
1168
2067
  content: JSON.stringify({
1169
2068
  success: true,
1170
- message:
1171
- removed.length > 0
1172
- ? `Удалено осиротевших задач: ${removed.length}.`
1173
- : "Осиротевших задач не найдено.",
1174
- removed,
2069
+ current,
2070
+ restartRequired: true,
2071
+ message: isProfilePinnedByEnv()
2072
+ ? `Профиль задан переменной OPENCODE_SCHEDULER_PROFILE=${current}. Перезапустите OpenCode.`
2073
+ : `Активный профиль: ${sanitizeProfileName(name)}. Перезапустите OpenCode, чтобы применить изменения.`,
1175
2074
  }),
1176
2075
  };
1177
2076
  }
1178
2077
 
1179
- const name = args.name?.trim();
1180
- if (!name) {
2078
+ const removed = deleteProfile(name);
2079
+ return {
2080
+ content: JSON.stringify({
2081
+ success: removed,
2082
+ message: removed
2083
+ ? `Профиль "${sanitizeProfileName(name)}" удалён вместе с его БД и настройками.`
2084
+ : "Профиль не найден.",
2085
+ }),
2086
+ };
2087
+ });
2088
+
2089
+ /** transfer_tasks — экспорт и импорт задач. */
2090
+ const transferTasksExecute = wrapExecute<TransferArgs>(async (args) => {
2091
+ if (args.action === "export") {
2092
+ const tasks = await scheduler.listTasks();
2093
+ const { data, count } = await buildExportJson(
2094
+ tasks.map((task) => ({ ...task, name: task.taskName || "" }))
2095
+ );
2096
+ return { content: JSON.stringify({ success: true, data, count }) };
2097
+ }
2098
+
2099
+ if (!args.data) {
2100
+ return { content: JSON.stringify({ success: false, error: "Для action=import нужны данные экспорта." }) };
2101
+ }
2102
+ const parsed = parseImportJson(args.data);
2103
+ if (parsed.tasks.length === 0) {
1181
2104
  return {
1182
2105
  content: JSON.stringify({
1183
2106
  success: false,
1184
- error: `Для action=${args.action} нужен name матрицы.`,
2107
+ error: "В данных нет задач для импорта.",
2108
+ errors: parsed.errors,
1185
2109
  }),
1186
2110
  };
1187
2111
  }
1188
2112
 
1189
- if (args.action === "cancel") {
2113
+ const imported: string[] = [];
2114
+ const errors: string[] = [...parsed.errors];
2115
+ for (const def of parsed.tasks) {
1190
2116
  try {
1191
- const result = await cancelMatrixRun(name);
1192
- return {
1193
- content: JSON.stringify({
1194
- success: true,
1195
- message: result.message,
1196
- cancelled: result.cancelled,
1197
- }),
1198
- };
2117
+ await schedulerCreateTask(
2118
+ def.name,
2119
+ def.schedule,
2120
+ def.prompt,
2121
+ def.timeoutSeconds,
2122
+ def.workingDirectory ?? def.workdir,
2123
+ def.retryCount,
2124
+ def.retryDelay,
2125
+ def.qualityGate,
2126
+ def.nextTaskOnSuccess,
2127
+ def.nextTaskOnError,
2128
+ def.triggerType,
2129
+ def.watchPath,
2130
+ def.dependsOn,
2131
+ def.model,
2132
+ def.priority,
2133
+ def.beforeScript,
2134
+ def.afterScript,
2135
+ def.mcpEvent,
2136
+ def.workspaceId,
2137
+ def.allowedTools,
2138
+ def.deniedTools,
2139
+ def.matrix,
2140
+ def.matrixParentId,
2141
+ "create",
2142
+ def.timezone,
2143
+ def.notBefore,
2144
+ def.notAfter,
2145
+ def.pausedUntil,
2146
+ def.runAt
2147
+ );
2148
+ await saveTaskDefinition(def);
2149
+ imported.push(def.name);
1199
2150
  } catch (err: any) {
1200
- return {
1201
- content: JSON.stringify({
1202
- success: false,
1203
- error: err instanceof Error ? err.message : String(err),
1204
- }),
1205
- };
2151
+ errors.push(`${def.name}: ${err instanceof Error ? err.message : String(err)}`);
2152
+ }
2153
+ }
2154
+ await refreshFileTriggers();
2155
+ return {
2156
+ content: JSON.stringify({ success: errors.length === 0, imported, errors }),
2157
+ };
2158
+ });
2159
+
2160
+ /** send_notification — тестовое уведомление или дайджест. */
2161
+ const sendNotificationExecute = wrapExecute<NotificationArgs>(async (args) => {
2162
+ const result =
2163
+ args.action === "test"
2164
+ ? await sendTestNotification()
2165
+ : await sendDigestNow({ updateLastSentAt: false });
2166
+ return { content: JSON.stringify(result) };
2167
+ });
2168
+
2169
+ /** get_dashboard_info — порт дашборда, платформа и активный профиль. */
2170
+ const getDashboardInfoExecute = wrapExecute<DashboardInfoArgs>(async () => {
2171
+ const port = getDashboardPort();
2172
+ return {
2173
+ content: JSON.stringify({
2174
+ success: true,
2175
+ port,
2176
+ url: port ? `http://127.0.0.1:${port}` : null,
2177
+ platform: scheduler.platform,
2178
+ title: scheduler.title,
2179
+ profile: getProfileName(),
2180
+ }),
2181
+ };
2182
+ });
2183
+
2184
+ /** cleanup_history — удаление старых записей истории. */
2185
+ const cleanupHistoryExecute = wrapExecute<CleanupHistoryArgs>(async (args) => {
2186
+ const report = await runHistoryRetention({
2187
+ retentionDays: args.retentionDays,
2188
+ maxRecords: args.maxRecords,
2189
+ });
2190
+ return {
2191
+ content: JSON.stringify({
2192
+ success: true,
2193
+ message: report.skipped
2194
+ ? report.skipped
2195
+ : `Удалено ${report.deleted} записей (по возрасту: ${report.deletedByAge}, по лимиту: ${report.deletedByCount}), осталось ${report.kept}.`,
2196
+ report,
2197
+ }),
2198
+ };
2199
+ });
2200
+
2201
+ /** emit_event — запуск задач, подписанных на MCP-событие. */
2202
+ const emitEventExecute = wrapExecute<EmitEventArgs>(async (args) => {
2203
+ const eventName = args.eventName?.trim();
2204
+ if (!eventName) {
2205
+ return { content: JSON.stringify({ success: false, error: "Не передано имя события." }) };
2206
+ }
2207
+ const payload = args.payload ?? {};
2208
+ const definitions = await loadTaskDefinitions();
2209
+ const matched = definitions
2210
+ .filter(
2211
+ (def) =>
2212
+ def.triggerType === "mcp-event" &&
2213
+ def.mcpEvent?.event?.toLowerCase() === eventName.toLowerCase() &&
2214
+ matchesEventFilter(def.mcpEvent?.filter, payload)
2215
+ )
2216
+ .sort(
2217
+ (a, b) =>
2218
+ (normalizePriority(b.priority) ?? 0) - (normalizePriority(a.priority) ?? 0)
2219
+ );
2220
+
2221
+ const triggered: string[] = [];
2222
+ for (const def of matched) {
2223
+ try {
2224
+ await runTaskEntry(def.name);
2225
+ triggered.push(def.name);
2226
+ } catch (err: any) {
2227
+ console.error(`[windows-scheduler] emit_event: не удалось запустить ${def.name}:`, err);
1206
2228
  }
1207
2229
  }
2230
+ return {
2231
+ content: JSON.stringify({
2232
+ success: true,
2233
+ message:
2234
+ triggered.length > 0
2235
+ ? `Запущено задач: ${triggered.length}.`
2236
+ : `Нет задач, подписанных на событие "${eventName}".`,
2237
+ triggered,
2238
+ }),
2239
+ };
2240
+ });
2241
+
2242
+ /**
2243
+ * Менеджер файловых триггеров живёт на уровне модуля, чтобы его можно было
2244
+ * обновлять после создания/изменения/удаления задачи. Раньше refresh()
2245
+ * вызывался только при старте плагина, из-за чего новые watchPath начинали
2246
+ * работать лишь после перезапуска OpenCode.
2247
+ */
2248
+ let fileWatcherManager: FileWatchManager | null = null;
1208
2249
 
2250
+ async function refreshFileTriggers(): Promise<void> {
2251
+ if (!fileWatcherManager) return;
1209
2252
  try {
1210
- const report = aggregateMatrixResults(name);
1211
- return { content: JSON.stringify({ success: true, report }) };
2253
+ await fileWatcherManager.refresh();
1212
2254
  } catch (err: any) {
1213
- return {
1214
- content: JSON.stringify({
1215
- success: false,
1216
- error: err instanceof Error ? err.message : String(err),
1217
- }),
1218
- };
2255
+ console.error(
2256
+ `[windows-scheduler] Не удалось обновить файловые триггеры: ${
2257
+ err instanceof Error ? err.message : String(err)
2258
+ }`
2259
+ );
1219
2260
  }
1220
- });
2261
+ }
1221
2262
 
1222
2263
  export default Plugin.define({
1223
2264
  id: "opencode-windows-scheduler",
@@ -1270,6 +2311,42 @@ export default Plugin.define({
1270
2311
  );
1271
2312
  });
1272
2313
 
2314
+ // Спринт 19: автопродолжение задач, поставленных на паузу до даты.
2315
+ // Проверяем сразу при старте и далее раз в 5 минут, пока плагин жив.
2316
+ void resumeExpiredPauses().catch((err: any) => {
2317
+ console.error(
2318
+ `[windows-scheduler] Не удалось проверить автопродолжение: ${
2319
+ err instanceof Error ? err.message : String(err)
2320
+ }`
2321
+ );
2322
+ });
2323
+ const pausedUntilTimer = setInterval(() => {
2324
+ void resumeExpiredPauses().catch((err: any) => {
2325
+ console.error(
2326
+ `[windows-scheduler] Не удалось проверить автопродолжение: ${
2327
+ err instanceof Error ? err.message : String(err)
2328
+ }`
2329
+ );
2330
+ });
2331
+ }, PAUSED_UNTIL_CHECK_MS);
2332
+ pausedUntilTimer.unref?.();
2333
+
2334
+ // Спринт 20: дайджест и детектор зависших матриц. Проверяем сразу при
2335
+ // старте и далее раз в минуту; таймер не держит процесс Node живым.
2336
+ const notificationTimer = setInterval(() => {
2337
+ void maybeSendDigest().catch(() => undefined);
2338
+ void checkStuckMatrices().catch((err: any) => {
2339
+ console.error(
2340
+ `[windows-scheduler] Детектор зависших матриц: ${
2341
+ err instanceof Error ? err.message : String(err)
2342
+ }`
2343
+ );
2344
+ });
2345
+ }, NOTIFICATION_CHECK_MS);
2346
+ notificationTimer.unref?.();
2347
+ void maybeSendDigest().catch(() => undefined);
2348
+ void checkStuckMatrices().catch(() => undefined);
2349
+
1273
2350
  // Инициализация блокировок: создаём директорию и очищаем зависшие lock-файлы (>24 ч).
1274
2351
  const lockManager = new LockManager(LOCK_DIR);
1275
2352
  await lockManager.initialize();
@@ -1293,22 +2370,24 @@ export default Plugin.define({
1293
2370
  // Catch-up имеет смысл только для cron-задач.
1294
2371
  if ((def.triggerType ?? "cron") !== "cron") continue;
1295
2372
  if (!def.schedule) continue;
1296
- const prevRun = previousRunTime(def.schedule, now);
1297
- if (!prevRun) continue;
1298
- const ageMs = now.getTime() - prevRun.getTime();
2373
+ // Задача на паузе до даты — её включит авто-продолжение.
2374
+ if (def.pausedUntil) continue;
2375
+ const prev = prevRun(def.schedule, now, def.timezone);
2376
+ if (!prev) continue;
2377
+ const ageMs = now.getTime() - prev.getTime();
1299
2378
  if (ageMs < catchUpThresholdMs) continue;
1300
2379
 
1301
2380
  // Есть ли запись в истории после предполагаемого времени запуска?
1302
2381
  const ranAfter = history.some(
1303
2382
  (r) =>
1304
2383
  r.taskName.toLowerCase() === def.name.toLowerCase() &&
1305
- new Date(r.startedAt).getTime() >= prevRun.getTime()
2384
+ new Date(r.startedAt).getTime() >= prev.getTime()
1306
2385
  );
1307
2386
  if (ranAfter) continue;
1308
2387
 
1309
2388
  // Запускаем задачу и пишем в лог.
1310
2389
  try {
1311
- await scheduler.runTask(def.name);
2390
+ await runTaskEntry(def.name);
1312
2391
  console.log(
1313
2392
  `[windows-scheduler] Запущено восстановление пропущенной задачи "${def.name}" (последний срабатывал ~${Math.round(ageMs / 1000)} с назад).`
1314
2393
  );
@@ -1329,9 +2408,9 @@ export default Plugin.define({
1329
2408
 
1330
2409
  // Файловые триггеры (File Watchers): задачи с triggerType === "file"
1331
2410
  // запускаются при изменении watchPath через chokidar (с дебаунсом).
1332
- const fileWatcherManager = new FileWatchManager(async (taskName) => {
2411
+ fileWatcherManager = new FileWatchManager(async (taskName) => {
1333
2412
  try {
1334
- await scheduler.runTask(taskName);
2413
+ await runTaskEntry(taskName);
1335
2414
  console.log(
1336
2415
  `[windows-scheduler] Запуск задачи "${taskName}" по изменению отслеживаемого файла.`
1337
2416
  );
@@ -1343,7 +2422,7 @@ export default Plugin.define({
1343
2422
  );
1344
2423
  }
1345
2424
  });
1346
- void fileWatcherManager.refresh();
2425
+ void refreshFileTriggers();
1347
2426
 
1348
2427
  const registration = await ctx.tool.transform((editor) => {
1349
2428
  // editor.add регистрирует новые инструменты плагина с codemode: true,
@@ -1459,10 +2538,100 @@ export default Plugin.define({
1459
2538
  name: "matrix_control",
1460
2539
  input: matrixControlSchema,
1461
2540
  description:
1462
- "Matrix lifecycle: results (aggregate status/counters of a matrix), cancel (cancel pending clones, stop running ones) or cleanup (delete orphaned clones and aggregators whose parent is gone).",
2541
+ "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).",
1463
2542
  options: { codemode: true },
1464
2543
  execute: matrixControlExecute as any,
1465
2544
  });
2545
+
2546
+ editor.add({
2547
+ name: "get_metrics",
2548
+ input: getMetricsSchema,
2549
+ description:
2550
+ "Returns aggregate run metrics: total runs, successes and failures across all tasks.",
2551
+ options: { codemode: true },
2552
+ execute: getMetricsExecute as any,
2553
+ });
2554
+
2555
+ editor.add({
2556
+ name: "get_analytics",
2557
+ input: getAnalyticsSchema,
2558
+ description:
2559
+ "Returns an analytics report for a period: run counts, success rate, duration, tokens and cost, plus top tasks.",
2560
+ options: { codemode: true },
2561
+ execute: getAnalyticsExecute as any,
2562
+ });
2563
+
2564
+ editor.add({
2565
+ name: "manage_settings",
2566
+ input: manageSettingsSchema,
2567
+ description:
2568
+ "Reads or updates global scheduler settings: maxConcurrent, winterMode, notifications (webhook, filters, matrix alerts, digest) and history retention. Updates are merged into the current settings.",
2569
+ options: { codemode: true },
2570
+ execute: manageSettingsExecute as any,
2571
+ });
2572
+
2573
+ editor.add({
2574
+ name: "manage_templates",
2575
+ input: manageTemplatesSchema,
2576
+ description:
2577
+ "Lists, saves or deletes reusable task templates (prompt, schedule, retries, Quality Gate, chains, triggers, tool restrictions).",
2578
+ options: { codemode: true },
2579
+ execute: manageTemplatesExecute as any,
2580
+ });
2581
+
2582
+ editor.add({
2583
+ name: "manage_profiles",
2584
+ input: manageProfilesSchema,
2585
+ description:
2586
+ "Lists, creates, switches or deletes isolated scheduler profiles (separate database, settings and dashboard port). Switching requires an OpenCode restart.",
2587
+ options: { codemode: true },
2588
+ execute: manageProfilesExecute as any,
2589
+ });
2590
+
2591
+ editor.add({
2592
+ name: "transfer_tasks",
2593
+ input: transferTasksSchema,
2594
+ description:
2595
+ "Exports all tasks as a portable JSON snapshot or imports tasks from such a snapshot, recreating them in the OS scheduler.",
2596
+ options: { codemode: true },
2597
+ execute: transferTasksExecute as any,
2598
+ });
2599
+
2600
+ editor.add({
2601
+ name: "send_notification",
2602
+ input: sendNotificationSchema,
2603
+ description:
2604
+ "Sends a test notification through the configured channel or sends the digest immediately.",
2605
+ options: { codemode: true },
2606
+ execute: sendNotificationExecute as any,
2607
+ });
2608
+
2609
+ editor.add({
2610
+ name: "get_dashboard_info",
2611
+ input: getDashboardInfoSchema,
2612
+ description:
2613
+ "Returns dashboard port and URL, OS platform, scheduler title and the active profile.",
2614
+ options: { codemode: true },
2615
+ execute: getDashboardInfoExecute as any,
2616
+ });
2617
+
2618
+ editor.add({
2619
+ name: "cleanup_history",
2620
+ input: cleanupHistorySchema,
2621
+ description:
2622
+ "Deletes old run history by age and/or record cap, using the stored retention policy unless overridden.",
2623
+ options: { codemode: true },
2624
+ execute: cleanupHistoryExecute as any,
2625
+ });
2626
+
2627
+ editor.add({
2628
+ name: "emit_event",
2629
+ input: emitEventSchema,
2630
+ description:
2631
+ "Emits an MCP event: every task with triggerType 'mcp-event' matching the event name (and filter) is started in priority order.",
2632
+ options: { codemode: true },
2633
+ execute: emitEventExecute as any,
2634
+ });
1466
2635
  });
1467
2636
 
1468
2637
  // Нативный скилл плагина: агент видит краткое описание в списке доступных
@@ -1522,9 +2691,16 @@ export default Plugin.define({
1522
2691
  allowedTools,
1523
2692
  deniedTools,
1524
2693
  matrix,
2694
+ timezone,
2695
+ notBefore,
2696
+ notAfter,
2697
+ runAt,
2698
+ delaySeconds,
2699
+ session,
2700
+ sessionMaxRuns,
1525
2701
  } = input as {
1526
2702
  name: string;
1527
- schedule: string;
2703
+ schedule?: string;
1528
2704
  prompt: string;
1529
2705
  retryCount?: number;
1530
2706
  retryDelay?: number;
@@ -1532,7 +2708,7 @@ export default Plugin.define({
1532
2708
  nextTaskOnSuccess?: string;
1533
2709
  nextTaskOnError?: string;
1534
2710
  dependsOn?: string[];
1535
- triggerType?: "cron" | "file" | "mcp-event";
2711
+ triggerType?: "cron" | "file" | "mcp-event" | "once";
1536
2712
  watchPath?: string;
1537
2713
  workingDirectory?: string;
1538
2714
  model?: string;
@@ -1544,11 +2720,42 @@ export default Plugin.define({
1544
2720
  allowedTools?: string[];
1545
2721
  deniedTools?: string[];
1546
2722
  matrix?: MatrixConfig;
2723
+ timezone?: string;
2724
+ notBefore?: string;
2725
+ notAfter?: string;
2726
+ runAt?: string;
2727
+ delaySeconds?: number;
2728
+ session?: "new" | "reuse" | "last";
2729
+ sessionMaxRuns?: number;
1547
2730
  };
2731
+ let effectiveRunAt: string | undefined;
2732
+ if (triggerType === "once") {
2733
+ const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
2734
+ if (!normalized.ok) {
2735
+ return { success: false, message: `Задача "${name}": ${normalized.error}` };
2736
+ }
2737
+ effectiveRunAt = normalized.runAt;
2738
+ }
2739
+ let effectiveSession: "new" | "reuse" | "last" = "new";
2740
+ if (session !== undefined) {
2741
+ const normalizedSession = normalizeSessionMode(session);
2742
+ if (!normalizedSession) {
2743
+ return { success: false, message: `Задача "${name}": неизвестный режим сессии "${String(session)}".` };
2744
+ }
2745
+ effectiveSession = normalizedSession;
2746
+ }
2747
+ if (
2748
+ sessionMaxRuns !== undefined &&
2749
+ (!Number.isInteger(sessionMaxRuns) || sessionMaxRuns < 1)
2750
+ ) {
2751
+ return { success: false, message: `Задача "${name}": sessionMaxRuns должен быть целым числом ≥ 1.` };
2752
+ }
2753
+ const effectiveSessionId =
2754
+ effectiveSession === "reuse" ? generateSessionId() : undefined;
1548
2755
  try {
1549
2756
  await schedulerCreateTask(
1550
2757
  name,
1551
- schedule,
2758
+ schedule ?? "",
1552
2759
  prompt,
1553
2760
  undefined,
1554
2761
  workingDirectory,
@@ -1568,7 +2775,17 @@ export default Plugin.define({
1568
2775
  workspaceId,
1569
2776
  allowedTools,
1570
2777
  deniedTools,
1571
- matrix
2778
+ matrix,
2779
+ undefined,
2780
+ "create",
2781
+ timezone,
2782
+ notBefore,
2783
+ notAfter,
2784
+ undefined,
2785
+ effectiveRunAt,
2786
+ effectiveSession,
2787
+ effectiveSessionId,
2788
+ sessionMaxRuns
1572
2789
  );
1573
2790
  return { success: true, message: `Задача "${name}" успешно создана.` };
1574
2791
  } catch (err: any) {
@@ -1699,7 +2916,7 @@ export default Plugin.define({
1699
2916
  const triggered: string[] = [];
1700
2917
  for (const def of matched) {
1701
2918
  try {
1702
- await scheduler.runTask(def.name);
2919
+ await runTaskEntry(def.name);
1703
2920
  triggered.push(def.name);
1704
2921
  console.log(
1705
2922
  `[windows-scheduler] Запуск задачи "${def.name}" по MCP-событию "${normalized}".`
@@ -1720,8 +2937,8 @@ export default Plugin.define({
1720
2937
  };
1721
2938
  },
1722
2939
  pause_task: async (input: unknown) => {
1723
- const { name } = input as { name: string };
1724
- const result = await pauseOrResumeTask(name, true);
2940
+ const { name, until } = input as { name: string; until?: string };
2941
+ const result = await pauseOrResumeTask(name, true, until);
1725
2942
  return { success: result.success, message: result.message };
1726
2943
  },
1727
2944
  resume_task: async (input: unknown) => {
@@ -1741,9 +2958,22 @@ export default Plugin.define({
1741
2958
  return { success: true, logs: result.logs };
1742
2959
  },
1743
2960
  get_history: async (input: unknown) => {
1744
- const { limit } = input as { limit?: number };
1745
- const records = await loadHistory();
1746
- return { records: records.slice(0, limit ?? 10) };
2961
+ // Контракт совпадает с агентским инструментом get_history:
2962
+ // limit по умолчанию 20 (максимум 200), фильтры taskName и status.
2963
+ const { limit, taskName, status } = input as {
2964
+ limit?: number;
2965
+ taskName?: string;
2966
+ status?: string;
2967
+ };
2968
+ const filter = taskName?.trim().toLowerCase();
2969
+ const statusFilter = status?.trim().toLowerCase();
2970
+ const max = Math.max(1, Math.min(Math.floor(limit ?? 20), 200));
2971
+ const records = (await loadHistory())
2972
+ .filter((record) => !filter || record.taskName.toLowerCase() === filter)
2973
+ .filter(
2974
+ (record) => !statusFilter || String(record.status).toLowerCase() === statusFilter
2975
+ );
2976
+ return { records: records.slice(0, max) };
1747
2977
  },
1748
2978
  get_metrics: async () => {
1749
2979
  return await loadMetrics();
@@ -1913,36 +3143,57 @@ export default Plugin.define({
1913
3143
  return {
1914
3144
  workspaces: listWorkspaces().map((workspace) => ({
1915
3145
  ...workspace,
3146
+ env: maskEnvForLog(workspace.env),
1916
3147
  gitBranch: readGitBranch(workspace.path) ?? null,
1917
3148
  })),
1918
3149
  };
1919
3150
  },
1920
3151
  add_workspace: async (input: unknown) => {
1921
3152
  try {
1922
- const { name, path: workspacePath, color } = input as {
3153
+ const { name, path: workspacePath, color, env, envFile } = input as {
1923
3154
  name?: string;
1924
3155
  path: string;
1925
3156
  color?: string;
3157
+ env?: Record<string, string> | null;
3158
+ envFile?: string | null;
3159
+ };
3160
+ const workspace = addWorkspace({ name, path: workspacePath, color, env, envFile });
3161
+ return {
3162
+ success: true,
3163
+ workspace: {
3164
+ ...workspace,
3165
+ env: maskEnvForLog(workspace.env),
3166
+ gitBranch: readGitBranch(workspace.path) ?? null,
3167
+ },
1926
3168
  };
1927
- const workspace = addWorkspace({ name, path: workspacePath, color });
1928
- return { success: true, workspace: { ...workspace, gitBranch: readGitBranch(workspace.path) ?? null } };
1929
3169
  } catch (err: any) {
1930
3170
  return { success: false, error: err instanceof Error ? err.message : String(err) };
1931
3171
  }
1932
3172
  },
1933
3173
  update_workspace: async (input: unknown) => {
1934
3174
  try {
1935
- const { id, name, path: workspacePath, color } = input as {
3175
+ const { id, name, path: workspacePath, color, env, envFile } = input as {
1936
3176
  id: string;
1937
3177
  name?: string;
1938
3178
  path?: string;
1939
3179
  color?: string;
3180
+ env?: Record<string, string> | null;
3181
+ envFile?: string | null;
1940
3182
  };
1941
- const workspace = updateWorkspace(id, { name, path: workspacePath, color });
3183
+ const workspace = updateWorkspace(id, { name, path: workspacePath, color, env, envFile });
1942
3184
  if (!workspace) {
1943
3185
  return { success: false, error: "Workspace не найден." };
1944
3186
  }
1945
- return { success: true, workspace: { ...workspace, gitBranch: readGitBranch(workspace.path) ?? null } };
3187
+ // env-файлы существующих задач перегенерируются сразу (Спринт 21).
3188
+ await refreshWorkspaceEnvFiles(workspace.id);
3189
+ return {
3190
+ success: true,
3191
+ workspace: {
3192
+ ...workspace,
3193
+ env: maskEnvForLog(workspace.env),
3194
+ gitBranch: readGitBranch(workspace.path) ?? null,
3195
+ },
3196
+ };
1946
3197
  } catch (err: any) {
1947
3198
  return { success: false, error: err instanceof Error ? err.message : String(err) };
1948
3199
  }
@@ -1961,22 +3212,90 @@ export default Plugin.define({
1961
3212
  return { success: false, message: err instanceof Error ? err.message : String(err) };
1962
3213
  }
1963
3214
  },
3215
+ get_profiles: async () => {
3216
+ return {
3217
+ current: getProfileName(),
3218
+ pinnedByEnv: isProfilePinnedByEnv(),
3219
+ profiles: listProfiles(),
3220
+ };
3221
+ },
3222
+ set_profile: async (input: unknown) => {
3223
+ const { name } = input as { name: string };
3224
+ try {
3225
+ setActiveProfile(name);
3226
+ const current = getProfileName();
3227
+ return {
3228
+ success: true,
3229
+ current,
3230
+ restartRequired: true,
3231
+ message: isProfilePinnedByEnv()
3232
+ ? `Профиль задан переменной OPENCODE_SCHEDULER_PROFILE=${current}. Перезапустите OpenCode, чтобы применить изменения.`
3233
+ : `Активный профиль: ${sanitizeProfileName(name)}. Перезапустите OpenCode, чтобы применить изменения.`,
3234
+ };
3235
+ } catch (err: any) {
3236
+ return {
3237
+ success: false,
3238
+ current: getProfileName(),
3239
+ restartRequired: false,
3240
+ message: err instanceof Error ? err.message : String(err),
3241
+ };
3242
+ }
3243
+ },
3244
+ create_profile: async (input: unknown) => {
3245
+ const { name, port } = input as { name: string; port?: number };
3246
+ try {
3247
+ const meta = createProfile(name, port);
3248
+ const profile = listProfiles().find((item) => item.name === meta.name);
3249
+ return {
3250
+ success: true,
3251
+ message: `Профиль "${meta.name}" создан (порт дашборда ${meta.port}).`,
3252
+ profile: profile ?? {
3253
+ name: meta.name,
3254
+ dir: getProfileDir(meta.name),
3255
+ port: meta.port,
3256
+ isDefault: meta.name === DEFAULT_PROFILE,
3257
+ active: meta.name === getProfileName(),
3258
+ },
3259
+ };
3260
+ } catch (err: any) {
3261
+ return {
3262
+ success: false,
3263
+ error: err instanceof Error ? err.message : String(err),
3264
+ };
3265
+ }
3266
+ },
3267
+ delete_profile: async (input: unknown) => {
3268
+ const { name } = input as { name: string };
3269
+ try {
3270
+ const removed = deleteProfile(name);
3271
+ return {
3272
+ success: removed,
3273
+ message: removed
3274
+ ? `Профиль "${sanitizeProfileName(name)}" удалён вместе с его БД и настройками.`
3275
+ : "Профиль не найден.",
3276
+ };
3277
+ } catch (err: any) {
3278
+ return { success: false, message: err instanceof Error ? err.message : String(err) };
3279
+ }
3280
+ },
1964
3281
  get_settings: async () => {
1965
3282
  return await loadSettings();
1966
3283
  },
1967
3284
  save_settings: async (input: unknown) => {
1968
- const { maxConcurrent, winterMode, notifications, history } = input as {
3285
+ const { maxConcurrent, winterMode, notifications, history, integrations } = input as {
1969
3286
  maxConcurrent?: number;
1970
3287
  winterMode?: boolean;
1971
3288
  notifications?: NotificationSettings;
1972
3289
  history?: HistorySettings;
3290
+ integrations?: IntegrationSettings;
1973
3291
  };
1974
3292
  const current = await loadSettings();
1975
3293
  if (
1976
3294
  maxConcurrent === undefined &&
1977
3295
  winterMode === undefined &&
1978
3296
  notifications === undefined &&
1979
- history === undefined
3297
+ history === undefined &&
3298
+ integrations === undefined
1980
3299
  ) {
1981
3300
  return {
1982
3301
  success: false,
@@ -1984,6 +3303,7 @@ export default Plugin.define({
1984
3303
  winterMode: current.winterMode,
1985
3304
  notifications: current.notifications,
1986
3305
  history: current.history,
3306
+ integrations: current.integrations,
1987
3307
  };
1988
3308
  }
1989
3309
  const settings = await saveSettings({
@@ -1991,6 +3311,7 @@ export default Plugin.define({
1991
3311
  winterMode,
1992
3312
  notifications,
1993
3313
  history,
3314
+ integrations,
1994
3315
  });
1995
3316
  return {
1996
3317
  success: true,
@@ -1998,11 +3319,16 @@ export default Plugin.define({
1998
3319
  winterMode: settings.winterMode,
1999
3320
  notifications: settings.notifications,
2000
3321
  history: settings.history,
3322
+ integrations: settings.integrations,
2001
3323
  };
2002
3324
  },
2003
3325
  test_notification: async () => {
2004
3326
  return await sendTestNotification();
2005
3327
  },
3328
+ send_digest: async () => {
3329
+ // Ручная отправка не сдвигает плановое расписание дайджеста.
3330
+ return await sendDigestNow({ updateLastSentAt: false });
3331
+ },
2006
3332
  get_templates: async () => {
2007
3333
  try {
2008
3334
  return { templates: await loadTemplates() };
@@ -2115,7 +3441,13 @@ export default Plugin.define({
2115
3441
  def.allowedTools,
2116
3442
  def.deniedTools,
2117
3443
  def.matrix,
2118
- def.matrixParentId
3444
+ def.matrixParentId,
3445
+ "create",
3446
+ def.timezone,
3447
+ def.notBefore,
3448
+ def.notAfter,
3449
+ def.pausedUntil,
3450
+ def.runAt
2119
3451
  );
2120
3452
  await saveTaskDefinition(def);
2121
3453
  imported.push(def.name);
@@ -2164,10 +3496,12 @@ export default Plugin.define({
2164
3496
  }
2165
3497
 
2166
3498
  return () => {
3499
+ clearInterval(pausedUntilTimer);
3500
+ clearInterval(notificationTimer);
2167
3501
  rpcRegistration.dispose();
2168
3502
  registration.dispose();
2169
3503
  void skillRegistration?.dispose();
2170
- void fileWatcherManager.stop();
3504
+ if (fileWatcherManager) void fileWatcherManager.stop();
2171
3505
  // При выгрузке плагина обязательно закрываем HTTP-сервер дашборда,
2172
3506
  // затем соединение SQLite (чекпойнт WAL выполняется в closeDb).
2173
3507
  void closeDashboardServer().finally(() => closeDb());
@@ -2248,7 +3582,7 @@ async function schedulerCreateTask(
2248
3582
  qualityGate?: string,
2249
3583
  nextTaskOnSuccess?: string,
2250
3584
  nextTaskOnError?: string,
2251
- triggerType?: "cron" | "file" | "mcp-event",
3585
+ triggerType?: "cron" | "file" | "mcp-event" | "once",
2252
3586
  watchPath?: string,
2253
3587
  dependsOn?: string[],
2254
3588
  model?: string,
@@ -2262,12 +3596,32 @@ async function schedulerCreateTask(
2262
3596
  matrix?: MatrixConfig,
2263
3597
  matrixParentId?: string,
2264
3598
  /** create — пересоздать клонов с нуля; sync — только diff (Спринт 17). */
2265
- matrixMode: "create" | "sync" = "create"
3599
+ matrixMode: "create" | "sync" = "create",
3600
+ /** IANA-зона задачи (Спринт 19). Не системная зона → poll-режим шлюза. */
3601
+ timezone?: string,
3602
+ /** Окно запуска: начало "HH:MM" (вне окна запуск переносится). */
3603
+ notBefore?: string,
3604
+ /** Окончание окна "HH:MM"; может быть меньше notBefore (через полночь). */
3605
+ notAfter?: string,
3606
+ /** Пауза до момента ISO; после него задача возобновляется автоматически. */
3607
+ pausedUntil?: string,
3608
+ /** Абсолютное время однократного запуска (ISO, только triggerType=once). */
3609
+ runAt?: string,
3610
+ /** Режим сессии OpenCode (Спринт 24): new (по умолчанию), reuse, last. */
3611
+ session?: "new" | "reuse" | "last",
3612
+ /** ID сессии для reuse (генерируется автоматически; пользователь не задаёт). */
3613
+ sessionId?: string,
3614
+ /** Сколько запусков переживает reuse-сессия до ротации (0/undefined — без ограничения). */
3615
+ sessionMaxRuns?: number
2266
3616
  ): Promise<void> {
2267
3617
  const normalizedModel = model?.trim() || undefined;
2268
3618
  const normalizedPriority = normalizePriority(priority);
2269
3619
  const normalizedBefore = beforeScript?.trim() || undefined;
2270
3620
  const normalizedAfter = afterScript?.trim() || undefined;
3621
+ const normalizedTz = timezone?.trim() || undefined;
3622
+ const normalizedNotBefore = notBefore?.trim() || undefined;
3623
+ const normalizedNotAfter = notAfter?.trim() || undefined;
3624
+ const normalizedPausedUntil = pausedUntil?.trim() || undefined;
2271
3625
  const normalizedMcpEvent =
2272
3626
  mcpEvent && mcpEvent.event?.trim()
2273
3627
  ? {
@@ -2277,6 +3631,30 @@ async function schedulerCreateTask(
2277
3631
  }
2278
3632
  : undefined;
2279
3633
  let effectiveTriggerType = triggerType ?? "cron";
3634
+ // One-shot: нормализуем время до создания файлов и задачи в ОС.
3635
+ // Для остальных триггеров runAt не имеет смысла и отбрасывается.
3636
+ let effectiveRunAt: string | undefined;
3637
+ if (effectiveTriggerType === "once") {
3638
+ const normalized = normalizeOneShotRunAt({ runAt });
3639
+ if (!normalized.ok) {
3640
+ throw new Error(`Задача "${name}": ${normalized.error}`);
3641
+ }
3642
+ effectiveRunAt = normalized.runAt;
3643
+ }
3644
+ // Спринт 24: режим сессии. sessionId генерируется автоматически для reuse;
3645
+ // значение пользователя никогда не принимаем.
3646
+ let effectiveSession: "new" | "reuse" | "last" = "new";
3647
+ let effectiveSessionId: string | undefined;
3648
+ if (session !== undefined) {
3649
+ const normalizedSession = normalizeSessionMode(session);
3650
+ if (!normalizedSession) {
3651
+ throw new Error(`Задача "${name}": неизвестный режим сессии "${String(session)}".`);
3652
+ }
3653
+ effectiveSession = normalizedSession;
3654
+ }
3655
+ if (effectiveSession === "reuse") {
3656
+ effectiveSessionId = sessionId?.trim() || generateSessionId();
3657
+ }
2280
3658
  // Role-scoped: нормализуем списки инструментов (trim, дедуп без регистра).
2281
3659
  // Пустой allowedTools — осознанная блокировка: «белый список из нуля
2282
3660
  // инструментов» это почти наверняка ошибка конфигурации.
@@ -2358,15 +3736,49 @@ async function schedulerCreateTask(
2358
3736
  // расписание не используется вовсе.
2359
3737
  if (effectiveTriggerType === "cron") {
2360
3738
  try {
2361
- convertCronToSchTasks(schedule);
3739
+ // Расширенная грамматика (Спринт 19): диапазоны, списки, шаги,
3740
+ // имена месяцев/дней, @every, L и FRI#3.
3741
+ parseCron(schedule);
2362
3742
  } catch (err: any) {
2363
3743
  throw new Error(err.message || String(err));
2364
3744
  }
3745
+ if (normalizedTz && !isValidIanaTimeZone(normalizedTz)) {
3746
+ throw new Error(
3747
+ `Задача "${name}": неизвестный часовой пояс "${normalizedTz}". ` +
3748
+ `Укажите IANA-зону, например Europe/Moscow.`
3749
+ );
3750
+ }
3751
+ const windowError = validateLaunchWindow(
3752
+ normalizedNotBefore,
3753
+ normalizedNotAfter
3754
+ );
3755
+ if (windowError) {
3756
+ throw new Error(`Задача "${name}": ${windowError}`);
3757
+ }
2365
3758
  }
2366
3759
 
2367
3760
  const sanitized = sanitizeName(name);
2368
3761
  const lockFile = lockFilePath(sanitized);
2369
3762
  const logFile = path.join(LOG_DIR, `${sanitized}.log`);
3763
+ // Шлюз расписания (Спринт 19): нужен только для cron в poll-режиме
3764
+ // (нестандартный cron или чужая IANA-зона) либо при окне запуска.
3765
+ const gate =
3766
+ effectiveTriggerType === "cron"
3767
+ ? buildScheduleGate(
3768
+ schedule,
3769
+ normalizedTz,
3770
+ normalizedNotBefore,
3771
+ normalizedNotAfter
3772
+ )
3773
+ : undefined;
3774
+ const wrapperGate = gate
3775
+ ? {
3776
+ ...gate,
3777
+ gateFile: gatePath,
3778
+ deferFile: `${lockFile}.defer`,
3779
+ forceFile: `${lockFile}.force`,
3780
+ }
3781
+ : undefined;
2370
3782
  // Workspace имеет приоритет над workingDirectory: одна задача = один repo
2371
3783
  // = один cwd. Мы не угадываем, куда мержить, и не смешиваем контексты.
2372
3784
  const normalizedWorkspaceId = workspaceId?.trim() || undefined;
@@ -2390,6 +3802,13 @@ async function schedulerCreateTask(
2390
3802
  const effectiveWorkingDirectory =
2391
3803
  workspace?.path || workingDirectory?.trim() || projectDirectory || process.cwd();
2392
3804
 
3805
+ // Спринт 21: env-переменные workspace → отдельный файл, который читает обёртка.
3806
+ // Значения не логируются; в лог попадает только факт загрузки.
3807
+ const taskEnvFile = writeWorkspaceEnvFile(workspace, PLUGIN_DIR, sanitized);
3808
+ if (taskEnvFile) {
3809
+ console.log(`[workspace] Задача "${name}": env-переменные workspace подключены.`);
3810
+ }
3811
+
2393
3812
  let promptFile: string;
2394
3813
  try {
2395
3814
  promptFile = await writePromptFile(sanitized, prompt);
@@ -2421,7 +3840,11 @@ async function schedulerCreateTask(
2421
3840
  normalizedAfter,
2422
3841
  workspace?.name,
2423
3842
  normalizedAllowedTools,
2424
- normalizedDeniedTools
3843
+ normalizedDeniedTools,
3844
+ wrapperGate,
3845
+ taskEnvFile,
3846
+ effectiveSession,
3847
+ effectiveSessionId
2425
3848
  );
2426
3849
  } else {
2427
3850
  wrapperPath = await writeBashWrapper({
@@ -2440,6 +3863,13 @@ async function schedulerCreateTask(
2440
3863
  workspaceName: workspace?.name,
2441
3864
  allowedTools: normalizedAllowedTools,
2442
3865
  deniedTools: normalizedDeniedTools,
3866
+ scheduleGate: wrapperGate,
3867
+ envFile: taskEnvFile,
3868
+ sessionMode: effectiveSession,
3869
+ sessionId: effectiveSessionId,
3870
+ ...(effectiveTriggerType === "once" && scheduler.platform === "darwin"
3871
+ ? { oneShotCleanupCommand: buildLaunchdOneShotCleanup(sanitized) }
3872
+ : {}),
2443
3873
  });
2444
3874
  }
2445
3875
  } catch (err: any) {
@@ -2454,17 +3884,24 @@ async function schedulerCreateTask(
2454
3884
  schedule,
2455
3885
  timeoutSeconds: timeoutSeconds ?? 3600,
2456
3886
  triggerType: effectiveTriggerType,
3887
+ ...(effectiveRunAt ? { runAt: effectiveRunAt } : {}),
2457
3888
  workingDirectory: effectiveWorkingDirectory,
2458
3889
  logFile,
2459
3890
  model: normalizedModel,
2460
3891
  priority: normalizedPriority,
3892
+ timezone: normalizedTz,
3893
+ notBefore: normalizedNotBefore,
3894
+ notAfter: normalizedNotAfter,
2461
3895
  });
2462
3896
  } catch (err: any) {
2463
3897
  throw new Error(err instanceof Error ? err.message : String(err));
2464
3898
  }
2465
3899
 
2466
3900
  // Сохраняем определение задачи для последующего экспорта/импорта.
2467
- const existingQueue = matrixMode === "sync" ? getTask(name)?.matrixQueue : undefined;
3901
+ // Определение до перезаписи: нужно и для очереди матрицы, и для счётчика сессии.
3902
+ const previousDefinition = getTask(name);
3903
+ const existingQueue =
3904
+ matrixMode === "sync" ? previousDefinition?.matrixQueue : undefined;
2468
3905
  const taskDefinition: TaskDefinition = {
2469
3906
  name,
2470
3907
  schedule,
@@ -2483,7 +3920,24 @@ async function schedulerCreateTask(
2483
3920
  nextTaskOnSuccess,
2484
3921
  nextTaskOnError,
2485
3922
  triggerType: effectiveTriggerType,
3923
+ runAt: effectiveRunAt,
3924
+ // Спринт 24: сессия. sessionRunCount не экспортируется (internal).
3925
+ session: effectiveSession,
3926
+ sessionId: effectiveSessionId,
3927
+ sessionMaxRuns,
3928
+ // Раньше редактирование всегда сбрасывало счётчик в 0, из-за чего лимит
3929
+ // sessionMaxRuns обходился правкой любого поля задачи. Сохраняем счётчик,
3930
+ // только если сессия и её id не изменились.
3931
+ sessionRunCount: preservedSessionRunCount(
3932
+ previousDefinition,
3933
+ effectiveSession,
3934
+ effectiveSessionId
3935
+ ),
2486
3936
  watchPath: normalizedMatrix ? undefined : watchPath,
3937
+ timezone: normalizedTz,
3938
+ notBefore: normalizedNotBefore,
3939
+ notAfter: normalizedNotAfter,
3940
+ pausedUntil: normalizedPausedUntil,
2487
3941
  allowedTools: normalizedAllowedTools,
2488
3942
  deniedTools: normalizedDeniedTools,
2489
3943
  matrix: normalizedMatrix,
@@ -2540,7 +3994,12 @@ async function schedulerCreateTask(
2540
3994
  clone.allowedTools,
2541
3995
  clone.deniedTools,
2542
3996
  undefined,
2543
- name
3997
+ name,
3998
+ "create",
3999
+ clone.timezone,
4000
+ clone.notBefore,
4001
+ clone.notAfter,
4002
+ clone.pausedUntil
2544
4003
  );
2545
4004
  };
2546
4005
 
@@ -2633,7 +4092,22 @@ async function runTaskEntry(name: string): Promise<{ alreadyRunning: boolean }>
2633
4092
  await runMatrix(definition);
2634
4093
  return { alreadyRunning: false };
2635
4094
  }
2636
- return scheduler.runTask(name);
4095
+
4096
+ // Любой запуск через этот вход — «сейчас», а не «по расписанию»:
4097
+ // run_task_now, RPC GUI, файловый триггер, MCP-событие и catch-up.
4098
+ // Маркер снимает проверку cron/окна внутри обёртки (poll-режим), иначе
4099
+ // запуск молча отменялся бы schedule-gate с кодом 3.
4100
+ const forceFile = await requestImmediateRun(name);
4101
+ try {
4102
+ return await scheduler.runTask(name);
4103
+ } catch (err) {
4104
+ // Планировщик не принял запуск — маркер не нужен, иначе он мог бы
4105
+ // «разрешить» следующий плановый тик в обход расписания.
4106
+ await fs.unlink(forceFile).catch(() => {
4107
+ /* не критично */
4108
+ });
4109
+ throw err;
4110
+ }
2637
4111
  }
2638
4112
 
2639
4113
  /**
@@ -2645,20 +4119,56 @@ async function collectTasksView() {
2645
4119
 
2646
4120
  // Читаем историю один раз, чтобы определить финальный статус по последней записи.
2647
4121
  const history = await loadHistory();
2648
- const lastByTask = new Map<string, { status: string; error?: string | null }>();
2649
- for (const record of history) {
2650
- lastByTask.set(record.taskName, {
2651
- status: record.status,
2652
- error: record.error,
2653
- });
2654
- }
4122
+ // loadHistory() отдаёт записи от новых к старым; helper оставляет самую свежую.
4123
+ const lastByTask = latestHistoryByTask(history);
2655
4124
 
2656
4125
  // Читаем определения задач один раз (расписание, повторы, цепочки, директория).
2657
4126
  const defs = await loadTaskDefinitions();
2658
4127
  const workspaces = listWorkspaces();
2659
4128
  const workspaceById = new Map(workspaces.map((workspace) => [workspace.id, workspace]));
2660
4129
 
2661
- return tasks.map((t) => {
4130
+ // Счётчики запусков по задачам. Основной источник — таблица metrics
4131
+ // (накопительные итоги, не зависят от retention истории). Для задач, у
4132
+ // которых метрик ещё нет, считаем по загруженной истории.
4133
+ const metricsByName = new Map(
4134
+ getAllMetrics(true).map((row) => [row.taskName.toLowerCase(), row])
4135
+ );
4136
+ const historyCounts = new Map<
4137
+ string,
4138
+ { total: number; success: number; error: number; partial: number }
4139
+ >();
4140
+ for (const record of history) {
4141
+ const key = record.taskName.toLowerCase();
4142
+ const counts = historyCounts.get(key) ?? {
4143
+ total: 0,
4144
+ success: 0,
4145
+ error: 0,
4146
+ partial: 0,
4147
+ };
4148
+ counts.total += 1;
4149
+ if (record.status === "success") counts.success += 1;
4150
+ else if (record.status === "partial") counts.partial += 1;
4151
+ else counts.error += 1;
4152
+ historyCounts.set(key, counts);
4153
+ }
4154
+
4155
+ // ОС-планировщик — источник истины о запуске, но определения в БД могут
4156
+ // существовать без задачи в ОС (сбой удаления, миграция, ручная чистка).
4157
+ // Показываем и их, помечая orphaned: раньше такие задачи были невидимы
4158
+ // для list_tasks, хотя dry_run/история их видели.
4159
+ const osNames = new Set(tasks.map((t) => (t.taskName || "").toLowerCase()));
4160
+ const orphanNames = defs
4161
+ .filter((def) => !osNames.has(def.name.toLowerCase()))
4162
+ .map((def) => def.name);
4163
+ const sources: Array<{ task: (typeof tasks)[number]; orphaned: boolean }> = [
4164
+ ...tasks.map((task) => ({ task, orphaned: false })),
4165
+ ...orphanNames.map((name) => ({
4166
+ task: { taskName: name } as (typeof tasks)[number],
4167
+ orphaned: true,
4168
+ })),
4169
+ ];
4170
+
4171
+ return sources.map(({ task: t, orphaned }) => {
2662
4172
  // Все бэкенды возвращают короткие имена (без папки планировщика).
2663
4173
  const name = t.taskName || "";
2664
4174
 
@@ -2666,11 +4176,13 @@ async function collectTasksView() {
2666
4176
  let status = mapStatus(t.status);
2667
4177
 
2668
4178
  // Приоритет 2: если последняя запись в истории — error/timeout, перебиваем на error.
2669
- const last = lastByTask.get(name);
2670
- if (last && (last.status === "error" || last.status === "timeout")) {
2671
- status = "error";
2672
- } else if (last && last.status === "success") {
2673
- status = "success";
4179
+ const last = lastByTask.get(name.toLowerCase());
4180
+ if (last) {
4181
+ if (last.status === "error" || last.status === "timeout") status = "error";
4182
+ else if (last.status === "success") status = "success";
4183
+ // partial раньше терялся: задача после частичного запуска выглядела
4184
+ // как «готова»/«не запускалась», хотя запуск был неуспешным.
4185
+ else if (last.status === "partial") status = "partial";
2674
4186
  }
2675
4187
 
2676
4188
  const def = defs.find((d) => d.name.toLowerCase() === name.toLowerCase());
@@ -2682,11 +4194,45 @@ async function collectTasksView() {
2682
4194
  status = matrixAggregate.status === "running" ? "running" : matrixAggregate.status;
2683
4195
  }
2684
4196
 
4197
+ // Счётчики именно этой задачи (раньше GUI показывал на каждой карточке
4198
+ // общие итоги по всем задачам — отсюда одинаковые 201/130/71).
4199
+ const metricsRow = metricsByName.get(name.toLowerCase());
4200
+ const counts = metricsRow
4201
+ ? {
4202
+ total: metricsRow.total,
4203
+ success: metricsRow.success,
4204
+ error: metricsRow.error,
4205
+ partial: metricsRow.partial,
4206
+ }
4207
+ : historyCounts.get(name.toLowerCase()) ?? {
4208
+ total: 0,
4209
+ success: 0,
4210
+ error: 0,
4211
+ partial: 0,
4212
+ };
4213
+
2685
4214
  return {
2686
4215
  name,
2687
4216
  schedule: def?.schedule ?? "",
2688
4217
  status,
2689
- nextRun: t.nextRunTime ? String(t.nextRunTime) : null,
4218
+ orphaned,
4219
+ // Спринт 24 (фикс): явный признак паузы. Раньше GUI пытался вывести его
4220
+ // из текстового статуса, но mapStatus() превращает "disabled" в "unknown",
4221
+ // поэтому кнопка «возобновить» была недоступна.
4222
+ paused: Boolean(t.paused),
4223
+ runsTotal: counts.total,
4224
+ runsSuccess: counts.success,
4225
+ runsError: counts.error,
4226
+ runsPartial: counts.partial,
4227
+ // Для разовой задачи показываем запланированное время, а не пустое расписание.
4228
+ nextRun: def?.triggerType === "once"
4229
+ ? def?.runAt ?? (t.nextRunTime ? String(t.nextRunTime) : null)
4230
+ : t.nextRunTime ? String(t.nextRunTime) : null,
4231
+ runAt: def?.runAt ?? null,
4232
+ session: def?.session ?? "new",
4233
+ sessionId: def?.sessionId ?? null,
4234
+ sessionMaxRuns: def?.sessionMaxRuns ?? null,
4235
+ sessionRunCount: def?.sessionRunCount ?? 0,
2690
4236
  model: def?.model ?? null,
2691
4237
  priority: def?.priority ?? 5,
2692
4238
  beforeScript: def?.beforeScript ?? null,
@@ -2700,6 +4246,10 @@ async function collectTasksView() {
2700
4246
  dependsOn: Array.isArray(def?.dependsOn) ? def.dependsOn : [],
2701
4247
  triggerType: def?.triggerType ?? "cron",
2702
4248
  watchPath: def?.watchPath ?? null,
4249
+ timezone: def?.timezone ?? null,
4250
+ notBefore: def?.notBefore ?? null,
4251
+ notAfter: def?.notAfter ?? null,
4252
+ pausedUntil: def?.pausedUntil ?? null,
2703
4253
  workingDirectory: workspace?.path ?? def?.workingDirectory ?? def?.workdir ?? null,
2704
4254
  workspaceId: workspace?.id ?? def?.workspaceId ?? null,
2705
4255
  workspaceName: workspace?.name ?? null,
@@ -2762,7 +4312,10 @@ function mapStatus(status?: string): string {
2762
4312
  if (!status) return "unknown";
2763
4313
  const s = status.toLowerCase();
2764
4314
  if (s.includes("running") || s.includes("выполняется")) return "running";
2765
- if (s.includes("ready") || s.includes("готов")) return "success";
4315
+ // "Ready" в планировщике Windows означает лишь «готова к запуску», а не
4316
+ // успешное выполнение. Раньше такие задачи показывались зелёными, хотя
4317
+ // могли ни разу не запускаться.
4318
+ if (s.includes("ready") || s.includes("готов")) return "idle";
2766
4319
  if (s.includes("disabled")) return "unknown";
2767
4320
  return "unknown";
2768
4321
  }