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
@@ -0,0 +1,253 @@
1
+ import crypto from "node:crypto";
2
+ import type http from "node:http";
3
+ import type { HookSettings } from "./settings.js";
4
+
5
+ /**
6
+ * Входящие webhook-триггеры (Спринт 22).
7
+ *
8
+ * Контракт:
9
+ * POST /api/hooks/<task>?token=<token>
10
+ * X-Scheduler-Signature: sha256=<hex hmac по сырому телу>
11
+ * X-Scheduler-Timestamp: <unix seconds|milliseconds> (необязательно)
12
+ *
13
+ * Для совместимости с GitHub Actions принимается также `X-Hub-Signature-256`,
14
+ * для GitLab — `X-Gitlab-Token` вместо query-параметра.
15
+ *
16
+ * HMAC считается по **сырому телу** запроса (без нормализации JSON), поэтому
17
+ * отправитель должен подписывать ровно те байты, которые кладёт в body.
18
+ */
19
+
20
+ /** Заголовки, в которых может прийти HMAC-подпись. */
21
+ const SIGNATURE_HEADERS = [
22
+ "x-scheduler-signature",
23
+ "x-hub-signature-256",
24
+ "x-signature-256",
25
+ ] as const;
26
+
27
+ /** Заголовки, в которых может прийти токен (альтернатива query-параметру). */
28
+ const TOKEN_HEADERS = ["x-scheduler-token", "x-gitlab-token"] as const;
29
+
30
+ type HeaderMap = Record<string, string | string[] | undefined>;
31
+
32
+ /** Первое значение заголовка (Node может вернуть массив). */
33
+ function firstHeader(value: string | string[] | undefined): string | null {
34
+ if (Array.isArray(value)) return value.length > 0 ? String(value[0]) : null;
35
+ return typeof value === "string" && value.trim() ? value.trim() : null;
36
+ }
37
+
38
+ /** Сравнение строк без утечки длины через раннее завершение. */
39
+ export function timingSafeStringEqual(expected: string, provided: string): boolean {
40
+ if (typeof expected !== "string" || typeof provided !== "string") return false;
41
+ if (!expected || !provided) return false;
42
+ const expectedHash = crypto.createHash("sha256").update(expected, "utf8").digest();
43
+ const providedHash = crypto.createHash("sha256").update(provided, "utf8").digest();
44
+ const equal = crypto.timingSafeEqual(expectedHash, providedHash);
45
+ return equal && expected.length === provided.length;
46
+ }
47
+
48
+ /** Проверяет токен из query-параметра или заголовка. */
49
+ export function verifyHookToken(expected: string, provided: string | null): boolean {
50
+ return typeof provided === "string" && timingSafeStringEqual(expected, provided);
51
+ }
52
+
53
+ /** Считает HMAC-SHA256 по сырому телу и возвращает значение в формате `sha256=<hex>`. */
54
+ export function signHookPayload(secret: string, body: Buffer | string): string {
55
+ const payload = Buffer.isBuffer(body) ? body : Buffer.from(body, "utf8");
56
+ const digest = crypto.createHmac("sha256", secret).update(payload).digest("hex");
57
+ return `sha256=${digest}`;
58
+ }
59
+
60
+ /** Достаёт подпись из поддерживаемых заголовков. */
61
+ export function extractHookSignature(headers: HeaderMap): string | null {
62
+ for (const name of SIGNATURE_HEADERS) {
63
+ const value = firstHeader(headers[name]);
64
+ if (value) return value;
65
+ }
66
+ return null;
67
+ }
68
+
69
+ /** Достаёт токен из поддерживаемых заголовков (если нет query-параметра). */
70
+ export function extractHookToken(headers: HeaderMap): string | null {
71
+ for (const name of TOKEN_HEADERS) {
72
+ const value = firstHeader(headers[name]);
73
+ if (value) return value;
74
+ }
75
+ return null;
76
+ }
77
+
78
+ /**
79
+ * Проверяет HMAC-подпись. Принимает `sha256=<hex>` и «голый» hex;
80
+ * алгоритмы кроме SHA-256 намеренно не поддерживаются.
81
+ */
82
+ export function verifyHookSignature(
83
+ secret: string,
84
+ body: Buffer | string,
85
+ signature: string | null
86
+ ): boolean {
87
+ if (!secret || !signature) return false;
88
+ const normalized = signature.trim();
89
+ if (!/^sha256=/i.test(normalized) && !/^[a-f0-9]{64}$/i.test(normalized)) {
90
+ return false;
91
+ }
92
+ const provided = normalized.replace(/^sha256=/i, "").trim().toLowerCase();
93
+ if (!/^[a-f0-9]{64}$/.test(provided)) return false;
94
+ const expected = signHookPayload(secret, body).replace(/^sha256=/, "");
95
+ return timingSafeStringEqual(expected, provided);
96
+ }
97
+
98
+ /**
99
+ * Проверяет необязательный timestamp против текущего времени.
100
+ * 0 в настройках — проверка выключена. Без заголовка запрос разрешён.
101
+ */
102
+ export function verifyHookTimestamp(
103
+ value: string | null,
104
+ toleranceSeconds: number,
105
+ nowMs = Date.now()
106
+ ): { ok: boolean; reason?: string } {
107
+ if (!value || toleranceSeconds <= 0) return { ok: true };
108
+ const trimmed = value.trim();
109
+ if (!/^\d+$/.test(trimmed)) {
110
+ return { ok: false, reason: "Некорректный X-Scheduler-Timestamp." };
111
+ }
112
+ const numeric = Number(trimmed);
113
+ if (!Number.isFinite(numeric)) {
114
+ return { ok: false, reason: "Некорректный X-Scheduler-Timestamp." };
115
+ }
116
+ // Значения больше 1e12 трактуем как миллисекунды, иначе — как секунды.
117
+ const timestampMs = numeric > 1e12 ? numeric : numeric * 1000;
118
+ const skewMs = Math.abs(nowMs - timestampMs);
119
+ if (skewMs > toleranceSeconds * 1000) {
120
+ return {
121
+ ok: false,
122
+ reason: `Timestamp вне допустимого окна (±${toleranceSeconds} с).`,
123
+ };
124
+ }
125
+ return { ok: true };
126
+ }
127
+
128
+ export interface HookAuthInput {
129
+ settings: HookSettings;
130
+ token: string | null;
131
+ signature: string | null;
132
+ timestamp: string | null;
133
+ /** Сырое тело запроса — ровно те байты, по которым считался HMAC. */
134
+ body: Buffer;
135
+ /** Текущее время (для тестов). */
136
+ nowMs?: number;
137
+ }
138
+
139
+ export interface HookAuthResult {
140
+ ok: boolean;
141
+ /** HTTP-статус для отказа (200 при успехе). */
142
+ status: number;
143
+ error?: string;
144
+ }
145
+
146
+ /**
147
+ * Полная проверка входящего хука: включён ли канал, токен, HMAC, timestamp.
148
+ * Возвращает понятную ошибку на русском для ответа и логов.
149
+ */
150
+ export function authenticateHookRequest(input: HookAuthInput): HookAuthResult {
151
+ const { settings } = input;
152
+ if (!settings.enabled) {
153
+ return { ok: false, status: 403, error: "Входящие webhook-триггеры отключены." };
154
+ }
155
+ if (!settings.token) {
156
+ return {
157
+ ok: false,
158
+ status: 403,
159
+ error: "В настройках не задан token для входящих хуков.",
160
+ };
161
+ }
162
+ if (!verifyHookToken(settings.token, input.token)) {
163
+ return { ok: false, status: 401, error: "Неверный token." };
164
+ }
165
+ if (settings.requireSignature) {
166
+ if (!settings.secret) {
167
+ return {
168
+ ok: false,
169
+ status: 403,
170
+ error: "В настройках не задан secret для HMAC-подписи.",
171
+ };
172
+ }
173
+ if (!input.signature) {
174
+ return {
175
+ ok: false,
176
+ status: 401,
177
+ error: "Не передана HMAC-подпись (X-Scheduler-Signature).",
178
+ };
179
+ }
180
+ if (!verifyHookSignature(settings.secret, input.body, input.signature)) {
181
+ return { ok: false, status: 401, error: "Неверная HMAC-подпись." };
182
+ }
183
+ }
184
+ const timestamp = verifyHookTimestamp(
185
+ input.timestamp,
186
+ settings.timestampToleranceSeconds,
187
+ input.nowMs
188
+ );
189
+ if (!timestamp.ok) {
190
+ return { ok: false, status: 401, error: timestamp.reason };
191
+ }
192
+ return { ok: true, status: 200 };
193
+ }
194
+
195
+ export type BodyReadResult =
196
+ | { ok: true; body: Buffer }
197
+ | { ok: false; status: number; error: string };
198
+
199
+ /**
200
+ * Читает тело запроса с ограничением размера.
201
+ *
202
+ * Лишние байты не накапливаются в памяти: после превышения лимита поток
203
+ * дочитывается и отбрасывается, чтобы клиент получил внятный 413, а не reset.
204
+ */
205
+ export function readRequestBody(
206
+ req: http.IncomingMessage,
207
+ maxBytes: number
208
+ ): Promise<BodyReadResult> {
209
+ return new Promise((resolve) => {
210
+ const limit = Math.max(1, Math.floor(maxBytes) || 1);
211
+ let size = 0;
212
+ let tooLarge = false;
213
+ let settled = false;
214
+ const chunks: Buffer[] = [];
215
+
216
+ const finish = (result: BodyReadResult) => {
217
+ if (settled) return;
218
+ settled = true;
219
+ resolve(result);
220
+ };
221
+
222
+ req.on("data", (chunk: Buffer) => {
223
+ size += chunk.length;
224
+ if (tooLarge) return;
225
+ if (size > limit) {
226
+ tooLarge = true;
227
+ chunks.length = 0;
228
+ return;
229
+ }
230
+ chunks.push(chunk);
231
+ });
232
+ req.on("end", () => {
233
+ if (tooLarge) {
234
+ finish({
235
+ ok: false,
236
+ status: 413,
237
+ error: `Тело запроса больше ${limit} байт.`,
238
+ });
239
+ return;
240
+ }
241
+ finish({ ok: true, body: Buffer.concat(chunks) });
242
+ });
243
+ req.on("error", (err) => {
244
+ finish({
245
+ ok: false,
246
+ status: 400,
247
+ error: `Не удалось прочитать тело запроса: ${
248
+ err instanceof Error ? err.message : String(err)
249
+ }`,
250
+ });
251
+ });
252
+ });
253
+ }
package/src/rpc.ts CHANGED
@@ -81,8 +81,16 @@ const TaskItem = {
81
81
  beforeScript: { type: ["string", "null"] },
82
82
  /** Post-flight команда (null — не задана). */
83
83
  afterScript: { type: ["string", "null"] },
84
- /** Тип триггера: "cron" (по умолчанию), "file" или "mcp-event". */
84
+ /** Тип триггера: "cron" (по умолчанию), "file", "mcp-event" или "once". */
85
85
  triggerType: { type: ["string", "null"] },
86
+ /** Время разового запуска (triggerType === "once"), ISO-8601; null для остальных. */
87
+ runAt: { type: ["string", "null"] },
88
+ /** Режим сессии OpenCode (Спринт 24): "new" (по умолчанию), "reuse" (--session), "last" (--continue). */
89
+ session: { type: ["string", "null"] },
90
+ /** Идентификатор переиспользуемой сессии (только для session === "reuse"); null для остальных. */
91
+ sessionId: { type: ["string", "null"] },
92
+ /** Сколько запусков переживает reuse-сессия до ротации; null — без ограничения. */
93
+ sessionMaxRuns: { type: ["number", "null"] },
86
94
  /** Параметры MCP-события (null — не MCP-триггер). */
87
95
  mcpEvent: McpEventSchema,
88
96
  /** Путь к файлу/папке для файлового триггера. */
@@ -113,6 +121,18 @@ const TaskItem = {
113
121
  matrixParentId: { type: ["string", "null"] },
114
122
  /** true — задача является родителем матрицы. */
115
123
  isMatrixParent: { type: "boolean" },
124
+ /** true — задача поставлена на паузу (disabled в планировщике ОС). */
125
+ paused: { type: "boolean" },
126
+ /** true — определение есть в БД, но задачи нет в планировщике ОС. */
127
+ orphaned: { type: "boolean" },
128
+ /** Всего запусков именно этой задачи. */
129
+ runsTotal: { type: "number" },
130
+ /** Успешных запусков этой задачи. */
131
+ runsSuccess: { type: "number" },
132
+ /** Ошибок и таймаутов этой задачи. */
133
+ runsError: { type: "number" },
134
+ /** Частичных выполнений этой задачи (partial). */
135
+ runsPartial: { type: "number" },
116
136
  /** Агрегат по клонам для родителя (null — не матрица). */
117
137
  matrixSummary: {
118
138
  type: ["object", "null"],
@@ -172,8 +192,16 @@ const CreateTaskInput = {
172
192
  beforeScript: { type: "string" },
173
193
  /** Команда после запуска (post-flight). */
174
194
  afterScript: { type: "string" },
175
- /** Тип триггера: "cron" (по умолчанию), "file" или "mcp-event". */
195
+ /** Тип триггера: "cron" (по умолчанию; нужен schedule), "file", "mcp-event" или "once" (нужен runAt либо delaySeconds). */
176
196
  triggerType: { type: "string" },
197
+ /** Время разового запуска (triggerType === "once"), ISO-8601. Взаимоисключает schedule/newSchedule. */
198
+ runAt: { type: "string" },
199
+ /** Отложенный разовый запуск через N секунд (triggerType === "once"). Взаимоисключает runAt. */
200
+ delaySeconds: { type: "number" },
201
+ /** Режим сессии OpenCode (Спринт 24): "new" (по умолчанию), "reuse" (--session <id>), "last" (--continue). sessionId генерируется плагином. */
202
+ session: { type: "string" },
203
+ /** Сколько запусков переживает reuse-сессия до ротации (удаление и чистый старт). 0/не задано — без ограничения. */
204
+ sessionMaxRuns: { type: "number" },
177
205
  /** Параметры MCP-события. */
178
206
  mcpEvent: McpEventSchema,
179
207
  /** Путь к файлу/папке для файлового триггера. */
@@ -195,7 +223,7 @@ const CreateTaskInput = {
195
223
  /** Конец окна запуска "HH:MM"; может быть меньше notBefore (через полночь). */
196
224
  notAfter: { type: "string" },
197
225
  },
198
- required: ["name", "schedule", "prompt"],
226
+ required: ["name", "prompt"],
199
227
  } as const;
200
228
 
201
229
  const CreateTaskOutput = {
@@ -267,9 +295,12 @@ const HistoryRecord = {
267
295
  const GetHistoryInput = {
268
296
  type: "object" as const,
269
297
  properties: {
298
+ /** Сколько последних записей вернуть (по умолчанию 20, максимум 200). */
270
299
  limit: { type: "number" },
271
300
  /** Фильтр по имени задачи (регистр не важен). */
272
301
  taskName: { type: "string" },
302
+ /** Фильтр по статусу: success | error | partial | running | timeout. */
303
+ status: { type: "string" },
273
304
  },
274
305
  additionalProperties: false,
275
306
  } as const;
@@ -707,8 +738,16 @@ const UpdateTaskInput = {
707
738
  beforeScript: { type: "string" },
708
739
  /** Команда после запуска (post-flight). */
709
740
  afterScript: { type: "string" },
710
- /** Тип триггера: "cron" (по умолчанию), "file" или "mcp-event". */
741
+ /** Тип триггера: "cron" (по умолчанию; нужен schedule), "file", "mcp-event" или "once" (нужен runAt либо delaySeconds). */
711
742
  triggerType: { type: "string" },
743
+ /** Время разового запуска (triggerType === "once"), ISO-8601. Взаимоисключает schedule/newSchedule. */
744
+ runAt: { type: "string" },
745
+ /** Отложенный разовый запуск через N секунд (triggerType === "once"). Взаимоисключает runAt. */
746
+ delaySeconds: { type: "number" },
747
+ /** Режим сессии OpenCode (Спринт 24): "new" (по умолчанию), "reuse" (--session <id>), "last" (--continue). sessionId генерируется плагином. */
748
+ session: { type: "string" },
749
+ /** Сколько запусков переживает reuse-сессия до ротации (удаление и чистый старт). 0/не задано — без ограничения. */
750
+ sessionMaxRuns: { type: "number" },
712
751
  /** Параметры MCP-события. */
713
752
  mcpEvent: McpEventSchema,
714
753
  /** Путь к файлу/папке для файлового триггера. */