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
package/src/settings.ts CHANGED
@@ -8,6 +8,55 @@ export interface WebhookNotificationSettings {
8
8
  enabled: boolean;
9
9
  /** URL вебхука. */
10
10
  url: string;
11
+ /** Таймаут запроса в мс (1000..120000). */
12
+ timeoutMs: number;
13
+ /** Сколько раз повторить при сетевой ошибке / 5xx / 429 (0..5). */
14
+ retryCount: number;
15
+ /** Базовая задержка backoff в мс; каждая следующая попытка ждёт вдвое дольше. */
16
+ retryDelayMs: number;
17
+ }
18
+
19
+ /** Настраиваемые шаблоны сообщений о завершении задачи. */
20
+ export interface NotificationTemplates {
21
+ /** Шаблон успеха. Плейсхолдеры: {task} {status} {duration} {error} {emoji}. */
22
+ success: string;
23
+ /** Шаблон ошибки. {error} разворачивается в «: текст» или пустую строку. */
24
+ error: string;
25
+ }
26
+
27
+ /** Фильтры по задачам: include имеет приоритет, exclude сильнее include. */
28
+ export interface NotificationFilters {
29
+ /** Уведомлять только эти задачи (пусто — все). Поддерживает `*`. */
30
+ include: string[];
31
+ /** Никогда не уведомлять эти задачи. Поддерживает `*`. */
32
+ exclude: string[];
33
+ }
34
+
35
+ /** Уведомления о матрицах (Спринт 20). */
36
+ export interface MatrixNotificationSettings {
37
+ /** Включены ли уведомления о матрицах. */
38
+ enabled: boolean;
39
+ /** Сообщать о partial (часть клонов упала). */
40
+ onPartial: boolean;
41
+ /** Сообщать, когда упали все клоны. */
42
+ onAllFailed: boolean;
43
+ /** Порог «матрица зависла» в минутах (0 — детектор выключен). */
44
+ stuckAfterMinutes: number;
45
+ }
46
+
47
+ /** Периодичность дайджеста. */
48
+ export type DigestFrequency = "daily" | "weekly";
49
+
50
+ /** Дайджест по истории запусков (Спринт 20). */
51
+ export interface DigestSettings {
52
+ /** Включён ли дайджест. */
53
+ enabled: boolean;
54
+ /** Ежедневно или еженедельно (по понедельникам). */
55
+ frequency: DigestFrequency;
56
+ /** Время отправки в формате HH:MM (локальное время сервера). */
57
+ time: string;
58
+ /** ISO-момент последней отправки — дедуп между перезапусками плагина. */
59
+ lastSentAt: string | null;
11
60
  }
12
61
 
13
62
  /**
@@ -23,6 +72,14 @@ export interface NotificationSettings {
23
72
  onlyOnError: boolean;
24
73
  /** Webhook-канал. */
25
74
  webhook?: WebhookNotificationSettings;
75
+ /** Шаблоны сообщений. */
76
+ templates?: NotificationTemplates;
77
+ /** Фильтры по задачам. */
78
+ filters?: NotificationFilters;
79
+ /** Уведомления о матрицах. */
80
+ matrix?: MatrixNotificationSettings;
81
+ /** Периодический дайджест. */
82
+ digest?: DigestSettings;
26
83
  }
27
84
 
28
85
  /**
@@ -64,6 +121,12 @@ export const DEFAULT_WINTER_MODE = false;
64
121
  export const DEFAULT_RETENTION_DAYS = 30;
65
122
  export const DEFAULT_MAX_RECORDS = 5000;
66
123
 
124
+ /** Уведомления (Спринт 20): таймаут webhook, повторы и порог «зависшей» матрицы. */
125
+ export const DEFAULT_WEBHOOK_TIMEOUT_MS = 10_000;
126
+ export const DEFAULT_WEBHOOK_RETRY_COUNT = 2;
127
+ export const DEFAULT_WEBHOOK_RETRY_DELAY_MS = 1_000;
128
+ export const DEFAULT_STUCK_AFTER_MINUTES = 60;
129
+
67
130
  /** Ретеншн по умолчанию: 30 дней и не больше 5000 записей. */
68
131
  export function defaultHistorySettings(): HistorySettings {
69
132
  return {
@@ -111,7 +174,30 @@ export function defaultNotifications(): NotificationSettings {
111
174
  return {
112
175
  enabled: false,
113
176
  onlyOnError: true,
114
- webhook: { enabled: false, url: "" },
177
+ webhook: {
178
+ enabled: false,
179
+ url: "",
180
+ timeoutMs: DEFAULT_WEBHOOK_TIMEOUT_MS,
181
+ retryCount: DEFAULT_WEBHOOK_RETRY_COUNT,
182
+ retryDelayMs: DEFAULT_WEBHOOK_RETRY_DELAY_MS,
183
+ },
184
+ templates: {
185
+ success: '✅ Задача "{task}" выполнена ({duration})',
186
+ error: '❌ Задача "{task}" упала ({duration}){error}',
187
+ },
188
+ filters: { include: [], exclude: [] },
189
+ matrix: {
190
+ enabled: true,
191
+ onPartial: true,
192
+ onAllFailed: true,
193
+ stuckAfterMinutes: DEFAULT_STUCK_AFTER_MINUTES,
194
+ },
195
+ digest: {
196
+ enabled: false,
197
+ frequency: "daily",
198
+ time: "09:00",
199
+ lastSentAt: null,
200
+ },
115
201
  };
116
202
  }
117
203
 
@@ -131,24 +217,82 @@ function normalizeWinterMode(value: unknown, fallback: boolean): boolean {
131
217
  return fallback;
132
218
  }
133
219
 
220
+ /** Приводит значение к конечному целому в диапазоне [min, max]. */
221
+ function normalizeIntInRange(
222
+ value: unknown,
223
+ fallback: number,
224
+ min: number,
225
+ max: number
226
+ ): number {
227
+ const n = Number(value);
228
+ if (!Number.isFinite(n)) return fallback;
229
+ return Math.min(max, Math.max(min, Math.floor(n)));
230
+ }
231
+
232
+ /** Приводит время HH:MM к безопасному виду. */
233
+ function normalizeDailyTime(value: unknown, fallback: string): string {
234
+ if (typeof value === "string" && /^([01]\d|2[0-3]):[0-5]\d$/.test(value.trim())) {
235
+ return value.trim();
236
+ }
237
+ return fallback;
238
+ }
239
+
240
+ /** Список имён задач: массив строк, обрезанных и без пустых значений. */
241
+ function normalizeNameList(value: unknown, fallback: string[]): string[] {
242
+ if (!Array.isArray(value)) return [...fallback];
243
+ return value
244
+ .filter((item): item is string => typeof item === "string")
245
+ .map((item) => item.trim())
246
+ .filter((item) => item.length > 0);
247
+ }
248
+
249
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
250
+ return value && typeof value === "object" && !Array.isArray(value)
251
+ ? (value as Record<string, unknown>)
252
+ : undefined;
253
+ }
254
+
134
255
  /** Приводит настройки уведомлений к безопасному виду. */
135
256
  function normalizeNotifications(
136
257
  value: unknown,
137
258
  fallback: NotificationSettings
138
259
  ): NotificationSettings {
139
- if (!value || typeof value !== "object" || Array.isArray(value)) {
260
+ const fallbackWebhook = fallback.webhook ?? defaultNotifications().webhook!;
261
+ const fallbackTemplates = fallback.templates ?? defaultNotifications().templates!;
262
+ const fallbackFilters = fallback.filters ?? { include: [], exclude: [] };
263
+ const fallbackMatrix = fallback.matrix ?? defaultNotifications().matrix!;
264
+ const fallbackDigest = fallback.digest ?? defaultNotifications().digest!;
265
+
266
+ const raw = asRecord(value);
267
+ if (!raw) {
140
268
  return {
141
269
  ...fallback,
142
- webhook: fallback.webhook ? { ...fallback.webhook } : { enabled: false, url: "" },
270
+ webhook: { ...fallbackWebhook },
271
+ templates: { ...fallbackTemplates },
272
+ filters: {
273
+ include: [...fallbackFilters.include],
274
+ exclude: [...fallbackFilters.exclude],
275
+ },
276
+ matrix: { ...fallbackMatrix },
277
+ digest: { ...fallbackDigest },
143
278
  };
144
279
  }
145
280
 
146
- const raw = value as Partial<NotificationSettings> & { webhook?: unknown };
147
- const rawWebhook =
148
- raw.webhook && typeof raw.webhook === "object" && !Array.isArray(raw.webhook)
149
- ? (raw.webhook as Partial<WebhookNotificationSettings>)
150
- : undefined;
151
- const fallbackWebhook = fallback.webhook ?? { enabled: false, url: "" };
281
+ const rawWebhook = asRecord(raw.webhook);
282
+ const rawTemplates = asRecord(raw.templates);
283
+ const rawFilters = asRecord(raw.filters);
284
+ const rawMatrix = asRecord(raw.matrix);
285
+ const rawDigest = asRecord(raw.digest);
286
+
287
+ const frequency: DigestFrequency =
288
+ rawDigest?.frequency === "weekly" || rawDigest?.frequency === "daily"
289
+ ? rawDigest.frequency
290
+ : fallbackDigest.frequency;
291
+
292
+ const lastSentAt =
293
+ typeof rawDigest?.lastSentAt === "string" && rawDigest.lastSentAt.trim()
294
+ ? rawDigest.lastSentAt.trim()
295
+ : null;
152
296
 
153
297
  return {
154
298
  enabled: typeof raw.enabled === "boolean" ? raw.enabled : fallback.enabled,
@@ -163,6 +307,67 @@ function normalizeNotifications(
163
307
  typeof rawWebhook?.url === "string"
164
308
  ? rawWebhook.url.trim()
165
309
  : fallbackWebhook.url,
310
+ timeoutMs: normalizeIntInRange(
311
+ rawWebhook?.timeoutMs,
312
+ fallbackWebhook.timeoutMs,
313
+ 1_000,
314
+ 120_000
315
+ ),
316
+ retryCount: normalizeIntInRange(
317
+ rawWebhook?.retryCount,
318
+ fallbackWebhook.retryCount,
319
+ 0,
320
+ 5
321
+ ),
322
+ retryDelayMs: normalizeIntInRange(
323
+ rawWebhook?.retryDelayMs,
324
+ fallbackWebhook.retryDelayMs,
325
+ 100,
326
+ 60_000
327
+ ),
328
+ },
329
+ templates: {
330
+ success:
331
+ typeof rawTemplates?.success === "string" && rawTemplates.success.trim()
332
+ ? rawTemplates.success
333
+ : fallbackTemplates.success,
334
+ error:
335
+ typeof rawTemplates?.error === "string" && rawTemplates.error.trim()
336
+ ? rawTemplates.error
337
+ : fallbackTemplates.error,
338
+ },
339
+ filters: {
340
+ include: normalizeNameList(rawFilters?.include, fallbackFilters.include),
341
+ exclude: normalizeNameList(rawFilters?.exclude, fallbackFilters.exclude),
342
+ },
343
+ matrix: {
344
+ enabled:
345
+ typeof rawMatrix?.enabled === "boolean"
346
+ ? rawMatrix.enabled
347
+ : fallbackMatrix.enabled,
348
+ onPartial:
349
+ typeof rawMatrix?.onPartial === "boolean"
350
+ ? rawMatrix.onPartial
351
+ : fallbackMatrix.onPartial,
352
+ onAllFailed:
353
+ typeof rawMatrix?.onAllFailed === "boolean"
354
+ ? rawMatrix.onAllFailed
355
+ : fallbackMatrix.onAllFailed,
356
+ stuckAfterMinutes: normalizeIntInRange(
357
+ rawMatrix?.stuckAfterMinutes,
358
+ fallbackMatrix.stuckAfterMinutes,
359
+ 0,
360
+ 10_080
361
+ ),
362
+ },
363
+ digest: {
364
+ enabled:
365
+ typeof rawDigest?.enabled === "boolean"
366
+ ? rawDigest.enabled
367
+ : fallbackDigest.enabled,
368
+ frequency,
369
+ time: normalizeDailyTime(rawDigest?.time, fallbackDigest.time),
370
+ lastSentAt,
166
371
  },
167
372
  };
168
373
  }
@@ -7,6 +7,7 @@ import {
7
7
  saveTask,
8
8
  deleteTask,
9
9
  } from "./db/tasks-repo.js";
10
+ import { isValidIanaTimeZone, validateLaunchWindow } from "./core/schedule-v2.js";
10
11
 
11
12
  /** Триггер задачи по событию из MCP-шины. */
12
13
  export interface McpEventTrigger {
@@ -140,6 +141,19 @@ export interface TaskDefinition {
140
141
  matrixQueue?: string[];
141
142
  /** Для родителя матрицы — true (флаг для фильтров/DAG). */
142
143
  isMatrixParent?: boolean;
144
+ /**
145
+ * IANA-часовой пояс задачи (Спринт 19), например "Europe/Moscow".
146
+ * Не задан — системный пояс. Если отличается от системного, задача
147
+ * регистрируется в poll-режиме: ОС будит её каждую минуту, а cron
148
+ * проверяется в обёртке с учётом этого пояса.
149
+ */
150
+ timezone?: string;
151
+ /** Начало окна запуска "HH:MM" (Спринт 19); вне окна запуск переносится. */
152
+ notBefore?: string;
153
+ /** Конец окна запуска "HH:MM"; может быть меньше notBefore (через полночь). */
154
+ notAfter?: string;
155
+ /** Пауза до даты (ISO, Спринт 19): плагин включит задачу автоматически. */
156
+ pausedUntil?: string;
143
157
  /** Когда задача была создана — защита от ложного catch-up сразу после создания. */
144
158
  createdAt?: string;
145
159
  }
@@ -266,6 +280,10 @@ export async function buildExportJson(
266
280
  ? { triggerType: "mcp-event" as const }
267
281
  : {}),
268
282
  ...(definition?.watchPath ? { watchPath: definition.watchPath } : {}),
283
+ ...(definition?.timezone ? { timezone: definition.timezone } : {}),
284
+ ...(definition?.notBefore ? { notBefore: definition.notBefore } : {}),
285
+ ...(definition?.notAfter ? { notAfter: definition.notAfter } : {}),
286
+ ...(definition?.pausedUntil ? { pausedUntil: definition.pausedUntil } : {}),
269
287
  ...(Array.isArray(definition?.allowedTools) && definition.allowedTools.length > 0
270
288
  ? { allowedTools: definition.allowedTools }
271
289
  : {}),
@@ -442,6 +460,28 @@ export function parseImportJson(raw: string): ParsedImport {
442
460
  const priority = normalizePriority(source.priority);
443
461
  const workspaceId = readOptionalString(source.workspaceId);
444
462
 
463
+ // Планирование 2.0 (Спринт 19): IANA-зона, окно запуска, пауза до даты.
464
+ const timezone = readOptionalString(source.timezone);
465
+ if (timezone && !isValidIanaTimeZone(timezone)) {
466
+ errors.push(
467
+ `Запись ${position}${name ? ` (${name})` : ""}: неизвестный часовой пояс ` +
468
+ `«${timezone}» (нужна IANA-зона, например Europe/Moscow).`
469
+ );
470
+ }
471
+ const notBefore = readOptionalString(source.notBefore);
472
+ const notAfter = readOptionalString(source.notAfter);
473
+ const windowError = validateLaunchWindow(notBefore, notAfter);
474
+ if (windowError) {
475
+ errors.push(`Запись ${position}${name ? ` (${name})` : ""}: ${windowError}`);
476
+ }
477
+ const pausedUntil = readOptionalString(source.pausedUntil);
478
+ if (pausedUntil && Number.isNaN(Date.parse(pausedUntil))) {
479
+ errors.push(
480
+ `Запись ${position}${name ? ` (${name})` : ""}: pausedUntil должен быть ` +
481
+ `датой в формате ISO (например 2026-12-01T09:00:00Z).`
482
+ );
483
+ }
484
+
445
485
  // Ограничения инструментов (Спринт 14): массив непустых строк без дублей.
446
486
  // Пустой allowedTools отклоняется с явной ошибкой (избегаем «запрещено всё»).
447
487
  const readToolList = (raw: unknown, fieldLabel: string): string[] | undefined | "empty" => {
@@ -636,6 +676,10 @@ export function parseImportJson(raw: string): ParsedImport {
636
676
  ...(dependsOn !== undefined ? { dependsOn } : {}),
637
677
  ...(triggerType === "cron" ? {} : { triggerType }),
638
678
  ...(watchPath ? { watchPath } : {}),
679
+ ...(timezone !== undefined ? { timezone } : {}),
680
+ ...(notBefore !== undefined ? { notBefore } : {}),
681
+ ...(notAfter !== undefined ? { notAfter } : {}),
682
+ ...(pausedUntil !== undefined ? { pausedUntil } : {}),
639
683
  ...(mcpEvent ? { mcpEvent } : {}),
640
684
  ...(allowedTools !== undefined ? { allowedTools } : {}),
641
685
  ...(deniedTools !== undefined ? { deniedTools } : {}),
package/src/types.ts 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
  /** Префикс всех задач плагина (историческое имя, сохраняется для совместимости). */
6
6
  export const TASK_PREFIX = "OpenCode\\windows-scheduler";
@@ -15,20 +15,10 @@ export const TASK_FOLDER_NAME = "windows-scheduler";
15
15
  * Windows: %APPDATA%\opencode\windows-scheduler (как раньше — без миграции).
16
16
  * macOS/Linux: $XDG_CONFIG_HOME/opencode/windows-scheduler или
17
17
  * ~/.config/opencode/windows-scheduler.
18
+ * Спринт 21: директория зависит от активного профиля (см. src/profiles.ts).
18
19
  */
19
20
  function resolvePluginDir(): string {
20
- // Explicit override (tests, custom installations). Takes precedence on every platform.
21
- const custom = process.env.OPENCODE_SCHEDULER_HOME?.trim();
22
- if (custom) return path.resolve(custom);
23
-
24
- if (process.platform === "win32") {
25
- const base = process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming");
26
- return path.join(base, "opencode", TASK_FOLDER_NAME);
27
- }
28
-
29
- const configHome =
30
- process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
31
- return path.join(configHome, "opencode", TASK_FOLDER_NAME);
21
+ return getProfileDir(getProfileName());
32
22
  }
33
23
 
34
24
  export const PLUGIN_DIR = resolvePluginDir();
package/src/workspaces.ts CHANGED
@@ -1,6 +1,6 @@
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";
@@ -18,6 +18,10 @@ export interface Workspace {
18
18
  path: string;
19
19
  gitRemote?: string;
20
20
  color?: string;
21
+ /** Env-переменные workspace (Спринт 21). Значения хранятся как есть. */
22
+ env?: Record<string, string>;
23
+ /** Путь к .env-файлу, переменные которого подмешиваются к env (Спринт 21). */
24
+ envFile?: string;
21
25
  createdAt: string;
22
26
  }
23
27
 
@@ -25,6 +29,8 @@ export interface AddWorkspaceInput {
25
29
  name?: string;
26
30
  path: string;
27
31
  color?: string;
32
+ env?: Record<string, string> | null;
33
+ envFile?: string | null;
28
34
  }
29
35
 
30
36
  export interface UpdateWorkspacePatch {
@@ -32,8 +38,13 @@ export interface UpdateWorkspacePatch {
32
38
  path?: string;
33
39
  color?: string;
34
40
  gitRemote?: string | null;
41
+ env?: Record<string, string> | null;
42
+ envFile?: string | null;
35
43
  }
36
44
 
45
+ /** Максимум пар env на workspace — защита от раздувания строки JSON. */
46
+ export const MAX_WORKSPACE_ENV_PAIRS = 100;
47
+
37
48
  /** Палитра цветных маркеров для GUI/дашборда. */
38
49
  export const WORKSPACE_COLORS = [
39
50
  "#5b8def",
@@ -44,13 +55,175 @@ export const WORKSPACE_COLORS = [
44
55
  "#3aa8b8",
45
56
  ];
46
57
 
58
+ const ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
59
+
60
+ /**
61
+ * Нормализует пары env: ключи — валидные имена переменных, значения — строки.
62
+ * Бросает понятную ошибку при нарушении (её показывает GUI/RPC).
63
+ */
64
+ export function normalizeWorkspaceEnv(
65
+ value: unknown
66
+ ): Record<string, string> | undefined {
67
+ if (value == null) return undefined;
68
+ if (typeof value !== "object" || Array.isArray(value)) {
69
+ throw new Error("env должен быть объектом «ключ → значение».");
70
+ }
71
+ const entries = Object.entries(value as Record<string, unknown>);
72
+ if (entries.length > MAX_WORKSPACE_ENV_PAIRS) {
73
+ throw new Error(
74
+ `Слишком много env-переменных: ${entries.length} (максимум ${MAX_WORKSPACE_ENV_PAIRS}).`
75
+ );
76
+ }
77
+ const result: Record<string, string> = {};
78
+ for (const [rawKey, rawValue] of entries) {
79
+ const key = String(rawKey).trim();
80
+ if (!ENV_KEY_RE.test(key)) {
81
+ throw new Error(
82
+ `Недопустимое имя env-переменной '${rawKey}': нужны латиница, цифры и '_', не с цифры.`
83
+ );
84
+ }
85
+ if (rawValue == null) {
86
+ result[key] = "";
87
+ continue;
88
+ }
89
+ if (typeof rawValue === "object") {
90
+ throw new Error(`Значение env '${key}' должно быть строкой.`);
91
+ }
92
+ result[key] = String(rawValue);
93
+ }
94
+ return result;
95
+ }
96
+
97
+ /**
98
+ * Разбирает содержимое .env: строки KEY=VALUE, комментарии `#`, пустые строки,
99
+ * префикс `export `, кавычки вокруг значения снимаются.
100
+ */
101
+ export function parseEnvFileContent(content: string): Record<string, string> {
102
+ const result: Record<string, string> = {};
103
+ for (const line of String(content).split(/\r?\n/)) {
104
+ const trimmed = line.trim();
105
+ if (!trimmed || trimmed.startsWith("#")) continue;
106
+ const withoutExport = trimmed.startsWith("export ")
107
+ ? trimmed.slice("export ".length).trim()
108
+ : trimmed;
109
+ const eq = withoutExport.indexOf("=");
110
+ if (eq <= 0) continue;
111
+ const key = withoutExport.slice(0, eq).trim();
112
+ if (!ENV_KEY_RE.test(key)) continue;
113
+ let value = withoutExport.slice(eq + 1).trim();
114
+ if (
115
+ (value.startsWith('"') && value.endsWith('"') && value.length >= 2) ||
116
+ (value.startsWith("'") && value.endsWith("'") && value.length >= 2)
117
+ ) {
118
+ value = value.slice(1, -1);
119
+ }
120
+ result[key] = value;
121
+ }
122
+ return result;
123
+ }
124
+
125
+ /** Читает .env-файл workspace (если он задан и существует). */
126
+ export function readWorkspaceEnvFile(envFile?: string): Record<string, string> {
127
+ if (!envFile) return {};
128
+ try {
129
+ return parseEnvFileContent(readFileSync(envFile, "utf8"));
130
+ } catch {
131
+ return {};
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Итоговые env-переменные workspace: сначала .env-файл, затем явные пары
137
+ * (пары важнее файла). Никогда не бросает.
138
+ */
139
+ export function resolveWorkspaceEnv(workspace: Workspace | undefined): Record<string, string> {
140
+ if (!workspace) return {};
141
+ return {
142
+ ...readWorkspaceEnvFile(workspace.envFile),
143
+ ...(workspace.env ?? {}),
144
+ };
145
+ }
146
+
147
+ /** Маскирует значение секрета для логов. */
148
+ export function maskSecretValue(): string {
149
+ return "***";
150
+ }
151
+
152
+ const SECRET_KEY_RE = /(TOKEN|SECRET|PASS|PASSWORD|KEY|CREDENTIAL|AUTH)/i;
153
+
154
+ /** Копия env для логов: значения «секретных» ключей заменены на ***. */
155
+ export function maskEnvForLog(env: Record<string, string> | undefined): Record<string, string> {
156
+ if (!env) return {};
157
+ const masked: Record<string, string> = {};
158
+ for (const [key, value] of Object.entries(env)) {
159
+ masked[key] = SECRET_KEY_RE.test(key) ? maskSecretValue() : value;
160
+ }
161
+ return masked;
162
+ }
163
+
164
+ /**
165
+ * Каталог env-файлов задач внутри каталога плагина (по одному файлу на задачу).
166
+ * Файлы содержат реальные значения и не попадают в git/логи.
167
+ */
168
+ export function workspaceEnvDir(pluginDir: string): string {
169
+ return join(pluginDir, "env");
170
+ }
171
+
172
+ /**
173
+ * Пишет env-файл задачи в формате KEY=VALUE (Спринт 21).
174
+ *
175
+ * Возвращает путь к файлу или undefined, если у workspace нет переменных.
176
+ * Пустой env удаляет ранее созданный файл. На POSIX права 0600.
177
+ */
178
+ export function writeWorkspaceEnvFile(
179
+ workspace: Workspace | undefined,
180
+ pluginDir: string,
181
+ sanitizedName: string
182
+ ): string | undefined {
183
+ const file = join(workspaceEnvDir(pluginDir), `${sanitizedName}.env`);
184
+ const env = resolveWorkspaceEnv(workspace);
185
+ const keys = Object.keys(env);
186
+ if (!keys.length) {
187
+ try {
188
+ rmSync(file, { force: true });
189
+ } catch {
190
+ // нечего удалять — не ошибка
191
+ }
192
+ return undefined;
193
+ }
194
+ const body =
195
+ keys
196
+ .map((key) => `${key}=${String(env[key]).replace(/\r?\n/g, " ")}`)
197
+ .join("\n") + "\n";
198
+ mkdirSync(workspaceEnvDir(pluginDir), { recursive: true });
199
+ writeFileSync(file, body, { encoding: "utf8", mode: 0o600 });
200
+ if (process.platform !== "win32") {
201
+ try {
202
+ chmodSync(file, 0o600);
203
+ } catch {
204
+ // права не критичны для работы задачи
205
+ }
206
+ }
207
+ return file;
208
+ }
209
+
47
210
  function rowToWorkspace(row: any): Workspace {
211
+ let env: Record<string, string> | undefined;
212
+ if (row.env_json) {
213
+ try {
214
+ env = normalizeWorkspaceEnv(JSON.parse(String(row.env_json)));
215
+ } catch {
216
+ env = undefined;
217
+ }
218
+ }
48
219
  return {
49
220
  id: String(row.id),
50
221
  name: String(row.name),
51
222
  path: String(row.path),
52
223
  gitRemote: row.git_remote == null ? undefined : String(row.git_remote),
53
224
  color: row.color == null ? undefined : String(row.color),
225
+ env,
226
+ envFile: row.env_file == null ? undefined : String(row.env_file),
54
227
  createdAt: String(row.created_at),
55
228
  };
56
229
  }
@@ -152,15 +325,26 @@ export function addWorkspace(input: AddWorkspaceInput): Workspace {
152
325
  WORKSPACE_COLORS[listWorkspaces().length % WORKSPACE_COLORS.length];
153
326
  const createdAt = new Date().toISOString();
154
327
  const gitRemote = readGitRemote(workspacePath);
328
+ const env = normalizeWorkspaceEnv(input.env);
329
+ const envFile = input.envFile?.trim() || undefined;
155
330
 
156
331
  getDb()
157
332
  .prepare(
158
- `INSERT INTO workspaces (id, name, path, git_remote, color, created_at)
159
- VALUES (?, ?, ?, ?, ?, ?)`
333
+ `INSERT INTO workspaces (id, name, path, git_remote, color, env_json, env_file, created_at)
334
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
160
335
  )
161
- .run(id, name, workspacePath, gitRemote ?? null, color, createdAt);
336
+ .run(
337
+ id,
338
+ name,
339
+ workspacePath,
340
+ gitRemote ?? null,
341
+ color,
342
+ env ? JSON.stringify(env) : null,
343
+ envFile ?? null,
344
+ createdAt
345
+ );
162
346
 
163
- return { id, name, path: workspacePath, gitRemote, color, createdAt };
347
+ return { id, name, path: workspacePath, gitRemote, color, env, envFile, createdAt };
164
348
  }
165
349
 
166
350
  /** Обновляет имя/путь/цвет workspace. */
@@ -191,12 +375,32 @@ export function updateWorkspace(id: string, patch: UpdateWorkspacePatch): Worksp
191
375
  : nextPath !== existing.path
192
376
  ? readGitRemote(nextPath)
193
377
  : existing.gitRemote;
378
+ const nextEnv =
379
+ patch.env === null
380
+ ? undefined
381
+ : patch.env !== undefined
382
+ ? normalizeWorkspaceEnv(patch.env)
383
+ : existing.env;
384
+ const nextEnvFile =
385
+ patch.envFile === null
386
+ ? undefined
387
+ : patch.envFile !== undefined
388
+ ? patch.envFile.trim() || undefined
389
+ : existing.envFile;
194
390
 
195
391
  getDb()
196
392
  .prepare(
197
- "UPDATE workspaces SET name = ?, path = ?, git_remote = ?, color = ? WHERE id = ?"
393
+ "UPDATE workspaces SET name = ?, path = ?, git_remote = ?, color = ?, env_json = ?, env_file = ? WHERE id = ?"
198
394
  )
199
- .run(nextName, nextPath, nextRemote ?? null, nextColor ?? null, id);
395
+ .run(
396
+ nextName,
397
+ nextPath,
398
+ nextRemote ?? null,
399
+ nextColor ?? null,
400
+ nextEnv ? JSON.stringify(nextEnv) : null,
401
+ nextEnvFile ?? null,
402
+ id
403
+ );
200
404
 
201
405
  return {
202
406
  id,
@@ -204,6 +408,8 @@ export function updateWorkspace(id: string, patch: UpdateWorkspacePatch): Worksp
204
408
  path: nextPath,
205
409
  gitRemote: nextRemote,
206
410
  color: nextColor,
411
+ env: nextEnv,
412
+ envFile: nextEnvFile,
207
413
  createdAt: existing.createdAt,
208
414
  };
209
415
  }