opencode-windows-scheduler 1.2.0 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/CHANGELOG.md +24 -1
  2. package/README.md +5 -5
  3. package/ROADMAP-STRATEGY.md +2 -2
  4. package/ROADMAP.md +31 -5
  5. package/dist/core/dry-run.d.ts +5 -1
  6. package/dist/core/dry-run.d.ts.map +1 -1
  7. package/dist/core/dry-run.js +20 -4
  8. package/dist/core/one-shot.d.ts +62 -0
  9. package/dist/core/one-shot.d.ts.map +1 -0
  10. package/dist/core/one-shot.js +126 -0
  11. package/dist/core/otel.d.ts +4 -0
  12. package/dist/core/otel.d.ts.map +1 -0
  13. package/dist/core/otel.js +98 -0
  14. package/dist/core/prometheus.d.ts +23 -0
  15. package/dist/core/prometheus.d.ts.map +1 -0
  16. package/dist/core/prometheus.js +146 -0
  17. package/dist/core/ps-wrapper.d.ts +6 -2
  18. package/dist/core/ps-wrapper.d.ts.map +1 -1
  19. package/dist/core/ps-wrapper.js +25 -3
  20. package/dist/core/record-history.d.ts.map +1 -1
  21. package/dist/core/record-history.js +9 -0
  22. package/dist/core/scheduler/linux.d.ts +12 -3
  23. package/dist/core/scheduler/linux.d.ts.map +1 -1
  24. package/dist/core/scheduler/linux.js +80 -3
  25. package/dist/core/scheduler/mac.d.ts.map +1 -1
  26. package/dist/core/scheduler/mac.js +17 -3
  27. package/dist/core/scheduler/posix.d.ts.map +1 -1
  28. package/dist/core/scheduler/posix.js +3 -0
  29. package/dist/core/scheduler/registry.d.ts +4 -0
  30. package/dist/core/scheduler/registry.d.ts.map +1 -1
  31. package/dist/core/scheduler/types.d.ts +5 -3
  32. package/dist/core/scheduler/types.d.ts.map +1 -1
  33. package/dist/core/scheduler/windows.d.ts.map +1 -1
  34. package/dist/core/scheduler/windows.js +10 -1
  35. package/dist/core/session.d.ts +34 -0
  36. package/dist/core/session.d.ts.map +1 -0
  37. package/dist/core/session.js +105 -0
  38. package/dist/core/structured-log.d.ts +84 -0
  39. package/dist/core/structured-log.d.ts.map +1 -0
  40. package/dist/core/structured-log.js +137 -0
  41. package/dist/core/wrappers/bash.d.ts +9 -0
  42. package/dist/core/wrappers/bash.d.ts.map +1 -1
  43. package/dist/core/wrappers/bash.js +27 -3
  44. package/dist/db/history-repo.d.ts.map +1 -1
  45. package/dist/db/history-repo.js +63 -6
  46. package/dist/db/metrics-repo.d.ts +3 -0
  47. package/dist/db/metrics-repo.d.ts.map +1 -1
  48. package/dist/db/metrics-repo.js +16 -8
  49. package/dist/db/migrate.d.ts.map +1 -1
  50. package/dist/db/migrate.js +8 -1
  51. package/dist/db/schema.d.ts +1 -1
  52. package/dist/db/schema.d.ts.map +1 -1
  53. package/dist/db/schema.js +8 -0
  54. package/dist/history.d.ts +7 -0
  55. package/dist/history.d.ts.map +1 -1
  56. package/dist/history.js +13 -0
  57. package/dist/index.d.ts +22 -3
  58. package/dist/index.d.ts.map +1 -1
  59. package/dist/index.js +330 -41
  60. package/dist/integrations.d.ts +64 -0
  61. package/dist/integrations.d.ts.map +1 -0
  62. package/dist/integrations.js +205 -0
  63. package/dist/rpc.d.ts +81 -4
  64. package/dist/rpc.d.ts.map +1 -1
  65. package/dist/rpc.js +43 -4
  66. package/dist/server.d.ts +2 -0
  67. package/dist/server.d.ts.map +1 -1
  68. package/dist/server.js +582 -70
  69. package/dist/settings.d.ts +38 -0
  70. package/dist/settings.d.ts.map +1 -1
  71. package/dist/settings.js +68 -0
  72. package/dist/shared/jobs-view.d.ts +43 -5
  73. package/dist/shared/jobs-view.d.ts.map +1 -1
  74. package/dist/shared/jobs-view.js +125 -7
  75. package/dist/task-transfer.d.ts +19 -3
  76. package/dist/task-transfer.d.ts.map +1 -1
  77. package/dist/task-transfer.js +75 -3
  78. package/docs/FEATURES.md +101 -4
  79. package/gui-experimental.cjs +4 -4
  80. package/package.json +11 -2
  81. package/scripts/demo-dashboard.mjs +12 -2
  82. package/src/core/dry-run.ts +24 -5
  83. package/src/core/one-shot.ts +173 -0
  84. package/src/core/otel.ts +128 -0
  85. package/src/core/prometheus.ts +215 -0
  86. package/src/core/ps-wrapper.ts +29 -3
  87. package/src/core/record-history.ts +13 -0
  88. package/src/core/scheduler/linux.ts +90 -3
  89. package/src/core/scheduler/mac.ts +35 -4
  90. package/src/core/scheduler/posix.ts +3 -0
  91. package/src/core/scheduler/registry.ts +4 -0
  92. package/src/core/scheduler/types.ts +5 -3
  93. package/src/core/scheduler/windows.ts +11 -1
  94. package/src/core/session.ts +115 -0
  95. package/src/core/structured-log.ts +205 -0
  96. package/src/core/wrappers/bash.ts +38 -2
  97. package/src/db/history-repo.ts +67 -7
  98. package/src/db/metrics-repo.ts +19 -7
  99. package/src/db/migrate.ts +7 -1
  100. package/src/db/schema.ts +11 -0
  101. package/src/gui.tsx +237 -18
  102. package/src/history.ts +17 -0
  103. package/src/index.ts +426 -47
  104. package/src/integrations.ts +253 -0
  105. package/src/rpc.ts +43 -4
  106. package/src/server.ts +622 -69
  107. package/src/settings.ts +122 -0
  108. package/src/shared/jobs-view.ts +158 -8
  109. package/src/task-transfer.ts +107 -5
  110. package/src/tui.tsx +290 -14
package/dist/index.js CHANGED
@@ -7,6 +7,8 @@ import path from "node:path";
7
7
  import { LockManager } from "./core/lock.js";
8
8
  import { LOCK_DIR, LOG_DIR, PLUGIN_DIR, sanitizeName } from "./types.js";
9
9
  import { parseCron, buildScheduleGate, isValidIanaTimeZone, validateLaunchWindow, prevRun } from "./core/schedule-v2.js";
10
+ import { buildLaunchdOneShotCleanup, normalizeOneShotRunAt, } from "./core/one-shot.js";
11
+ import { generateSessionId, normalizeSessionMode, preservedSessionRunCount, } from "./core/session.js";
10
12
  import { ensureWrapper, writePromptFile, writeWrapperCmd, lockFilePath, requestImmediateRun } from "./core/ps-wrapper.js";
11
13
  import { getSchedulerBackend } from "./core/scheduler/index.js";
12
14
  import { SCHEDULER_SKILL_ID, loadSchedulerSkill } from "./skill.js";
@@ -15,7 +17,7 @@ import { writeBashWrapper } from "./core/wrappers/bash.js";
15
17
  import { simulatePipeline } from "./core/dry-run.js";
16
18
  import { aggregateMatrixResults, cancelPendingMatrixClones, expandMatrixTask, findOrphanedMatrixTasks, getMatrixDeletionGuard, matrixCompleteName, planMatrixFamilyDelete, removeMatrixChildren, runMatrix, syncMatrixFamily, } from "./core/matrix.js";
17
19
  import { SchedulerRpc } from "./rpc.js";
18
- import { loadHistory, loadMetrics } from "./history.js";
20
+ import { latestHistoryByTask, loadHistory, loadMetrics } from "./history.js";
19
21
  import { loadSettings, saveSettings } from "./settings.js";
20
22
  import { runHistoryRetention, maybeRunHistoryRetention } from "./core/retention.js";
21
23
  import { buildAnalytics } from "./core/analytics.js";
@@ -114,7 +116,29 @@ export const scheduleTaskSchema = z.object({
114
116
  name: z.string().describe("Unique task name (the plugin prefix is applied automatically)."),
115
117
  schedule: z
116
118
  .string()
117
- .describe("Cron expression (5 fields: minute hour day-of-month month day-of-week). Supports ranges, lists, */N steps, month/weekday names, @every 15m|2h|1d, L (last day of month) and FRI#3 (third Friday). Expressions schtasks cannot express are checked every minute inside the wrapper."),
119
+ .optional()
120
+ .describe("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."),
121
+ runAt: z
122
+ .string()
123
+ .optional()
124
+ .describe("Absolute one-shot start time in ISO-8601 (e.g. 2026-12-01T09:00:00Z). Requires triggerType=once; mutually exclusive with delaySeconds (runAt wins)."),
125
+ delaySeconds: z
126
+ .number()
127
+ .int()
128
+ .positive()
129
+ .optional()
130
+ .describe("One-shot delay in seconds from now. Requires triggerType=once. Convenient alternative to runAt."),
131
+ session: z
132
+ .enum(["new", "reuse", "last"])
133
+ .optional()
134
+ .describe("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)."),
135
+ sessionMaxRuns: z
136
+ .number()
137
+ .int()
138
+ .min(1)
139
+ .max(10000)
140
+ .optional()
141
+ .describe("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."),
118
142
  timezone: z
119
143
  .string()
120
144
  .optional()
@@ -175,9 +199,9 @@ export const scheduleTaskSchema = z.object({
175
199
  .optional()
176
200
  .describe("Compensation/rollback task started after a failed run."),
177
201
  triggerType: z
178
- .enum(["cron", "file", "mcp-event"])
202
+ .enum(["cron", "file", "mcp-event", "once"])
179
203
  .optional()
180
- .describe("Trigger type: cron (default), file or mcp-event."),
204
+ .describe("Trigger type: cron (default), file, mcp-event or once (single run at runAt/delaySeconds)."),
181
205
  mcpEvent: z
182
206
  .object({
183
207
  server: z.string(),
@@ -209,6 +233,38 @@ export const scheduleTaskSchema = z.object({
209
233
  matrix: matrixSchema
210
234
  .optional()
211
235
  .describe("Matrix fan-out: the task becomes a template that is expanded into clones, one per workspace. The parent never runs itself. Cannot be combined with workspaceId."),
236
+ }).superRefine((value, ctx) => {
237
+ const trigger = value.triggerType ?? "cron";
238
+ if (trigger === "cron" && !value.schedule?.trim()) {
239
+ ctx.addIssue({
240
+ code: z.ZodIssueCode.custom,
241
+ path: ["schedule"],
242
+ message: "Для triggerType=cron нужно cron-выражение schedule.",
243
+ });
244
+ }
245
+ if (trigger === "once" &&
246
+ !value.runAt &&
247
+ value.delaySeconds === undefined) {
248
+ ctx.addIssue({
249
+ code: z.ZodIssueCode.custom,
250
+ path: ["runAt"],
251
+ message: "Для triggerType=once нужен runAt (ISO-8601) или delaySeconds.",
252
+ });
253
+ }
254
+ if (trigger === "once" && value.matrix) {
255
+ ctx.addIssue({
256
+ code: z.ZodIssueCode.custom,
257
+ path: ["matrix"],
258
+ message: "One-shot нельзя комбинировать с matrix: матрица запускается только вручную.",
259
+ });
260
+ }
261
+ if (trigger !== "once" && (value.runAt || value.delaySeconds !== undefined)) {
262
+ ctx.addIssue({
263
+ code: z.ZodIssueCode.custom,
264
+ path: ["runAt"],
265
+ message: "runAt/delaySeconds допустимы только при triggerType=once.",
266
+ });
267
+ }
212
268
  });
213
269
  const listTasksSchema = z.object({});
214
270
  const deleteTaskSchema = z.object({
@@ -223,6 +279,27 @@ export const updateTaskSchema = z.object({
223
279
  .string()
224
280
  .optional()
225
281
  .describe("New cron expression. Keeps the current value when omitted."),
282
+ runAt: z
283
+ .string()
284
+ .optional()
285
+ .describe("New one-shot time in ISO-8601. Requires triggerType=once. Empty string clears it."),
286
+ delaySeconds: z
287
+ .number()
288
+ .int()
289
+ .positive()
290
+ .optional()
291
+ .describe("New one-shot delay in seconds from now. Requires triggerType=once."),
292
+ session: z
293
+ .enum(["new", "reuse", "last"])
294
+ .optional()
295
+ .describe("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)."),
296
+ sessionMaxRuns: z
297
+ .number()
298
+ .int()
299
+ .min(1)
300
+ .max(10000)
301
+ .optional()
302
+ .describe("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."),
226
303
  timezone: z
227
304
  .string()
228
305
  .optional()
@@ -272,7 +349,7 @@ export const updateTaskSchema = z.object({
272
349
  .optional()
273
350
  .describe("New error-chain task. Empty string clears it."),
274
351
  triggerType: z
275
- .enum(["cron", "file", "mcp-event"])
352
+ .enum(["cron", "file", "mcp-event", "once"])
276
353
  .optional()
277
354
  .describe("New trigger type."),
278
355
  mcpEvent: z
@@ -307,6 +384,23 @@ export const updateTaskSchema = z.object({
307
384
  .nullable()
308
385
  .optional()
309
386
  .describe("New matrix configuration. Pass null to turn the matrix off (clones and aggregator are removed)."),
387
+ }).superRefine((value, ctx) => {
388
+ if (value.triggerType !== undefined &&
389
+ value.triggerType !== "once" &&
390
+ (value.runAt || value.delaySeconds !== undefined)) {
391
+ ctx.addIssue({
392
+ code: z.ZodIssueCode.custom,
393
+ path: ["runAt"],
394
+ message: "runAt/delaySeconds допустимы только при triggerType=once.",
395
+ });
396
+ }
397
+ if (value.triggerType === "once" && value.matrix) {
398
+ ctx.addIssue({
399
+ code: z.ZodIssueCode.custom,
400
+ path: ["matrix"],
401
+ message: "One-shot нельзя комбинировать с matrix.",
402
+ });
403
+ }
310
404
  });
311
405
  const pauseTaskSchema = z.object({
312
406
  name: z.string().describe("Task name to pause."),
@@ -435,6 +529,10 @@ export const manageSettingsSchema = z.object({
435
529
  })
436
530
  .optional()
437
531
  .describe("History retention policy."),
532
+ integrations: z
533
+ .any()
534
+ .optional()
535
+ .describe("Integration settings patch (hooks: enabled, token, secret, requireSignature, maxBodyBytes, timestampToleranceSeconds)."),
438
536
  });
439
537
  /** manage_templates — пользовательские шаблоны задач. */
440
538
  export const manageTemplatesSchema = z.object({
@@ -527,9 +625,23 @@ function wrapExecute(fn) {
527
625
  }
528
626
  /** schedule_task — создаёт задачу в schtasks через общий schedulerCreateTask. */
529
627
  const scheduleTaskExecute = wrapExecute(async (args) => {
530
- const { name, schedule, prompt, timeoutSeconds, model, priority, beforeScript, afterScript, qualityGate, dependsOn, retryCount, retryDelay, nextTaskOnSuccess, nextTaskOnError, triggerType, mcpEvent, watchPath, workingDirectory, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, } = args;
628
+ const { name, schedule, runAt, delaySeconds, prompt, timeoutSeconds, model, priority, beforeScript, afterScript, qualityGate, dependsOn, retryCount, retryDelay, nextTaskOnSuccess, nextTaskOnError, triggerType, mcpEvent, watchPath, workingDirectory, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, session, sessionMaxRuns, } = args;
629
+ let effectiveRunAt;
630
+ if ((triggerType ?? "cron") === "once") {
631
+ const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
632
+ if (!normalized.ok) {
633
+ return {
634
+ content: JSON.stringify({ success: false, error: normalized.error }),
635
+ };
636
+ }
637
+ effectiveRunAt = normalized.runAt;
638
+ }
639
+ // Спринт 24: режим сессии. По умолчанию "new" (старое поведение).
640
+ // sessionId пользователя никогда не принимаем — он создаётся автоматически.
641
+ const effectiveSession = normalizeSessionMode(session) ?? "new";
642
+ const effectiveSessionId = effectiveSession === "reuse" ? generateSessionId() : undefined;
531
643
  try {
532
- await schedulerCreateTask(name, schedule, prompt, timeoutSeconds, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, undefined, "create", timezone, notBefore, notAfter);
644
+ await schedulerCreateTask(name, schedule ?? "", prompt, timeoutSeconds, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, undefined, "create", timezone, notBefore, notAfter, undefined, effectiveRunAt, effectiveSession, effectiveSessionId, sessionMaxRuns);
533
645
  }
534
646
  catch (err) {
535
647
  return {
@@ -563,6 +675,10 @@ const scheduleTaskExecute = wrapExecute(async (args) => {
563
675
  nextTaskOnSuccess: nextTaskOnSuccess?.trim() || null,
564
676
  nextTaskOnError: nextTaskOnError?.trim() || null,
565
677
  triggerType: triggerType ?? "cron",
678
+ runAt: effectiveRunAt ?? null,
679
+ session: effectiveSession,
680
+ sessionId: effectiveSessionId ?? null,
681
+ sessionMaxRuns: sessionMaxRuns ?? null,
566
682
  timezone: timezone?.trim() || null,
567
683
  notBefore: notBefore?.trim() || null,
568
684
  notAfter: notAfter?.trim() || null,
@@ -850,15 +966,74 @@ async function updateTaskFromInput(input) {
850
966
  message: `Для обновления задачи "${name}" нужен промпт.`,
851
967
  };
852
968
  }
969
+ // One-shot: без нового runAt/delaySeconds сохраняем прежнее время.
970
+ // При смене триггера на once время обязательно, иначе задача не запустится.
971
+ let runAt;
972
+ if (triggerType === "once") {
973
+ const candidateRunAt = input.runAt !== undefined
974
+ ? input.runAt
975
+ : input.delaySeconds !== undefined
976
+ ? undefined
977
+ : previous.runAt;
978
+ const normalized = normalizeOneShotRunAt({
979
+ runAt: candidateRunAt,
980
+ delaySeconds: input.delaySeconds,
981
+ });
982
+ if (!normalized.ok) {
983
+ return {
984
+ success: false,
985
+ message: `Задача "${name}": ${normalized.error}`,
986
+ };
987
+ }
988
+ runAt = normalized.runAt;
989
+ }
990
+ // Спринт 24: режим сессии. Без новых session/sessionMaxRuns сохраняем прежние.
991
+ // sessionId пользователя не принимаем — генерируем сами при переходе на reuse.
992
+ let session = "new";
993
+ if (input.session !== undefined) {
994
+ const normalizedSession = normalizeSessionMode(input.session);
995
+ if (!normalizedSession) {
996
+ return {
997
+ success: false,
998
+ message: `Задача "${name}": неизвестный режим сессии "${String(input.session)}".`,
999
+ };
1000
+ }
1001
+ session = normalizedSession;
1002
+ }
1003
+ else if (previous.session) {
1004
+ session = previous.session;
1005
+ }
1006
+ const sessionMaxRuns = input.sessionMaxRuns !== undefined ? input.sessionMaxRuns : previous.sessionMaxRuns;
1007
+ if (sessionMaxRuns !== undefined &&
1008
+ (!Number.isInteger(sessionMaxRuns) || sessionMaxRuns < 1)) {
1009
+ return {
1010
+ success: false,
1011
+ message: `Задача "${name}": sessionMaxRuns должен быть целым числом ≥ 1.`,
1012
+ };
1013
+ }
1014
+ let sessionId = previous.sessionId;
1015
+ if (session === "reuse" && !sessionId) {
1016
+ sessionId = generateSessionId();
1017
+ }
1018
+ if (session !== "reuse") {
1019
+ sessionId = undefined;
1020
+ }
853
1021
  const matrixWas = previous.matrix;
854
1022
  const matrixNext = input.matrix === undefined ? matrixWas : input.matrix ?? undefined;
1023
+ if (triggerType === "once" && matrixNext) {
1024
+ return {
1025
+ success: false,
1026
+ message: `Задача "${name}": one-shot нельзя комбинировать с matrix. ` +
1027
+ `Запустите матрицу вручную или используйте cron/file-триггер.`,
1028
+ };
1029
+ }
855
1030
  try {
856
1031
  // Обновление = пересоздание в планировщике с сохранением старых значений.
857
1032
  await scheduler.deleteTask(name);
858
- await schedulerCreateTask(name, schedule ?? "* * * * *", prompt, input.timeoutSeconds ?? previous.timeoutSeconds, clearableString(input.workingDirectory, previous.workingDirectory), input.retryCount ?? previous.retryCount, input.retryDelay ?? previous.retryDelay, clearableString(input.qualityGate, previous.qualityGate), clearableString(input.nextTaskOnSuccess, previous.nextTaskOnSuccess), clearableString(input.nextTaskOnError, previous.nextTaskOnError), triggerType, clearableString(input.watchPath, previous.watchPath), clearableList(input.dependsOn, previous.dependsOn), clearableString(input.model, previous.model), input.priority ?? previous.priority, clearableString(input.beforeScript, previous.beforeScript), clearableString(input.afterScript, previous.afterScript), input.mcpEvent ?? previous.mcpEvent, clearableString(input.workspaceId, previous.workspaceId), clearableList(input.allowedTools, previous.allowedTools), clearableList(input.deniedTools, previous.deniedTools), matrixNext, undefined,
1033
+ await schedulerCreateTask(name, schedule ?? "", prompt, input.timeoutSeconds ?? previous.timeoutSeconds, clearableString(input.workingDirectory, previous.workingDirectory), input.retryCount ?? previous.retryCount, input.retryDelay ?? previous.retryDelay, clearableString(input.qualityGate, previous.qualityGate), clearableString(input.nextTaskOnSuccess, previous.nextTaskOnSuccess), clearableString(input.nextTaskOnError, previous.nextTaskOnError), triggerType, clearableString(input.watchPath, previous.watchPath), clearableList(input.dependsOn, previous.dependsOn), clearableString(input.model, previous.model), input.priority ?? previous.priority, clearableString(input.beforeScript, previous.beforeScript), clearableString(input.afterScript, previous.afterScript), input.mcpEvent ?? previous.mcpEvent, clearableString(input.workspaceId, previous.workspaceId), clearableList(input.allowedTools, previous.allowedTools), clearableList(input.deniedTools, previous.deniedTools), matrixNext, undefined,
859
1034
  // Если задача была матрицей — синхронизируем клонов, а не
860
1035
  // пересоздаём их с нуля (Спринт 17).
861
- matrixWas && matrixNext ? "sync" : "create", timezone, notBefore, notAfter, previous.pausedUntil);
1036
+ matrixWas && matrixNext ? "sync" : "create", timezone, notBefore, notAfter, previous.pausedUntil, runAt, session, sessionId, sessionMaxRuns);
862
1037
  // Матрица отключена при обновлении — убираем клонов и агрегатор.
863
1038
  if (matrixWas && !matrixNext) {
864
1039
  await removeMatrixChildrenFromScheduler(name);
@@ -1365,11 +1540,12 @@ const manageSettingsExecute = wrapExecute(async (args) => {
1365
1540
  if (args.maxConcurrent === undefined &&
1366
1541
  args.winterMode === undefined &&
1367
1542
  args.notifications === undefined &&
1368
- args.history === undefined) {
1543
+ args.history === undefined &&
1544
+ args.integrations === undefined) {
1369
1545
  return {
1370
1546
  content: JSON.stringify({
1371
1547
  success: false,
1372
- error: "Для action=update передайте хотя бы одно поле: maxConcurrent, winterMode, notifications или history.",
1548
+ error: "Для action=update передайте хотя бы одно поле: maxConcurrent, winterMode, notifications, history или integrations.",
1373
1549
  settings: current,
1374
1550
  }),
1375
1551
  };
@@ -1379,6 +1555,7 @@ const manageSettingsExecute = wrapExecute(async (args) => {
1379
1555
  winterMode: args.winterMode,
1380
1556
  notifications: args.notifications,
1381
1557
  history: args.history,
1558
+ integrations: args.integrations,
1382
1559
  });
1383
1560
  return { content: JSON.stringify({ success: true, settings }) };
1384
1561
  });
@@ -1500,7 +1677,7 @@ const transferTasksExecute = wrapExecute(async (args) => {
1500
1677
  const errors = [...parsed.errors];
1501
1678
  for (const def of parsed.tasks) {
1502
1679
  try {
1503
- await schedulerCreateTask(def.name, def.schedule, def.prompt, def.timeoutSeconds, def.workingDirectory ?? def.workdir, def.retryCount, def.retryDelay, def.qualityGate, def.nextTaskOnSuccess, def.nextTaskOnError, def.triggerType, def.watchPath, def.dependsOn, def.model, def.priority, def.beforeScript, def.afterScript, def.mcpEvent, def.workspaceId, def.allowedTools, def.deniedTools, def.matrix, def.matrixParentId, "create", def.timezone, def.notBefore, def.notAfter, def.pausedUntil);
1680
+ await schedulerCreateTask(def.name, def.schedule, def.prompt, def.timeoutSeconds, def.workingDirectory ?? def.workdir, def.retryCount, def.retryDelay, def.qualityGate, def.nextTaskOnSuccess, def.nextTaskOnError, def.triggerType, def.watchPath, def.dependsOn, def.model, def.priority, def.beforeScript, def.afterScript, def.mcpEvent, def.workspaceId, def.allowedTools, def.deniedTools, def.matrix, def.matrixParentId, "create", def.timezone, def.notBefore, def.notAfter, def.pausedUntil, def.runAt);
1504
1681
  await saveTaskDefinition(def);
1505
1682
  imported.push(def.name);
1506
1683
  }
@@ -1915,9 +2092,30 @@ export default Plugin.define({
1915
2092
  },
1916
2093
  create_task: async (input) => {
1917
2094
  console.log("[windows-scheduler] create_task input:", input);
1918
- const { name, schedule, prompt, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, dependsOn, triggerType, watchPath, workingDirectory, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, } = input;
2095
+ const { name, schedule, prompt, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, dependsOn, triggerType, watchPath, workingDirectory, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, timezone, notBefore, notAfter, runAt, delaySeconds, session, sessionMaxRuns, } = input;
2096
+ let effectiveRunAt;
2097
+ if (triggerType === "once") {
2098
+ const normalized = normalizeOneShotRunAt({ runAt, delaySeconds });
2099
+ if (!normalized.ok) {
2100
+ return { success: false, message: `Задача "${name}": ${normalized.error}` };
2101
+ }
2102
+ effectiveRunAt = normalized.runAt;
2103
+ }
2104
+ let effectiveSession = "new";
2105
+ if (session !== undefined) {
2106
+ const normalizedSession = normalizeSessionMode(session);
2107
+ if (!normalizedSession) {
2108
+ return { success: false, message: `Задача "${name}": неизвестный режим сессии "${String(session)}".` };
2109
+ }
2110
+ effectiveSession = normalizedSession;
2111
+ }
2112
+ if (sessionMaxRuns !== undefined &&
2113
+ (!Number.isInteger(sessionMaxRuns) || sessionMaxRuns < 1)) {
2114
+ return { success: false, message: `Задача "${name}": sessionMaxRuns должен быть целым числом ≥ 1.` };
2115
+ }
2116
+ const effectiveSessionId = effectiveSession === "reuse" ? generateSessionId() : undefined;
1919
2117
  try {
1920
- await schedulerCreateTask(name, schedule, prompt, undefined, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, undefined, "create", timezone, notBefore, notAfter);
2118
+ await schedulerCreateTask(name, schedule ?? "", prompt, undefined, workingDirectory, retryCount, retryDelay, qualityGate, nextTaskOnSuccess, nextTaskOnError, triggerType, watchPath, dependsOn, model, priority, beforeScript, afterScript, mcpEvent, workspaceId, allowedTools, deniedTools, matrix, undefined, "create", timezone, notBefore, notAfter, undefined, effectiveRunAt, effectiveSession, effectiveSessionId, sessionMaxRuns);
1921
2119
  return { success: true, message: `Задача "${name}" успешно создана.` };
1922
2120
  }
1923
2121
  catch (err) {
@@ -2068,10 +2266,16 @@ export default Plugin.define({
2068
2266
  return { success: true, logs: result.logs };
2069
2267
  },
2070
2268
  get_history: async (input) => {
2071
- const { limit, taskName } = input;
2269
+ // Контракт совпадает с агентским инструментом get_history:
2270
+ // limit по умолчанию 20 (максимум 200), фильтры taskName и status.
2271
+ const { limit, taskName, status } = input;
2072
2272
  const filter = taskName?.trim().toLowerCase();
2073
- const records = (await loadHistory()).filter((record) => !filter || record.taskName.toLowerCase() === filter);
2074
- return { records: records.slice(0, limit ?? 10) };
2273
+ const statusFilter = status?.trim().toLowerCase();
2274
+ const max = Math.max(1, Math.min(Math.floor(limit ?? 20), 200));
2275
+ const records = (await loadHistory())
2276
+ .filter((record) => !filter || record.taskName.toLowerCase() === filter)
2277
+ .filter((record) => !statusFilter || String(record.status).toLowerCase() === statusFilter);
2278
+ return { records: records.slice(0, max) };
2075
2279
  },
2076
2280
  get_metrics: async () => {
2077
2281
  return await loadMetrics();
@@ -2365,18 +2569,20 @@ export default Plugin.define({
2365
2569
  return await loadSettings();
2366
2570
  },
2367
2571
  save_settings: async (input) => {
2368
- const { maxConcurrent, winterMode, notifications, history } = input;
2572
+ const { maxConcurrent, winterMode, notifications, history, integrations } = input;
2369
2573
  const current = await loadSettings();
2370
2574
  if (maxConcurrent === undefined &&
2371
2575
  winterMode === undefined &&
2372
2576
  notifications === undefined &&
2373
- history === undefined) {
2577
+ history === undefined &&
2578
+ integrations === undefined) {
2374
2579
  return {
2375
2580
  success: false,
2376
2581
  maxConcurrent: current.maxConcurrent,
2377
2582
  winterMode: current.winterMode,
2378
2583
  notifications: current.notifications,
2379
2584
  history: current.history,
2585
+ integrations: current.integrations,
2380
2586
  };
2381
2587
  }
2382
2588
  const settings = await saveSettings({
@@ -2384,6 +2590,7 @@ export default Plugin.define({
2384
2590
  winterMode,
2385
2591
  notifications,
2386
2592
  history,
2593
+ integrations,
2387
2594
  });
2388
2595
  return {
2389
2596
  success: true,
@@ -2391,6 +2598,7 @@ export default Plugin.define({
2391
2598
  winterMode: settings.winterMode,
2392
2599
  notifications: settings.notifications,
2393
2600
  history: settings.history,
2601
+ integrations: settings.integrations,
2394
2602
  };
2395
2603
  },
2396
2604
  test_notification: async () => {
@@ -2487,7 +2695,7 @@ export default Plugin.define({
2487
2695
  const errors = [...parsed.errors];
2488
2696
  for (const def of parsed.tasks) {
2489
2697
  try {
2490
- await schedulerCreateTask(def.name, def.schedule, def.prompt, def.timeoutSeconds, def.workingDirectory ?? def.workdir, def.retryCount, def.retryDelay, def.qualityGate, def.nextTaskOnSuccess, def.nextTaskOnError, def.triggerType, def.watchPath, def.dependsOn, def.model, def.priority, def.beforeScript, def.afterScript, def.mcpEvent, def.workspaceId, def.allowedTools, def.deniedTools, def.matrix, def.matrixParentId, "create", def.timezone, def.notBefore, def.notAfter, def.pausedUntil);
2698
+ await schedulerCreateTask(def.name, def.schedule, def.prompt, def.timeoutSeconds, def.workingDirectory ?? def.workdir, def.retryCount, def.retryDelay, def.qualityGate, def.nextTaskOnSuccess, def.nextTaskOnError, def.triggerType, def.watchPath, def.dependsOn, def.model, def.priority, def.beforeScript, def.afterScript, def.mcpEvent, def.workspaceId, def.allowedTools, def.deniedTools, def.matrix, def.matrixParentId, "create", def.timezone, def.notBefore, def.notAfter, def.pausedUntil, def.runAt);
2491
2699
  await saveTaskDefinition(def);
2492
2700
  imported.push(def.name);
2493
2701
  }
@@ -2599,7 +2807,15 @@ notBefore,
2599
2807
  /** Окончание окна "HH:MM"; может быть меньше notBefore (через полночь). */
2600
2808
  notAfter,
2601
2809
  /** Пауза до момента ISO; после него задача возобновляется автоматически. */
2602
- pausedUntil) {
2810
+ pausedUntil,
2811
+ /** Абсолютное время однократного запуска (ISO, только triggerType=once). */
2812
+ runAt,
2813
+ /** Режим сессии OpenCode (Спринт 24): new (по умолчанию), reuse, last. */
2814
+ session,
2815
+ /** ID сессии для reuse (генерируется автоматически; пользователь не задаёт). */
2816
+ sessionId,
2817
+ /** Сколько запусков переживает reuse-сессия до ротации (0/undefined — без ограничения). */
2818
+ sessionMaxRuns) {
2603
2819
  const normalizedModel = model?.trim() || undefined;
2604
2820
  const normalizedPriority = normalizePriority(priority);
2605
2821
  const normalizedBefore = beforeScript?.trim() || undefined;
@@ -2616,6 +2832,30 @@ pausedUntil) {
2616
2832
  }
2617
2833
  : undefined;
2618
2834
  let effectiveTriggerType = triggerType ?? "cron";
2835
+ // One-shot: нормализуем время до создания файлов и задачи в ОС.
2836
+ // Для остальных триггеров runAt не имеет смысла и отбрасывается.
2837
+ let effectiveRunAt;
2838
+ if (effectiveTriggerType === "once") {
2839
+ const normalized = normalizeOneShotRunAt({ runAt });
2840
+ if (!normalized.ok) {
2841
+ throw new Error(`Задача "${name}": ${normalized.error}`);
2842
+ }
2843
+ effectiveRunAt = normalized.runAt;
2844
+ }
2845
+ // Спринт 24: режим сессии. sessionId генерируется автоматически для reuse;
2846
+ // значение пользователя никогда не принимаем.
2847
+ let effectiveSession = "new";
2848
+ let effectiveSessionId;
2849
+ if (session !== undefined) {
2850
+ const normalizedSession = normalizeSessionMode(session);
2851
+ if (!normalizedSession) {
2852
+ throw new Error(`Задача "${name}": неизвестный режим сессии "${String(session)}".`);
2853
+ }
2854
+ effectiveSession = normalizedSession;
2855
+ }
2856
+ if (effectiveSession === "reuse") {
2857
+ effectiveSessionId = sessionId?.trim() || generateSessionId();
2858
+ }
2619
2859
  // Role-scoped: нормализуем списки инструментов (trim, дедуп без регистра).
2620
2860
  // Пустой allowedTools — осознанная блокировка: «белый список из нуля
2621
2861
  // инструментов» это почти наверняка ошибка конфигурации.
@@ -2756,7 +2996,7 @@ pausedUntil) {
2756
2996
  try {
2757
2997
  if (scheduler.platform === "win32") {
2758
2998
  await ensureWrapper();
2759
- wrapperPath = await writeWrapperCmd(sanitized, name, promptFile, timeoutSeconds ?? 3600, lockFile, effectiveWorkingDirectory, logFile, recorderPath, qualityGate, normalizedModel, normalizedBefore, normalizedAfter, workspace?.name, normalizedAllowedTools, normalizedDeniedTools, wrapperGate, taskEnvFile);
2999
+ wrapperPath = await writeWrapperCmd(sanitized, name, promptFile, timeoutSeconds ?? 3600, lockFile, effectiveWorkingDirectory, logFile, recorderPath, qualityGate, normalizedModel, normalizedBefore, normalizedAfter, workspace?.name, normalizedAllowedTools, normalizedDeniedTools, wrapperGate, taskEnvFile, effectiveSession, effectiveSessionId);
2760
3000
  }
2761
3001
  else {
2762
3002
  wrapperPath = await writeBashWrapper({
@@ -2777,6 +3017,11 @@ pausedUntil) {
2777
3017
  deniedTools: normalizedDeniedTools,
2778
3018
  scheduleGate: wrapperGate,
2779
3019
  envFile: taskEnvFile,
3020
+ sessionMode: effectiveSession,
3021
+ sessionId: effectiveSessionId,
3022
+ ...(effectiveTriggerType === "once" && scheduler.platform === "darwin"
3023
+ ? { oneShotCleanupCommand: buildLaunchdOneShotCleanup(sanitized) }
3024
+ : {}),
2780
3025
  });
2781
3026
  }
2782
3027
  }
@@ -2791,6 +3036,7 @@ pausedUntil) {
2791
3036
  schedule,
2792
3037
  timeoutSeconds: timeoutSeconds ?? 3600,
2793
3038
  triggerType: effectiveTriggerType,
3039
+ ...(effectiveRunAt ? { runAt: effectiveRunAt } : {}),
2794
3040
  workingDirectory: effectiveWorkingDirectory,
2795
3041
  logFile,
2796
3042
  model: normalizedModel,
@@ -2804,7 +3050,9 @@ pausedUntil) {
2804
3050
  throw new Error(err instanceof Error ? err.message : String(err));
2805
3051
  }
2806
3052
  // Сохраняем определение задачи для последующего экспорта/импорта.
2807
- const existingQueue = matrixMode === "sync" ? getTask(name)?.matrixQueue : undefined;
3053
+ // Определение до перезаписи: нужно и для очереди матрицы, и для счётчика сессии.
3054
+ const previousDefinition = getTask(name);
3055
+ const existingQueue = matrixMode === "sync" ? previousDefinition?.matrixQueue : undefined;
2808
3056
  const taskDefinition = {
2809
3057
  name,
2810
3058
  schedule,
@@ -2823,6 +3071,15 @@ pausedUntil) {
2823
3071
  nextTaskOnSuccess,
2824
3072
  nextTaskOnError,
2825
3073
  triggerType: effectiveTriggerType,
3074
+ runAt: effectiveRunAt,
3075
+ // Спринт 24: сессия. sessionRunCount не экспортируется (internal).
3076
+ session: effectiveSession,
3077
+ sessionId: effectiveSessionId,
3078
+ sessionMaxRuns,
3079
+ // Раньше редактирование всегда сбрасывало счётчик в 0, из-за чего лимит
3080
+ // sessionMaxRuns обходился правкой любого поля задачи. Сохраняем счётчик,
3081
+ // только если сессия и её id не изменились.
3082
+ sessionRunCount: preservedSessionRunCount(previousDefinition, effectiveSession, effectiveSessionId),
2826
3083
  watchPath: normalizedMatrix ? undefined : watchPath,
2827
3084
  timezone: normalizedTz,
2828
3085
  notBefore: normalizedNotBefore,
@@ -2952,13 +3209,8 @@ async function collectTasksView() {
2952
3209
  const tasks = await scheduler.listTasks();
2953
3210
  // Читаем историю один раз, чтобы определить финальный статус по последней записи.
2954
3211
  const history = await loadHistory();
2955
- const lastByTask = new Map();
2956
- for (const record of history) {
2957
- lastByTask.set(record.taskName, {
2958
- status: record.status,
2959
- error: record.error,
2960
- });
2961
- }
3212
+ // loadHistory() отдаёт записи от новых к старым; helper оставляет самую свежую.
3213
+ const lastByTask = latestHistoryByTask(history);
2962
3214
  // Читаем определения задач один раз (расписание, повторы, цепочки, директория).
2963
3215
  const defs = await loadTaskDefinitions();
2964
3216
  const workspaces = listWorkspaces();
@@ -2970,10 +3222,17 @@ async function collectTasksView() {
2970
3222
  const historyCounts = new Map();
2971
3223
  for (const record of history) {
2972
3224
  const key = record.taskName.toLowerCase();
2973
- const counts = historyCounts.get(key) ?? { total: 0, success: 0, error: 0 };
3225
+ const counts = historyCounts.get(key) ?? {
3226
+ total: 0,
3227
+ success: 0,
3228
+ error: 0,
3229
+ partial: 0,
3230
+ };
2974
3231
  counts.total += 1;
2975
3232
  if (record.status === "success")
2976
3233
  counts.success += 1;
3234
+ else if (record.status === "partial")
3235
+ counts.partial += 1;
2977
3236
  else
2978
3237
  counts.error += 1;
2979
3238
  historyCounts.set(key, counts);
@@ -2999,12 +3258,16 @@ async function collectTasksView() {
2999
3258
  // Приоритет 1: статус, который сообщает планировщик ОС.
3000
3259
  let status = mapStatus(t.status);
3001
3260
  // Приоритет 2: если последняя запись в истории — error/timeout, перебиваем на error.
3002
- const last = lastByTask.get(name);
3003
- if (last && (last.status === "error" || last.status === "timeout")) {
3004
- status = "error";
3005
- }
3006
- else if (last && last.status === "success") {
3007
- status = "success";
3261
+ const last = lastByTask.get(name.toLowerCase());
3262
+ if (last) {
3263
+ if (last.status === "error" || last.status === "timeout")
3264
+ status = "error";
3265
+ else if (last.status === "success")
3266
+ status = "success";
3267
+ // partial раньше терялся: задача после частичного запуска выглядела
3268
+ // как «готова»/«не запускалась», хотя запуск был неуспешным.
3269
+ else if (last.status === "partial")
3270
+ status = "partial";
3008
3271
  }
3009
3272
  const def = defs.find((d) => d.name.toLowerCase() === name.toLowerCase());
3010
3273
  const workspace = def?.workspaceId ? workspaceById.get(def.workspaceId) : undefined;
@@ -3017,17 +3280,40 @@ async function collectTasksView() {
3017
3280
  // общие итоги по всем задачам — отсюда одинаковые 201/130/71).
3018
3281
  const metricsRow = metricsByName.get(name.toLowerCase());
3019
3282
  const counts = metricsRow
3020
- ? { total: metricsRow.total, success: metricsRow.success, error: metricsRow.error }
3021
- : historyCounts.get(name.toLowerCase()) ?? { total: 0, success: 0, error: 0 };
3283
+ ? {
3284
+ total: metricsRow.total,
3285
+ success: metricsRow.success,
3286
+ error: metricsRow.error,
3287
+ partial: metricsRow.partial,
3288
+ }
3289
+ : historyCounts.get(name.toLowerCase()) ?? {
3290
+ total: 0,
3291
+ success: 0,
3292
+ error: 0,
3293
+ partial: 0,
3294
+ };
3022
3295
  return {
3023
3296
  name,
3024
3297
  schedule: def?.schedule ?? "",
3025
3298
  status,
3026
3299
  orphaned,
3300
+ // Спринт 24 (фикс): явный признак паузы. Раньше GUI пытался вывести его
3301
+ // из текстового статуса, но mapStatus() превращает "disabled" в "unknown",
3302
+ // поэтому кнопка «возобновить» была недоступна.
3303
+ paused: Boolean(t.paused),
3027
3304
  runsTotal: counts.total,
3028
3305
  runsSuccess: counts.success,
3029
3306
  runsError: counts.error,
3030
- nextRun: t.nextRunTime ? String(t.nextRunTime) : null,
3307
+ runsPartial: counts.partial,
3308
+ // Для разовой задачи показываем запланированное время, а не пустое расписание.
3309
+ nextRun: def?.triggerType === "once"
3310
+ ? def?.runAt ?? (t.nextRunTime ? String(t.nextRunTime) : null)
3311
+ : t.nextRunTime ? String(t.nextRunTime) : null,
3312
+ runAt: def?.runAt ?? null,
3313
+ session: def?.session ?? "new",
3314
+ sessionId: def?.sessionId ?? null,
3315
+ sessionMaxRuns: def?.sessionMaxRuns ?? null,
3316
+ sessionRunCount: def?.sessionRunCount ?? 0,
3031
3317
  model: def?.model ?? null,
3032
3318
  priority: def?.priority ?? 5,
3033
3319
  beforeScript: def?.beforeScript ?? null,
@@ -3107,8 +3393,11 @@ function mapStatus(status) {
3107
3393
  const s = status.toLowerCase();
3108
3394
  if (s.includes("running") || s.includes("выполняется"))
3109
3395
  return "running";
3396
+ // "Ready" в планировщике Windows означает лишь «готова к запуску», а не
3397
+ // успешное выполнение. Раньше такие задачи показывались зелёными, хотя
3398
+ // могли ни разу не запускаться.
3110
3399
  if (s.includes("ready") || s.includes("готов"))
3111
- return "success";
3400
+ return "idle";
3112
3401
  if (s.includes("disabled"))
3113
3402
  return "unknown";
3114
3403
  return "unknown";