opencode-windows-scheduler 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +45 -1
  2. package/README.md +13 -3
  3. package/README.ru.md +13 -3
  4. package/ROADMAP.md +20 -13
  5. package/dist/core/analytics.d.ts +10 -0
  6. package/dist/core/analytics.d.ts.map +1 -1
  7. package/dist/core/analytics.js +21 -0
  8. package/dist/core/dry-run.d.ts +13 -0
  9. package/dist/core/dry-run.d.ts.map +1 -1
  10. package/dist/core/dry-run.js +30 -0
  11. package/dist/core/matrix.d.ts.map +1 -1
  12. package/dist/core/matrix.js +10 -0
  13. package/dist/core/ps-wrapper.d.ts +32 -2
  14. package/dist/core/ps-wrapper.d.ts.map +1 -1
  15. package/dist/core/ps-wrapper.js +101 -3
  16. package/dist/core/schedule-gate.d.ts +2 -0
  17. package/dist/core/schedule-gate.d.ts.map +1 -0
  18. package/dist/core/schedule-gate.js +182 -0
  19. package/dist/core/schedule-v2.d.ts +88 -0
  20. package/dist/core/schedule-v2.d.ts.map +1 -0
  21. package/dist/core/schedule-v2.js +496 -0
  22. package/dist/core/scheduler/types.d.ts +15 -0
  23. package/dist/core/scheduler/types.d.ts.map +1 -1
  24. package/dist/core/scheduler/windows.d.ts.map +1 -1
  25. package/dist/core/scheduler/windows.js +13 -1
  26. package/dist/core/wrappers/bash.d.ts +15 -0
  27. package/dist/core/wrappers/bash.d.ts.map +1 -1
  28. package/dist/core/wrappers/bash.js +44 -1
  29. package/dist/db/history-repo.d.ts +8 -0
  30. package/dist/db/history-repo.d.ts.map +1 -1
  31. package/dist/db/history-repo.js +13 -0
  32. package/dist/db/schema.d.ts +1 -1
  33. package/dist/db/schema.d.ts.map +1 -1
  34. package/dist/db/schema.js +11 -0
  35. package/dist/index.d.ts +117 -0
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +1010 -54
  38. package/dist/notifications.d.ts +112 -6
  39. package/dist/notifications.d.ts.map +1 -1
  40. package/dist/notifications.js +396 -34
  41. package/dist/profiles.d.ts +60 -0
  42. package/dist/profiles.d.ts.map +1 -0
  43. package/dist/profiles.js +209 -0
  44. package/dist/rpc.d.ts +511 -0
  45. package/dist/rpc.d.ts.map +1 -1
  46. package/dist/rpc.js +190 -2
  47. package/dist/server.d.ts.map +1 -1
  48. package/dist/server.js +5 -2
  49. package/dist/settings.d.ts +57 -0
  50. package/dist/settings.d.ts.map +1 -1
  51. package/dist/settings.js +118 -8
  52. package/dist/task-transfer.d.ts +13 -0
  53. package/dist/task-transfer.d.ts.map +1 -1
  54. package/dist/task-transfer.js +26 -0
  55. package/dist/types.d.ts.map +1 -1
  56. package/dist/types.js +3 -11
  57. package/dist/workspaces.d.ts +43 -0
  58. package/dist/workspaces.d.ts.map +1 -1
  59. package/dist/workspaces.js +174 -8
  60. package/docs/ARCHITECTURE.md +32 -12
  61. package/docs/FEATURES.md +86 -7
  62. package/gui-experimental.cjs +4 -2
  63. package/package.json +6 -2
  64. package/src/core/analytics.ts +36 -0
  65. package/src/core/dry-run.ts +42 -0
  66. package/src/core/matrix.ts +10 -0
  67. package/src/core/ps-wrapper.ts +117 -3
  68. package/src/core/schedule-gate.ts +213 -0
  69. package/src/core/schedule-v2.ts +533 -0
  70. package/src/core/scheduler/types.ts +15 -0
  71. package/src/core/scheduler/windows.ts +13 -1
  72. package/src/core/wrappers/bash.ts +60 -0
  73. package/src/db/history-repo.ts +23 -0
  74. package/src/db/schema.ts +14 -0
  75. package/src/gui.tsx +767 -22
  76. package/src/index.ts +1226 -52
  77. package/src/notifications.ts +516 -40
  78. package/src/profiles.ts +236 -0
  79. package/src/rpc.ts +201 -2
  80. package/src/server.ts +5 -2
  81. package/src/settings.ts +214 -9
  82. package/src/task-transfer.ts +44 -0
  83. package/src/types.ts +3 -13
  84. package/src/workspaces.ts +214 -8
@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { PLUGIN_DIR, sanitizeName } from "./types.js";
4
4
  import { listTasks, saveTask, deleteTask, } from "./db/tasks-repo.js";
5
+ import { isValidIanaTimeZone, validateLaunchWindow } from "./core/schedule-v2.js";
5
6
  const PREFIX = "\\OpenCode\\windows-scheduler\\";
6
7
  /** Приоритет по умолчанию — «Обычный». */
7
8
  export const DEFAULT_PRIORITY = 5;
@@ -109,6 +110,10 @@ export async function buildExportJson(tasks) {
109
110
  ? { triggerType: "mcp-event" }
110
111
  : {}),
111
112
  ...(definition?.watchPath ? { watchPath: definition.watchPath } : {}),
113
+ ...(definition?.timezone ? { timezone: definition.timezone } : {}),
114
+ ...(definition?.notBefore ? { notBefore: definition.notBefore } : {}),
115
+ ...(definition?.notAfter ? { notAfter: definition.notAfter } : {}),
116
+ ...(definition?.pausedUntil ? { pausedUntil: definition.pausedUntil } : {}),
112
117
  ...(Array.isArray(definition?.allowedTools) && definition.allowedTools.length > 0
113
118
  ? { allowedTools: definition.allowedTools }
114
119
  : {}),
@@ -246,6 +251,23 @@ export function parseImportJson(raw) {
246
251
  const model = readOptionalString(source.model);
247
252
  const priority = normalizePriority(source.priority);
248
253
  const workspaceId = readOptionalString(source.workspaceId);
254
+ // Планирование 2.0 (Спринт 19): IANA-зона, окно запуска, пауза до даты.
255
+ const timezone = readOptionalString(source.timezone);
256
+ if (timezone && !isValidIanaTimeZone(timezone)) {
257
+ errors.push(`Запись ${position}${name ? ` (${name})` : ""}: неизвестный часовой пояс ` +
258
+ `«${timezone}» (нужна IANA-зона, например Europe/Moscow).`);
259
+ }
260
+ const notBefore = readOptionalString(source.notBefore);
261
+ const notAfter = readOptionalString(source.notAfter);
262
+ const windowError = validateLaunchWindow(notBefore, notAfter);
263
+ if (windowError) {
264
+ errors.push(`Запись ${position}${name ? ` (${name})` : ""}: ${windowError}`);
265
+ }
266
+ const pausedUntil = readOptionalString(source.pausedUntil);
267
+ if (pausedUntil && Number.isNaN(Date.parse(pausedUntil))) {
268
+ errors.push(`Запись ${position}${name ? ` (${name})` : ""}: pausedUntil должен быть ` +
269
+ `датой в формате ISO (например 2026-12-01T09:00:00Z).`);
270
+ }
249
271
  // Ограничения инструментов (Спринт 14): массив непустых строк без дублей.
250
272
  // Пустой allowedTools отклоняется с явной ошибкой (избегаем «запрещено всё»).
251
273
  const readToolList = (raw, fieldLabel) => {
@@ -431,6 +453,10 @@ export function parseImportJson(raw) {
431
453
  ...(dependsOn !== undefined ? { dependsOn } : {}),
432
454
  ...(triggerType === "cron" ? {} : { triggerType }),
433
455
  ...(watchPath ? { watchPath } : {}),
456
+ ...(timezone !== undefined ? { timezone } : {}),
457
+ ...(notBefore !== undefined ? { notBefore } : {}),
458
+ ...(notAfter !== undefined ? { notAfter } : {}),
459
+ ...(pausedUntil !== undefined ? { pausedUntil } : {}),
434
460
  ...(mcpEvent ? { mcpEvent } : {}),
435
461
  ...(allowedTools !== undefined ? { allowedTools } : {}),
436
462
  ...(deniedTools !== undefined ? { deniedTools } : {}),
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,oFAAoF;AACpF,eAAO,MAAM,WAAW,gCAAgC,CAAC;AAEzD,uDAAuD;AACvD,eAAO,MAAM,WAAW,aAAa,CAAC;AACtC,eAAO,MAAM,gBAAgB,sBAAsB,CAAC;AAwBpD,eAAO,MAAM,UAAU,QAAqB,CAAC;AAE7C,eAAO,MAAM,QAAQ,QAAiC,CAAC;AACvD,eAAO,MAAM,OAAO,QAAgC,CAAC;AACrD,eAAO,MAAM,WAAW,QAAoC,CAAC;AAE7D,4CAA4C;AAC5C,eAAO,MAAM,UAAU,SAA+B,CAAC;AAEvD,iFAAiF;AACjF,eAAO,MAAM,qBAAqB,QAAsB,CAAC;AAEzD;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAcjD;AAED;;;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AM,WAAW,cAAc;IAC7B,yDAAyD;IACzD,EAAE,EAAE,QAAQ,GAAG,QAAQ,GAAG,OAAO,GAAG,QAAQ,CAAC;IAC7C,sEAAsE;IACtE,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,kDAAkD;IAClD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,sCAAsC;IACtC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,+CAA+C;IAC/C,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC,oDAAoD;IACpD,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;IACpB,oDAAoD;IACpD,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB"}
package/dist/types.js CHANGED
@@ -1,6 +1,6 @@
1
- import os from "node:os";
2
1
  import path from "node:path";
3
2
  import { z } from "zod";
3
+ import { getProfileDir, getProfileName } from "./profiles.js";
4
4
  /** Префикс всех задач плагина (историческое имя, сохраняется для совместимости). */
5
5
  export const TASK_PREFIX = "OpenCode\\windows-scheduler";
6
6
  /** Папка задач плагина в планировщике ОС (Windows). */
@@ -12,18 +12,10 @@ export const TASK_FOLDER_NAME = "windows-scheduler";
12
12
  * Windows: %APPDATA%\opencode\windows-scheduler (как раньше — без миграции).
13
13
  * macOS/Linux: $XDG_CONFIG_HOME/opencode/windows-scheduler или
14
14
  * ~/.config/opencode/windows-scheduler.
15
+ * Спринт 21: директория зависит от активного профиля (см. src/profiles.ts).
15
16
  */
16
17
  function resolvePluginDir() {
17
- // Explicit override (tests, custom installations). Takes precedence on every platform.
18
- const custom = process.env.OPENCODE_SCHEDULER_HOME?.trim();
19
- if (custom)
20
- return path.resolve(custom);
21
- if (process.platform === "win32") {
22
- const base = process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming");
23
- return path.join(base, "opencode", TASK_FOLDER_NAME);
24
- }
25
- const configHome = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
26
- return path.join(configHome, "opencode", TASK_FOLDER_NAME);
18
+ return getProfileDir(getProfileName());
27
19
  }
28
20
  export const PLUGIN_DIR = resolvePluginDir();
29
21
  export const LOCK_DIR = path.join(PLUGIN_DIR, "locks");
@@ -11,21 +11,64 @@ export interface Workspace {
11
11
  path: string;
12
12
  gitRemote?: string;
13
13
  color?: string;
14
+ /** Env-переменные workspace (Спринт 21). Значения хранятся как есть. */
15
+ env?: Record<string, string>;
16
+ /** Путь к .env-файлу, переменные которого подмешиваются к env (Спринт 21). */
17
+ envFile?: string;
14
18
  createdAt: string;
15
19
  }
16
20
  export interface AddWorkspaceInput {
17
21
  name?: string;
18
22
  path: string;
19
23
  color?: string;
24
+ env?: Record<string, string> | null;
25
+ envFile?: string | null;
20
26
  }
21
27
  export interface UpdateWorkspacePatch {
22
28
  name?: string;
23
29
  path?: string;
24
30
  color?: string;
25
31
  gitRemote?: string | null;
32
+ env?: Record<string, string> | null;
33
+ envFile?: string | null;
26
34
  }
35
+ /** Максимум пар env на workspace — защита от раздувания строки JSON. */
36
+ export declare const MAX_WORKSPACE_ENV_PAIRS = 100;
27
37
  /** Палитра цветных маркеров для GUI/дашборда. */
28
38
  export declare const WORKSPACE_COLORS: string[];
39
+ /**
40
+ * Нормализует пары env: ключи — валидные имена переменных, значения — строки.
41
+ * Бросает понятную ошибку при нарушении (её показывает GUI/RPC).
42
+ */
43
+ export declare function normalizeWorkspaceEnv(value: unknown): Record<string, string> | undefined;
44
+ /**
45
+ * Разбирает содержимое .env: строки KEY=VALUE, комментарии `#`, пустые строки,
46
+ * префикс `export `, кавычки вокруг значения снимаются.
47
+ */
48
+ export declare function parseEnvFileContent(content: string): Record<string, string>;
49
+ /** Читает .env-файл workspace (если он задан и существует). */
50
+ export declare function readWorkspaceEnvFile(envFile?: string): Record<string, string>;
51
+ /**
52
+ * Итоговые env-переменные workspace: сначала .env-файл, затем явные пары
53
+ * (пары важнее файла). Никогда не бросает.
54
+ */
55
+ export declare function resolveWorkspaceEnv(workspace: Workspace | undefined): Record<string, string>;
56
+ /** Маскирует значение секрета для логов. */
57
+ export declare function maskSecretValue(): string;
58
+ /** Копия env для логов: значения «секретных» ключей заменены на ***. */
59
+ export declare function maskEnvForLog(env: Record<string, string> | undefined): Record<string, string>;
60
+ /**
61
+ * Каталог env-файлов задач внутри каталога плагина (по одному файлу на задачу).
62
+ * Файлы содержат реальные значения и не попадают в git/логи.
63
+ */
64
+ export declare function workspaceEnvDir(pluginDir: string): string;
65
+ /**
66
+ * Пишет env-файл задачи в формате KEY=VALUE (Спринт 21).
67
+ *
68
+ * Возвращает путь к файлу или undefined, если у workspace нет переменных.
69
+ * Пустой env удаляет ранее созданный файл. На POSIX права 0600.
70
+ */
71
+ export declare function writeWorkspaceEnvFile(workspace: Workspace | undefined, pluginDir: string, sanitizedName: string): string | undefined;
29
72
  /** Проверяет, что путь существует и является директорией. */
30
73
  export declare function validateWorkspacePath(workspacePath: string): void;
31
74
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"workspaces.d.ts","sourceRoot":"","sources":["../src/workspaces.ts"],"names":[],"mappings":"AAOA;;;;;;GAMG;AACH,MAAM,WAAW,SAAS;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;I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wBAAgB,kBAAkB,CAAC,aAAa,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS,CAM/E;AAED,8DAA8D;AAC9D,wBAAgB,YAAY,CAAC,KAAK,EAAE,iBAAiB,GAAG,SAAS,CA2ChE;AAED,yCAAyC;AACzC,wBAAgB,eAAe,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,oBAAoB,GAAG,SAAS,CAgElF;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAenD;AAED,kDAAkD;AAClD,wBAAgB,eAAe,IAAI,MAAM,CAGxC"}
@@ -1,9 +1,11 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { statSync } from "node:fs";
3
- import { basename, resolve } from "node:path";
2
+ import { chmodSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
3
+ import { basename, join, resolve } from "node:path";
4
4
  import { spawnSync } from "node:child_process";
5
5
  import { getDb } from "./db/index.js";
6
6
  import { clearWorkspaceAssignments } from "./db/tasks-repo.js";
7
+ /** Максимум пар env на workspace — защита от раздувания строки JSON. */
8
+ export const MAX_WORKSPACE_ENV_PAIRS = 100;
7
9
  /** Палитра цветных маркеров для GUI/дашборда. */
8
10
  export const WORKSPACE_COLORS = [
9
11
  "#5b8def",
@@ -13,13 +15,163 @@ export const WORKSPACE_COLORS = [
13
15
  "#8b6fe8",
14
16
  "#3aa8b8",
15
17
  ];
18
+ const ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
19
+ /**
20
+ * Нормализует пары env: ключи — валидные имена переменных, значения — строки.
21
+ * Бросает понятную ошибку при нарушении (её показывает GUI/RPC).
22
+ */
23
+ export function normalizeWorkspaceEnv(value) {
24
+ if (value == null)
25
+ return undefined;
26
+ if (typeof value !== "object" || Array.isArray(value)) {
27
+ throw new Error("env должен быть объектом «ключ → значение».");
28
+ }
29
+ const entries = Object.entries(value);
30
+ if (entries.length > MAX_WORKSPACE_ENV_PAIRS) {
31
+ throw new Error(`Слишком много env-переменных: ${entries.length} (максимум ${MAX_WORKSPACE_ENV_PAIRS}).`);
32
+ }
33
+ const result = {};
34
+ for (const [rawKey, rawValue] of entries) {
35
+ const key = String(rawKey).trim();
36
+ if (!ENV_KEY_RE.test(key)) {
37
+ throw new Error(`Недопустимое имя env-переменной '${rawKey}': нужны латиница, цифры и '_', не с цифры.`);
38
+ }
39
+ if (rawValue == null) {
40
+ result[key] = "";
41
+ continue;
42
+ }
43
+ if (typeof rawValue === "object") {
44
+ throw new Error(`Значение env '${key}' должно быть строкой.`);
45
+ }
46
+ result[key] = String(rawValue);
47
+ }
48
+ return result;
49
+ }
50
+ /**
51
+ * Разбирает содержимое .env: строки KEY=VALUE, комментарии `#`, пустые строки,
52
+ * префикс `export `, кавычки вокруг значения снимаются.
53
+ */
54
+ export function parseEnvFileContent(content) {
55
+ const result = {};
56
+ for (const line of String(content).split(/\r?\n/)) {
57
+ const trimmed = line.trim();
58
+ if (!trimmed || trimmed.startsWith("#"))
59
+ continue;
60
+ const withoutExport = trimmed.startsWith("export ")
61
+ ? trimmed.slice("export ".length).trim()
62
+ : trimmed;
63
+ const eq = withoutExport.indexOf("=");
64
+ if (eq <= 0)
65
+ continue;
66
+ const key = withoutExport.slice(0, eq).trim();
67
+ if (!ENV_KEY_RE.test(key))
68
+ continue;
69
+ let value = withoutExport.slice(eq + 1).trim();
70
+ if ((value.startsWith('"') && value.endsWith('"') && value.length >= 2) ||
71
+ (value.startsWith("'") && value.endsWith("'") && value.length >= 2)) {
72
+ value = value.slice(1, -1);
73
+ }
74
+ result[key] = value;
75
+ }
76
+ return result;
77
+ }
78
+ /** Читает .env-файл workspace (если он задан и существует). */
79
+ export function readWorkspaceEnvFile(envFile) {
80
+ if (!envFile)
81
+ return {};
82
+ try {
83
+ return parseEnvFileContent(readFileSync(envFile, "utf8"));
84
+ }
85
+ catch {
86
+ return {};
87
+ }
88
+ }
89
+ /**
90
+ * Итоговые env-переменные workspace: сначала .env-файл, затем явные пары
91
+ * (пары важнее файла). Никогда не бросает.
92
+ */
93
+ export function resolveWorkspaceEnv(workspace) {
94
+ if (!workspace)
95
+ return {};
96
+ return {
97
+ ...readWorkspaceEnvFile(workspace.envFile),
98
+ ...(workspace.env ?? {}),
99
+ };
100
+ }
101
+ /** Маскирует значение секрета для логов. */
102
+ export function maskSecretValue() {
103
+ return "***";
104
+ }
105
+ const SECRET_KEY_RE = /(TOKEN|SECRET|PASS|PASSWORD|KEY|CREDENTIAL|AUTH)/i;
106
+ /** Копия env для логов: значения «секретных» ключей заменены на ***. */
107
+ export function maskEnvForLog(env) {
108
+ if (!env)
109
+ return {};
110
+ const masked = {};
111
+ for (const [key, value] of Object.entries(env)) {
112
+ masked[key] = SECRET_KEY_RE.test(key) ? maskSecretValue() : value;
113
+ }
114
+ return masked;
115
+ }
116
+ /**
117
+ * Каталог env-файлов задач внутри каталога плагина (по одному файлу на задачу).
118
+ * Файлы содержат реальные значения и не попадают в git/логи.
119
+ */
120
+ export function workspaceEnvDir(pluginDir) {
121
+ return join(pluginDir, "env");
122
+ }
123
+ /**
124
+ * Пишет env-файл задачи в формате KEY=VALUE (Спринт 21).
125
+ *
126
+ * Возвращает путь к файлу или undefined, если у workspace нет переменных.
127
+ * Пустой env удаляет ранее созданный файл. На POSIX права 0600.
128
+ */
129
+ export function writeWorkspaceEnvFile(workspace, pluginDir, sanitizedName) {
130
+ const file = join(workspaceEnvDir(pluginDir), `${sanitizedName}.env`);
131
+ const env = resolveWorkspaceEnv(workspace);
132
+ const keys = Object.keys(env);
133
+ if (!keys.length) {
134
+ try {
135
+ rmSync(file, { force: true });
136
+ }
137
+ catch {
138
+ // нечего удалять — не ошибка
139
+ }
140
+ return undefined;
141
+ }
142
+ const body = keys
143
+ .map((key) => `${key}=${String(env[key]).replace(/\r?\n/g, " ")}`)
144
+ .join("\n") + "\n";
145
+ mkdirSync(workspaceEnvDir(pluginDir), { recursive: true });
146
+ writeFileSync(file, body, { encoding: "utf8", mode: 0o600 });
147
+ if (process.platform !== "win32") {
148
+ try {
149
+ chmodSync(file, 0o600);
150
+ }
151
+ catch {
152
+ // права не критичны для работы задачи
153
+ }
154
+ }
155
+ return file;
156
+ }
16
157
  function rowToWorkspace(row) {
158
+ let env;
159
+ if (row.env_json) {
160
+ try {
161
+ env = normalizeWorkspaceEnv(JSON.parse(String(row.env_json)));
162
+ }
163
+ catch {
164
+ env = undefined;
165
+ }
166
+ }
17
167
  return {
18
168
  id: String(row.id),
19
169
  name: String(row.name),
20
170
  path: String(row.path),
21
171
  gitRemote: row.git_remote == null ? undefined : String(row.git_remote),
22
172
  color: row.color == null ? undefined : String(row.color),
173
+ env,
174
+ envFile: row.env_file == null ? undefined : String(row.env_file),
23
175
  createdAt: String(row.created_at),
24
176
  };
25
177
  }
@@ -114,11 +266,13 @@ export function addWorkspace(input) {
114
266
  WORKSPACE_COLORS[listWorkspaces().length % WORKSPACE_COLORS.length];
115
267
  const createdAt = new Date().toISOString();
116
268
  const gitRemote = readGitRemote(workspacePath);
269
+ const env = normalizeWorkspaceEnv(input.env);
270
+ const envFile = input.envFile?.trim() || undefined;
117
271
  getDb()
118
- .prepare(`INSERT INTO workspaces (id, name, path, git_remote, color, created_at)
119
- VALUES (?, ?, ?, ?, ?, ?)`)
120
- .run(id, name, workspacePath, gitRemote ?? null, color, createdAt);
121
- return { id, name, path: workspacePath, gitRemote, color, createdAt };
272
+ .prepare(`INSERT INTO workspaces (id, name, path, git_remote, color, env_json, env_file, created_at)
273
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)
274
+ .run(id, name, workspacePath, gitRemote ?? null, color, env ? JSON.stringify(env) : null, envFile ?? null, createdAt);
275
+ return { id, name, path: workspacePath, gitRemote, color, env, envFile, createdAt };
122
276
  }
123
277
  /** Обновляет имя/путь/цвет workspace. */
124
278
  export function updateWorkspace(id, patch) {
@@ -147,15 +301,27 @@ export function updateWorkspace(id, patch) {
147
301
  : nextPath !== existing.path
148
302
  ? readGitRemote(nextPath)
149
303
  : existing.gitRemote;
304
+ const nextEnv = patch.env === null
305
+ ? undefined
306
+ : patch.env !== undefined
307
+ ? normalizeWorkspaceEnv(patch.env)
308
+ : existing.env;
309
+ const nextEnvFile = patch.envFile === null
310
+ ? undefined
311
+ : patch.envFile !== undefined
312
+ ? patch.envFile.trim() || undefined
313
+ : existing.envFile;
150
314
  getDb()
151
- .prepare("UPDATE workspaces SET name = ?, path = ?, git_remote = ?, color = ? WHERE id = ?")
152
- .run(nextName, nextPath, nextRemote ?? null, nextColor ?? null, id);
315
+ .prepare("UPDATE workspaces SET name = ?, path = ?, git_remote = ?, color = ?, env_json = ?, env_file = ? WHERE id = ?")
316
+ .run(nextName, nextPath, nextRemote ?? null, nextColor ?? null, nextEnv ? JSON.stringify(nextEnv) : null, nextEnvFile ?? null, id);
153
317
  return {
154
318
  id,
155
319
  name: nextName,
156
320
  path: nextPath,
157
321
  gitRemote: nextRemote,
158
322
  color: nextColor,
323
+ env: nextEnv,
324
+ envFile: nextEnvFile,
159
325
  createdAt: existing.createdAt,
160
326
  };
161
327
  }
@@ -86,21 +86,28 @@ is read from the database or from files under the plugin directory.
86
86
 
87
87
  1. Agent tool / GUI / import calls `schedulerCreateTask(...)`.
88
88
  2. Definitions are validated (cron, workspace path, matrix rules), a prompt file and a
89
- wrapper script are written under the plugin directory.
89
+ wrapper script are written under the plugin directory; if the task's workspace has
90
+ env variables, `<PLUGIN_DIR>/env/<sanitized>.env` is written (mode `0600` on POSIX).
90
91
  3. An OS entry is created through the platform backend.
91
92
  4. The definition is stored in `tasks.definition_json`.
92
93
 
93
94
  **Run a task**
94
95
 
95
96
  1. The OS scheduler starts the wrapper.
96
- 2. The wrapper acquires the lock (`locks/<task>.lock`), writes the log
97
- (`logs/<task>.log`), runs the pre-flight hook and starts `opencode run` with the
98
- prompt file. Output is streamed to the log.
99
- 3. When the process ends, the wrapper enforces the timeout result, runs the Quality
97
+ 2. When the task carries a schedule gate (poll-mode cron, foreign timezone or a
98
+ launch window), the wrapper first runs `node dist/core/schedule-gate.js`: it
99
+ re-checks the extended cron in the task's zone, and if now is outside the
100
+ launch window it waits until the window opens (postpone, deduplicated by a
101
+ defer-file) or exits with code 3 so the wrapper skips silently.
102
+ 3. The wrapper acquires the lock (`locks/<task>.lock`), writes the log
103
+ (`logs/<task>.log`), loads workspace env from `<PLUGIN_DIR>/env/<sanitized>.env`
104
+ (Windows `-EnvFile`, POSIX `set -a; . "$ENV_FILE"; set +a`) before starting
105
+ `opencode run` with the prompt file. Output is streamed to the log.
106
+ 4. When the process ends, the wrapper enforces the timeout result, runs the Quality
100
107
  Gate and the post-flight hook.
101
- 4. The wrapper calls `node dist/core/record-history.js --finish ...` with status,
108
+ 5. The wrapper calls `node dist/core/record-history.js --finish ...` with status,
102
109
  duration, tokens, cost, model and hook results.
103
- 5. The recorder writes `history` and updates `metrics`, then evaluates retries, task
110
+ 6. The recorder writes `history` and updates `metrics`, then evaluates retries, task
104
111
  chains, DAG dependents and matrix continuation.
105
112
 
106
113
  **Read state**
@@ -119,10 +126,11 @@ from their clones instead of their own last run.
119
126
  | `src/server.ts` | Local web dashboard HTTP server and HTML rendering |
120
127
  | `src/skill.ts` | Loads and registers the bundled agent skill |
121
128
  | `src/task-transfer.ts` | Export/import, validation, `MatrixConfig` types |
122
- | `src/workspaces.ts` | Workspace registry and path validation |
129
+ | `src/profiles.ts` | Profile directory resolution: per-profile plugin dir (base for `default`, `<base>/profiles/<name>` for named profiles); profile name, marker, port, create/delete/switch |
130
+ | `src/workspaces.ts` | Workspace registry and path validation; env pairs and `.env` file resolution with secret masking |
123
131
  | `src/templates.ts` | Reusable task templates |
124
132
  | `src/settings.ts` | Plugin settings: notifications and history retention |
125
- | `src/notifications.ts` | Webhook notifications |
133
+ | `src/notifications.ts` | Webhook delivery with retries/backoff, templates, task filters, matrix and stuck-clone notifications, daily/weekly digest |
126
134
  | `src/history.ts` | History model and status types |
127
135
  | `src/version.ts` | Runtime plugin version (reads package.json) |
128
136
  | `src/core/retention.ts` | Daily history prune and incremental vacuum |
@@ -136,6 +144,8 @@ from their clones instead of their own last run.
136
144
  | `src/core/lock.ts` | Single-instance lock manager |
137
145
  | `src/core/file-watcher.ts` | chokidar-based file triggers |
138
146
  | `src/core/cron-to-schtasks.ts` | Cron → Task Scheduler translation |
147
+ | `src/core/schedule-v2.ts` | Extended cron parser/matcher, timezone math, launch windows, poll-mode decisions |
148
+ | `src/core/schedule-gate.ts` | Wrapper-side gate: cron re-check (poll mode), window postpone, defer-file |
139
149
  | `src/db/` | SQLite access: schema, migrations, repositories, recovery |
140
150
  | `src/shared/jobs-view.ts` | Task view shared by the GUI and dashboard |
141
151
 
@@ -166,6 +176,7 @@ enforced:
166
176
  | Working directory | Task `workingDirectory`, or the workspace path, or the plugin directory |
167
177
  | Prompt | Written to a prompt file, passed to `opencode run` |
168
178
  | Timeout | `timeoutSeconds`; on expiry the child process tree is stopped and the run is marked `timeout` |
179
+ | Workspace env | Variables from the workspace's `.env` file and explicit pairs are injected before `opencode run` (wrapper `env:` / `export`); secret-looking keys are masked in logs |
169
180
  | No overlap | Lock file per task; a second start exits immediately and records `skipped` |
170
181
  | Pre-flight | `beforeScript`; non-zero exit marks `preFlight` as failed |
171
182
  | Quality Gate | `qualityGate` after a successful run; non-zero exit turns the run into an error |
@@ -238,10 +249,13 @@ remote and color. Workspaces provide:
238
249
  - the working directory for a task (`workspaceId` instead of `workingDirectory`);
239
250
  - matrix targets (`matrix.workspaceIds`);
240
251
  - per-workspace overrides (`matrix.overrides`);
241
- - dashboard grouping.
252
+ - dashboard grouping;
253
+ - env variables: explicit `KEY=VALUE` pairs plus an optional `.env` file (loaded first,
254
+ explicit pairs override), injected into task runs via the wrapper; secret-looking
255
+ keys are masked in logs.
242
256
 
243
257
  Paths are validated on creation, update and import: a workspace must point to an
244
- existing directory.
258
+ existing directory. Env keys must match `^[A-Za-z_][A-Za-z0-9_]*$`; max 100 pairs.
245
259
 
246
260
  ## Triggers
247
261
 
@@ -270,11 +284,17 @@ logs/ per-task run logs
270
284
  locks/ lock files
271
285
  wrappers/ generated .cmd / .sh wrappers
272
286
  prompts/ prompt files
287
+ env/ per-workspace env files (<task>.env), mode 0600 on POSIX
273
288
  ```
274
289
 
290
+ Named profiles (Sprint 21) each own a copy of this tree under
291
+ `<base>/profiles/<name>` (`default` uses the base directory). Profile directory,
292
+ database, settings, logs, wrappers and locks all resolve per-profile.
293
+
275
294
  Override the database location with `OPENCODE_SCHEDULER_DB` (used by tests). Override
276
295
  the whole plugin directory (database, logs, locks, wrappers, prompts) with
277
- `OPENCODE_SCHEDULER_HOME` on any platform.
296
+ `OPENCODE_SCHEDULER_HOME` on any platform. Profile selection uses
297
+ `OPENCODE_SCHEDULER_PROFILE` > `active-profile` marker > `default`.
278
298
 
279
299
  Schema evolution is additive: `applySchema` runs `CREATE TABLE IF NOT EXISTS` on every
280
300
  connection and adds missing columns after `PRAGMA table_info`, so upgrading the plugin
package/docs/FEATURES.md CHANGED
@@ -7,6 +7,8 @@ matter in practice.
7
7
  - [Execution policy](#execution-policy)
8
8
  - [Orchestration](#orchestration)
9
9
  - [Multi-repository workspaces](#multi-repository-workspaces)
10
+ - [Profiles (multi-project)](#profiles-multi-project)
11
+ - [Workspace environment variables](#workspace-environment-variables)
10
12
  - [Observability](#observability)
11
13
  - [Management](#management)
12
14
  - [Agent interface](#agent-interface)
@@ -17,7 +19,10 @@ matter in practice.
17
19
 
18
20
  ### Cron schedules
19
21
 
20
- Five-field cron: `minute hour day-of-month month day-of-week`.
22
+ Five-field cron: `minute hour day-of-month month day-of-week`. Supports lists,
23
+ ranges and steps in every field (`0 8-10,18 * * 1-5/2`), month and weekday names
24
+ (`0 9 * * MON-FRI`), `@every` sugar (`@every 15m`, `@every 2h`, `@every 1d`),
25
+ `L` as the last day of the month and the `d#n` n-th weekday form (`0 9 * * FRI#3`).
21
26
 
22
27
  | Pattern | Example | Meaning |
23
28
  | --- | --- | --- |
@@ -25,10 +30,26 @@ Five-field cron: `minute hour day-of-month month day-of-week`.
25
30
  | Fixed time | `0 9 * * *` | Daily at 09:00 |
26
31
  | Weekdays | `30 8 * * 1-5` | 08:30 Monday to Friday |
27
32
  | Monthly | `0 3 1 * *` | 03:00 on the 1st |
28
-
29
- The Windows backend translates cron to native Task Scheduler triggers. Expressions
30
- that `schtasks` cannot express are rejected at creation time with an explicit error
31
- instead of being silently approximated.
33
+ | Last day | `0 3 L * *` | 03:00 on the last day of the month |
34
+ | N-th weekday | `0 9 * * FRI#3` | 09:00 on the third Friday |
35
+ | Sugar | `@every 15m` | Every 15 minutes |
36
+
37
+ The Windows backend translates simple cron expressions to native Task Scheduler
38
+ triggers. Expressions `schtasks` cannot express (`L`, `#`, complex lists) or tasks
39
+ with a timezone other than the system one are registered in poll mode: the OS task
40
+ wakes the wrapper every minute and `schedule-gate` decides whether the agent runs.
41
+
42
+ ### Timezones and launch windows
43
+
44
+ - `timezone` — IANA zone per task (e.g. `Europe/Moscow`). `nextRun`/`prevRun`,
45
+ dry-run next-run estimates and the gate evaluate cron in this zone; DST
46
+ transitions are handled (nonexistent spring-forward times are skipped).
47
+ - `notBefore` / `notAfter` — daily launch window in `HH:MM` (may cross midnight,
48
+ e.g. `22:00`–`06:00`). A run that fires outside the window is **postponed**
49
+ until the window opens (once, via a defer-file), not skipped.
50
+ - `pausedUntil` — pause a task until an ISO moment. `pause_task` accepts
51
+ `until`; the plugin re-enables the task automatically at startup and on a
52
+ 5-minute timer, and `resume_task` resumes early.
32
53
 
33
54
  ### File triggers
34
55
 
@@ -186,6 +207,42 @@ Use `workspaceId` instead of `workingDirectory` to run a task in a workspace. Pa
186
207
  validated on add/update/import, and the dashboard groups tasks and runs by workspace.
187
208
  Workspaces are the unit that matrix builds fan out to.
188
209
 
210
+ ## Profiles (multi-project, Спринт 21)
211
+
212
+ Profiles let you run several independent scheduler installations inside one plugin,
213
+ each with its own SQLite database, settings, logs, wrappers and dashboard port.
214
+ This is useful for separating projects, clients or environments (e.g. `default` and
215
+ `work`) without them seeing each other's data.
216
+
217
+ - Profile `default` uses the plugin's base directory (no migration, behaves exactly
218
+ as before Sprint 21). Named profiles live in `<base>/profiles/<name>`.
219
+ - Profile selection order: `OPENCODE_SCHEDULER_PROFILE` env var → file `active-profile`
220
+ in the base directory → `default`. Switching profiles writes the marker and requires
221
+ an OpenCode restart because plugin directories are resolved at module load time.
222
+ - Dashboard port per profile: `OPENCODE_SCHEDULER_PORT` env var → port from
223
+ `profile.json` → server default (3782, then 4782/5782 fallback).
224
+ - RPC: `get_profiles` lists profiles with dirs, ports and the active flag;
225
+ `set_profile` switches the active profile (restart hint); `create_profile` /
226
+ `delete_profile` manage named profiles (`default` cannot be deleted).
227
+
228
+ ### Workspace environment variables (Спринт 21)
229
+
230
+ Each workspace can carry env variables that are injected into every task run in that
231
+ workspace:
232
+
233
+ - `env` — explicit `KEY=VALUE` pairs stored in SQLite as JSON;
234
+ - `envFile` — optional path to a `.env` file whose variables are loaded first, then
235
+ explicit pairs override them;
236
+ - File format: `KEY=value` lines, `#` comments, blank lines, leading `export `,
237
+ values in matching quotes are unquoted;
238
+ - Key validation: `^[A-Za-z_][A-Za-z0-9_]*$`, max 100 pairs per workspace;
239
+ - Delivery: at task create/update the plugin writes `<PLUGIN_DIR>/env/<sanitized>.env`
240
+ with real values (mode `0600` on POSIX) and passes it to the wrapper
241
+ (Windows: `-EnvFile "<path>"`; POSIX: `set -a; . "$ENV_FILE"; set +a` before the
242
+ `opencode run` invocation);
243
+ - Secret masking: keys matching `/(TOKEN|SECRET|PASS|PASSWORD|KEY|CREDENTIAL|AUTH)/i`
244
+ are shown as `***` in logs and masked API responses — values never leak into logs.
245
+
189
246
  ## Observability
190
247
 
191
248
  ### History
@@ -248,6 +305,25 @@ matrix combinations are rejected explicitly.
248
305
  Webhook notifications on run completion, configurable in settings and testable with
249
306
  `test_notification`.
250
307
 
308
+ - **Delivery:** per-task completion (success/error/timeout) through a Discord/Slack
309
+ compatible webhook (`{ content, text }`). `webhook.timeoutMs` (default 10 000),
310
+ `webhook.retryCount` (default 2) and `webhook.retryDelayMs` (default 1000) control
311
+ the request; network errors, timeouts, HTTP 5xx and 429 are retried with exponential
312
+ backoff (capped at 30 s), other 4xx are not.
313
+ - **Templates:** `templates.success` and `templates.error` accept placeholders
314
+ `{task}`, `{status}`, `{duration}`, `{error}`, `{emoji}`.
315
+ - **Filters:** `filters.include` / `filters.exclude` are task-name patterns with `*`
316
+ wildcards; an empty include list means all tasks, exclude wins.
317
+ - **Matrix notifications:** on family completion — success, `partial` (`onPartial`)
318
+ and all clones failed (`onAllFailed`). A stuck detector reports clones running
319
+ longer than `matrix.stuckAfterMinutes` (default 60, `0` disables) once per run.
320
+ - **Digest:** `digest.enabled` sends a daily (`frequency: "daily"`, at `digest.time`)
321
+ or weekly (Mondays, catch-up afterwards) summary: runs, success rate, cost, tokens
322
+ and top errors. Also available as the `send_digest` RPC and the GUI's
323
+ «📊 Отправить дайджест сейчас» button (manual sends do not move the schedule).
324
+ - **ntfy.sh is intentionally not implemented** (excluded by the assignment); the
325
+ network channel is the webhook, plus GUI toasts for manual runs.
326
+
251
327
  ### Crash recovery
252
328
 
253
329
  Runs left in `running` after a crash are marked `error` on the next plugin start, so
@@ -265,9 +341,12 @@ the `cleanup_history` RPC and the GUI's «Очистить сейчас» button
265
341
 
266
342
  ## Agent interface
267
343
 
268
- Twelve tools: `schedule_task`, `list_tasks`, `update_task`, `delete_task`,
344
+ Twenty-two tools: `schedule_task`, `list_tasks`, `update_task`, `delete_task`,
269
345
  `run_task_now`, `pause_task`, `resume_task`, `get_history`, `get_task_logs`, `dry_run`,
270
- `manage_workspaces`, `matrix_control`.
346
+ `manage_workspaces`, `matrix_control` (results/cancel/cleanup/preview), `get_metrics`,
347
+ `get_analytics`, `manage_settings`, `manage_templates`, `manage_profiles`,
348
+ `transfer_tasks`, `send_notification`, `get_dashboard_info`, `cleanup_history`,
349
+ `emit_event`.
271
350
 
272
351
  A bundled skill, `scheduled-job-best-practices`, teaches the agent safe defaults:
273
352
  least privilege, Quality Gates, timeout, matrix concurrency, DAG rules and a