opencode-windows-scheduler 1.0.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 (93) hide show
  1. package/CHANGELOG.md +58 -7
  2. package/README.md +14 -4
  3. package/README.ru.md +14 -4
  4. package/ROADMAP.md +30 -20
  5. package/dist/core/analytics.d.ts +129 -0
  6. package/dist/core/analytics.d.ts.map +1 -0
  7. package/dist/core/analytics.js +286 -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/retention.d.ts +29 -0
  17. package/dist/core/retention.d.ts.map +1 -0
  18. package/dist/core/retention.js +98 -0
  19. package/dist/core/schedule-gate.d.ts +2 -0
  20. package/dist/core/schedule-gate.d.ts.map +1 -0
  21. package/dist/core/schedule-gate.js +182 -0
  22. package/dist/core/schedule-v2.d.ts +88 -0
  23. package/dist/core/schedule-v2.d.ts.map +1 -0
  24. package/dist/core/schedule-v2.js +496 -0
  25. package/dist/core/scheduler/types.d.ts +15 -0
  26. package/dist/core/scheduler/types.d.ts.map +1 -1
  27. package/dist/core/scheduler/windows.d.ts.map +1 -1
  28. package/dist/core/scheduler/windows.js +13 -1
  29. package/dist/core/wrappers/bash.d.ts +15 -0
  30. package/dist/core/wrappers/bash.d.ts.map +1 -1
  31. package/dist/core/wrappers/bash.js +44 -1
  32. package/dist/db/history-repo.d.ts +41 -0
  33. package/dist/db/history-repo.d.ts.map +1 -1
  34. package/dist/db/history-repo.js +78 -0
  35. package/dist/db/schema.d.ts +1 -1
  36. package/dist/db/schema.d.ts.map +1 -1
  37. package/dist/db/schema.js +11 -0
  38. package/dist/index.d.ts +117 -0
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +1094 -56
  41. package/dist/notifications.d.ts +112 -6
  42. package/dist/notifications.d.ts.map +1 -1
  43. package/dist/notifications.js +396 -34
  44. package/dist/profiles.d.ts +60 -0
  45. package/dist/profiles.d.ts.map +1 -0
  46. package/dist/profiles.js +209 -0
  47. package/dist/rpc.d.ts +645 -0
  48. package/dist/rpc.d.ts.map +1 -1
  49. package/dist/rpc.js +251 -2
  50. package/dist/server.d.ts.map +1 -1
  51. package/dist/server.js +200 -7
  52. package/dist/settings.d.ts +80 -0
  53. package/dist/settings.d.ts.map +1 -1
  54. package/dist/settings.js +159 -8
  55. package/dist/task-transfer.d.ts +13 -0
  56. package/dist/task-transfer.d.ts.map +1 -1
  57. package/dist/task-transfer.js +26 -0
  58. package/dist/types.d.ts.map +1 -1
  59. package/dist/types.js +3 -11
  60. package/dist/version.d.ts +8 -0
  61. package/dist/version.d.ts.map +1 -0
  62. package/dist/version.js +27 -0
  63. package/dist/workspaces.d.ts +43 -0
  64. package/dist/workspaces.d.ts.map +1 -1
  65. package/dist/workspaces.js +174 -8
  66. package/docs/ARCHITECTURE.md +45 -13
  67. package/docs/FEATURES.md +103 -12
  68. package/gui-experimental.cjs +4 -2
  69. package/package.json +8 -2
  70. package/src/core/analytics.ts +414 -0
  71. package/src/core/dry-run.ts +42 -0
  72. package/src/core/matrix.ts +10 -0
  73. package/src/core/ps-wrapper.ts +117 -3
  74. package/src/core/retention.ts +141 -0
  75. package/src/core/schedule-gate.ts +213 -0
  76. package/src/core/schedule-v2.ts +533 -0
  77. package/src/core/scheduler/types.ts +15 -0
  78. package/src/core/scheduler/windows.ts +13 -1
  79. package/src/core/wrappers/bash.ts +60 -0
  80. package/src/db/history-repo.ts +116 -0
  81. package/src/db/schema.ts +14 -0
  82. package/src/gui.tsx +3613 -2725
  83. package/src/index.ts +1325 -55
  84. package/src/notifications.ts +516 -40
  85. package/src/profiles.ts +236 -0
  86. package/src/rpc.ts +267 -2
  87. package/src/server.ts +226 -7
  88. package/src/settings.ts +285 -9
  89. package/src/task-transfer.ts +44 -0
  90. package/src/types.ts +3 -13
  91. package/src/version.ts +27 -0
  92. package/src/workspaces.ts +214 -8
  93. package/dist/gui-experimental.cjs +0 -1
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
  }
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("solid-js/web"),m=require("solid-js"),a=require("@opencode/plugin/gui");function p(r){switch(r){case"running":return"●";case"error":return"✗";case"success":return"✓";default:return"?"}}async function _(r){return[]}var $=e.template("<div style=padding:8px><h4>Планировщик Windows"),g=e.template("<p>Задач пока нет"),v=e.template("<ul>"),f=e.template("<li> ");const h=a.Plugin.define({setup(r){const[u,i]=m.createSignal([]);return _().then(i).catch(()=>i([])),r.add(a.Panel,{id:"scheduler-jobs",region:"side",list:()=>[{id:"jobs",title:"Планировщик",pinned:!0}],render:()=>(()=>{var s=$();return s.firstChild,e.insert(s,(()=>{var c=e.memo(()=>u().length===0);return()=>c()?g():(()=>{var l=v();return e.insert(l,()=>u().map(n=>(()=>{var t=f(),o=t.firstChild;return e.insert(t,()=>p(n.status),o),e.insert(t,()=>n.name,null),e.insert(t,(()=>{var d=e.memo(()=>!!n.nextRun);return()=>d()?` → ${n.nextRun}`:""})(),null),t})())),l})()})(),null),s})()})}});exports.default=h;