opencode-windows-scheduler 1.1.0 → 1.2.1

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 (144) hide show
  1. package/CHANGELOG.md +60 -1
  2. package/README.md +18 -8
  3. package/README.ru.md +13 -3
  4. package/ROADMAP-STRATEGY.md +2 -2
  5. package/ROADMAP.md +51 -18
  6. package/dist/core/analytics.d.ts +10 -0
  7. package/dist/core/analytics.d.ts.map +1 -1
  8. package/dist/core/analytics.js +21 -0
  9. package/dist/core/dry-run.d.ts +18 -1
  10. package/dist/core/dry-run.d.ts.map +1 -1
  11. package/dist/core/dry-run.js +49 -3
  12. package/dist/core/matrix.d.ts.map +1 -1
  13. package/dist/core/matrix.js +10 -0
  14. package/dist/core/one-shot.d.ts +62 -0
  15. package/dist/core/one-shot.d.ts.map +1 -0
  16. package/dist/core/one-shot.js +126 -0
  17. package/dist/core/otel.d.ts +4 -0
  18. package/dist/core/otel.d.ts.map +1 -0
  19. package/dist/core/otel.js +98 -0
  20. package/dist/core/prometheus.d.ts +23 -0
  21. package/dist/core/prometheus.d.ts.map +1 -0
  22. package/dist/core/prometheus.js +146 -0
  23. package/dist/core/ps-wrapper.d.ts +36 -2
  24. package/dist/core/ps-wrapper.d.ts.map +1 -1
  25. package/dist/core/ps-wrapper.js +124 -4
  26. package/dist/core/record-history.d.ts.map +1 -1
  27. package/dist/core/record-history.js +9 -0
  28. package/dist/core/schedule-gate.d.ts +2 -0
  29. package/dist/core/schedule-gate.d.ts.map +1 -0
  30. package/dist/core/schedule-gate.js +182 -0
  31. package/dist/core/schedule-v2.d.ts +88 -0
  32. package/dist/core/schedule-v2.d.ts.map +1 -0
  33. package/dist/core/schedule-v2.js +496 -0
  34. package/dist/core/scheduler/linux.d.ts +12 -3
  35. package/dist/core/scheduler/linux.d.ts.map +1 -1
  36. package/dist/core/scheduler/linux.js +80 -3
  37. package/dist/core/scheduler/mac.d.ts.map +1 -1
  38. package/dist/core/scheduler/mac.js +17 -3
  39. package/dist/core/scheduler/posix.d.ts.map +1 -1
  40. package/dist/core/scheduler/posix.js +3 -0
  41. package/dist/core/scheduler/registry.d.ts +4 -0
  42. package/dist/core/scheduler/registry.d.ts.map +1 -1
  43. package/dist/core/scheduler/types.d.ts +20 -3
  44. package/dist/core/scheduler/types.d.ts.map +1 -1
  45. package/dist/core/scheduler/windows.d.ts.map +1 -1
  46. package/dist/core/scheduler/windows.js +23 -2
  47. package/dist/core/session.d.ts +34 -0
  48. package/dist/core/session.d.ts.map +1 -0
  49. package/dist/core/session.js +105 -0
  50. package/dist/core/structured-log.d.ts +84 -0
  51. package/dist/core/structured-log.d.ts.map +1 -0
  52. package/dist/core/structured-log.js +137 -0
  53. package/dist/core/wrappers/bash.d.ts +24 -0
  54. package/dist/core/wrappers/bash.d.ts.map +1 -1
  55. package/dist/core/wrappers/bash.js +70 -3
  56. package/dist/db/history-repo.d.ts +8 -0
  57. package/dist/db/history-repo.d.ts.map +1 -1
  58. package/dist/db/history-repo.js +76 -6
  59. package/dist/db/metrics-repo.d.ts +3 -0
  60. package/dist/db/metrics-repo.d.ts.map +1 -1
  61. package/dist/db/metrics-repo.js +16 -8
  62. package/dist/db/migrate.d.ts.map +1 -1
  63. package/dist/db/migrate.js +8 -1
  64. package/dist/db/schema.d.ts +1 -1
  65. package/dist/db/schema.d.ts.map +1 -1
  66. package/dist/db/schema.js +19 -0
  67. package/dist/gui-experimental.cjs +1 -0
  68. package/dist/history.d.ts +7 -0
  69. package/dist/history.d.ts.map +1 -1
  70. package/dist/history.js +13 -0
  71. package/dist/index.d.ts +137 -1
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +1323 -78
  74. package/dist/integrations.d.ts +64 -0
  75. package/dist/integrations.d.ts.map +1 -0
  76. package/dist/integrations.js +205 -0
  77. package/dist/notifications.d.ts +112 -6
  78. package/dist/notifications.d.ts.map +1 -1
  79. package/dist/notifications.js +396 -34
  80. package/dist/profiles.d.ts +60 -0
  81. package/dist/profiles.d.ts.map +1 -0
  82. package/dist/profiles.js +209 -0
  83. package/dist/rpc.d.ts +592 -4
  84. package/dist/rpc.d.ts.map +1 -1
  85. package/dist/rpc.js +233 -6
  86. package/dist/server.d.ts +2 -0
  87. package/dist/server.d.ts.map +1 -1
  88. package/dist/server.js +473 -58
  89. package/dist/settings.d.ts +95 -0
  90. package/dist/settings.d.ts.map +1 -1
  91. package/dist/settings.js +186 -8
  92. package/dist/shared/jobs-view.d.ts +43 -5
  93. package/dist/shared/jobs-view.d.ts.map +1 -1
  94. package/dist/shared/jobs-view.js +125 -7
  95. package/dist/task-transfer.d.ts +32 -3
  96. package/dist/task-transfer.d.ts.map +1 -1
  97. package/dist/task-transfer.js +101 -3
  98. package/dist/types.d.ts.map +1 -1
  99. package/dist/types.js +3 -11
  100. package/dist/workspaces.d.ts +43 -0
  101. package/dist/workspaces.d.ts.map +1 -1
  102. package/dist/workspaces.js +174 -8
  103. package/docs/ARCHITECTURE.md +32 -12
  104. package/docs/FEATURES.md +186 -10
  105. package/gui-experimental.cjs +4 -2
  106. package/package.json +15 -2
  107. package/scripts/demo-dashboard.mjs +12 -2
  108. package/src/core/analytics.ts +36 -0
  109. package/src/core/dry-run.ts +65 -4
  110. package/src/core/matrix.ts +10 -0
  111. package/src/core/one-shot.ts +173 -0
  112. package/src/core/otel.ts +128 -0
  113. package/src/core/prometheus.ts +215 -0
  114. package/src/core/ps-wrapper.ts +144 -4
  115. package/src/core/record-history.ts +13 -0
  116. package/src/core/schedule-gate.ts +213 -0
  117. package/src/core/schedule-v2.ts +533 -0
  118. package/src/core/scheduler/linux.ts +90 -3
  119. package/src/core/scheduler/mac.ts +35 -4
  120. package/src/core/scheduler/posix.ts +3 -0
  121. package/src/core/scheduler/registry.ts +4 -0
  122. package/src/core/scheduler/types.ts +20 -3
  123. package/src/core/scheduler/windows.ts +24 -2
  124. package/src/core/session.ts +115 -0
  125. package/src/core/structured-log.ts +205 -0
  126. package/src/core/wrappers/bash.ts +98 -2
  127. package/src/db/history-repo.ts +90 -7
  128. package/src/db/metrics-repo.ts +19 -7
  129. package/src/db/migrate.ts +7 -1
  130. package/src/db/schema.ts +25 -0
  131. package/src/gui.tsx +3832 -2868
  132. package/src/history.ts +17 -0
  133. package/src/index.ts +1670 -117
  134. package/src/integrations.ts +253 -0
  135. package/src/notifications.ts +516 -40
  136. package/src/profiles.ts +236 -0
  137. package/src/rpc.ts +244 -6
  138. package/src/server.ts +506 -58
  139. package/src/settings.ts +336 -9
  140. package/src/shared/jobs-view.ts +158 -8
  141. package/src/task-transfer.ts +151 -5
  142. package/src/tui.tsx +290 -14
  143. package/src/types.ts +3 -13
  144. package/src/workspaces.ts +214 -8
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-windows-scheduler",
3
- "version": "1.1.0",
3
+ "version": "1.2.1",
4
4
  "description": "Local-first scheduling and orchestration for OpenCode v2 agent jobs: cron, DAG pipelines, matrix fan-out, quality gates and observability. Free and open source (MIT).",
5
5
  "license": "MIT",
6
6
  "author": "opencode-windows-scheduler contributors",
@@ -62,7 +62,7 @@
62
62
  "demo": "node scripts/demo-dashboard.mjs",
63
63
  "prepare": "npm run build",
64
64
  "prepublishOnly": "npm run build && npm run build:gui",
65
- "test": "node test-sqlite.mjs && node test-crash-recovery.mjs && node test-workspaces.mjs && node test-role-scoped.mjs && node test-dry-run.mjs && node test-matrix.mjs && node test-matrix-lifecycle.mjs && node test-matrix-sync.mjs && node test-retention.mjs && node test-metrics.mjs && node test-agent-tools.mjs && node test-skill.mjs && node test-docs.mjs",
65
+ "test": "node test-sqlite.mjs && node test-crash-recovery.mjs && node test-workspaces.mjs && node test-role-scoped.mjs && node test-dry-run.mjs && node test-matrix.mjs && node test-matrix-lifecycle.mjs && node test-matrix-sync.mjs && node test-retention.mjs && node test-metrics.mjs && node test-schedule-v2.mjs && node test-notifications-v2.mjs && node test-profiles.mjs && node test-env.mjs && node test-agent-tools.mjs && node test-skill.mjs && node test-integrations.mjs && node test-one-shot.mjs && node test-session-continuity.mjs && node test-task-status.mjs && node test-jobs-view.mjs && node test-dag.mjs && node test-dashboard.mjs && node test-dashboard-dag.mjs && node test-dashboard-json.mjs && node test-docs.mjs",
66
66
  "test:sqlite": "node test-sqlite.mjs",
67
67
  "test:crash": "node test-crash-recovery.mjs",
68
68
  "test:workspaces": "node test-workspaces.mjs",
@@ -73,8 +73,21 @@
73
73
  "test:matrix-sync": "node test-matrix-sync.mjs",
74
74
  "test:retention": "node test-retention.mjs",
75
75
  "test:metrics": "node test-metrics.mjs",
76
+ "test:schedule-v2": "node test-schedule-v2.mjs",
77
+ "test:notifications-v2": "node test-notifications-v2.mjs",
78
+ "test:profiles": "node test-profiles.mjs",
79
+ "test:env": "node test-env.mjs",
76
80
  "test:agent": "node test-agent-tools.mjs",
77
81
  "test:skill": "node test-skill.mjs",
82
+ "test:integrations": "node test-integrations.mjs",
83
+ "test:session-continuity": "node test-session-continuity.mjs",
84
+ "test:task-status": "node test-task-status.mjs",
85
+ "test:jobs-view": "node test-jobs-view.mjs",
86
+ "test:one-shot": "node test-one-shot.mjs",
87
+ "test:dag": "node test-dag.mjs",
88
+ "test:dashboard": "node test-dashboard.mjs",
89
+ "test:dashboard-dag": "node test-dashboard-dag.mjs",
90
+ "test:dashboard-json": "node test-dashboard-json.mjs",
78
91
  "test:docs": "node test-docs.mjs"
79
92
  },
80
93
  "dependencies": {
@@ -181,8 +181,18 @@ function taskView(definition) {
181
181
 
182
182
  const deps = {
183
183
  getTasks: async () => listTasks().map(taskView),
184
- runTask: async () => ({ alreadyRunning: false }),
185
- deleteTask: async () => {},
184
+ // Демо-режим ничего не меняет в системе: действия честно отвечают ошибкой,
185
+ // вместо того чтобы имитировать успех (раньше кнопки «молча работали»).
186
+ runTask: async () => {
187
+ throw new Error("Демо-режим: запуск задач отключён. Запустите плагин в OpenCode.");
188
+ },
189
+ deleteTask: async () => {
190
+ throw new Error("Демо-режим: удаление задач отключено. Запустите плагин в OpenCode.");
191
+ },
192
+ cancelMatrix: async () => {
193
+ throw new Error("Демо-режим: отмена матрицы недоступна. Запустите плагин в OpenCode.");
194
+ },
195
+ cleanupMatrixOrphans: async () => [],
186
196
  };
187
197
 
188
198
  const started = await startDashboardServer(deps, { preferred: preferredPort, fallback: preferredPort + 1000 });
@@ -72,6 +72,15 @@ export interface ModelAnalyticsRow {
72
72
  costUsd: number;
73
73
  }
74
74
 
75
+ /** Агрегат по тексту ошибки — топ ошибок для дайджеста (Спринт 20). */
76
+ export interface ErrorAnalyticsRow {
77
+ /** Текст ошибки (обрезан до 160 символов). */
78
+ message: string;
79
+ count: number;
80
+ /** Последнее появление (ISO). */
81
+ lastAt: string;
82
+ }
83
+
75
84
  export interface AnalyticsReport {
76
85
  generatedAt: string;
77
86
  /** Окно анализа в днях. */
@@ -91,6 +100,8 @@ export interface AnalyticsReport {
91
100
  topByCost: TaskAnalyticsRow[];
92
101
  matrices: MatrixAnalyticsRow[];
93
102
  byModel: ModelAnalyticsRow[];
103
+ /** Топ ошибок по частоте (Спринт 20). */
104
+ errors: ErrorAnalyticsRow[];
94
105
  sources: {
95
106
  historyRecords: number;
96
107
  /** Сколько записей попало в окно. */
@@ -171,6 +182,7 @@ export function buildAnalytics(
171
182
 
172
183
  const byTask = new Map<string, TaskAnalyticsRow>();
173
184
  const byModel = new Map<string, ModelAnalyticsRow>();
185
+ const byError = new Map<string, ErrorAnalyticsRow>();
174
186
  const cloneParent = new Map<string, string>();
175
187
  for (const task of options.tasks ?? []) {
176
188
  const parentId = task.matrixParentId?.trim();
@@ -253,6 +265,27 @@ export function buildAnalytics(
253
265
  modelRow.total += 1;
254
266
  modelRow.costUsd += cost;
255
267
  byModel.set(model, modelRow);
268
+
269
+ // Топ ошибок: группируем по тексту, чтобы дайджест показывал частые причины.
270
+ if (status !== "success" && status !== "partial") {
271
+ const message =
272
+ typeof record.error === "string" && record.error.trim()
273
+ ? record.error.trim().slice(0, 160)
274
+ : "(без текста)";
275
+ const errorRow = byError.get(message) ?? {
276
+ message,
277
+ count: 0,
278
+ lastAt: record.startedAt,
279
+ };
280
+ errorRow.count += 1;
281
+ if (
282
+ new Date(record.startedAt).getTime() >
283
+ new Date(errorRow.lastAt).getTime()
284
+ ) {
285
+ errorRow.lastAt = record.startedAt;
286
+ }
287
+ byError.set(message, errorRow);
288
+ }
256
289
  }
257
290
 
258
291
  const tasks = [...byTask.values()]
@@ -322,6 +355,9 @@ export function buildAnalytics(
322
355
  byModel: [...byModel.values()]
323
356
  .map((row) => ({ ...row, costUsd: Math.round(row.costUsd * 1e6) / 1e6 }))
324
357
  .sort((a, b) => b.costUsd - a.costUsd),
358
+ errors: [...byError.values()]
359
+ .sort((a, b) => b.count - a.count || a.message.localeCompare(b.message))
360
+ .slice(0, topLimit),
325
361
  sources: {
326
362
  historyRecords: records.length,
327
363
  recordsInWindow,
@@ -10,6 +10,7 @@ import { loadTaskDefinitions } from "../task-transfer.js";
10
10
  import { getHistory } from "../db/history-repo.js";
11
11
  import { getWorkspace } from "../workspaces.js";
12
12
  import { expandMatrixTask } from "./matrix.js";
13
+ import { nextRun } from "./schedule-v2.js";
13
14
  import type { TaskDefinition } from "../task-transfer.js";
14
15
 
15
16
  export interface DryRunRoleScoped {
@@ -20,7 +21,7 @@ export interface DryRunRoleScoped {
20
21
  export interface DryRunTaskItem {
21
22
  name: string;
22
23
  order: number;
23
- trigger: "manual" | "cron" | "dag";
24
+ trigger: "manual" | "cron" | "dag" | "once";
24
25
  cwd: string;
25
26
  command: string;
26
27
  workspace?: { name: string; path: string };
@@ -33,6 +34,23 @@ export interface DryRunTaskItem {
33
34
  estimatedTokens?: number | null;
34
35
  /** Для клона матрицы — имя родителя-шаблона (Спринт 15). */
35
36
  matrixParent?: string;
37
+ /** Режим сессии OpenCode (Спринт 24): new (по умолчанию), reuse, last. */
38
+ session?: string | null;
39
+ /** Идентификатор переиспользуемой сессии (только для session=reuse). */
40
+ sessionId?: string | null;
41
+ /**
42
+ * Эффективное расписание cron-задачи (Спринт 19): пояс, окно запуска и
43
+ * ближайшие срабатывания с учётом часового пояса. Позволяет проверить
44
+ * пересчёт cron до регистрации в ОС.
45
+ */
46
+ scheduleDetails?: {
47
+ cron: string;
48
+ timezone: string | null;
49
+ notBefore: string | null;
50
+ notAfter: string | null;
51
+ pausedUntil: string | null;
52
+ nextRuns: string[];
53
+ };
36
54
  }
37
55
 
38
56
  export interface DryRunTotals {
@@ -204,10 +222,13 @@ export async function simulatePipeline(taskName: string): Promise<DryRunReport>
204
222
 
205
223
  // Триггер: корневая задача (или клон корневой матрицы) — manual,
206
224
  // остальные попали в конвейер через dependsOn — dag.
225
+ const triggerType = def.triggerType ?? "cron";
207
226
  const trigger: DryRunTaskItem["trigger"] =
208
- lower === rootLower || (matrixParent && matrixParent.toLowerCase() === rootLower)
209
- ? "manual"
210
- : "dag";
227
+ triggerType === "once"
228
+ ? "once"
229
+ : lower === rootLower || (matrixParent && matrixParent.toLowerCase() === rootLower)
230
+ ? "manual"
231
+ : "dag";
211
232
 
212
233
  // Команда, которую выполнит обёртка.
213
234
  const modelArg = def.model ? ` --model ${def.model}` : "";
@@ -253,10 +274,49 @@ export async function simulatePipeline(taskName: string): Promise<DryRunReport>
253
274
  ? { allowed: undefined, denied: def.deniedTools }
254
275
  : null;
255
276
 
277
+ // Эффективное расписание cron-задачи (Спринт 19): ближайшие срабатывания
278
+ // считаем в часовом поясе задачи, чтобы dry-run показывал то же время, что
279
+ // увидит планировщик после регистрации.
280
+ let scheduleDetails: DryRunTaskItem["scheduleDetails"];
281
+ if (triggerType === "once" && def.runAt) {
282
+ // Для разовой задачи dry-run показывает единственное запланированное время.
283
+ scheduleDetails = {
284
+ cron: "once",
285
+ timezone: def.timezone ?? null,
286
+ notBefore: def.notBefore ?? null,
287
+ notAfter: def.notAfter ?? null,
288
+ pausedUntil: def.pausedUntil ?? null,
289
+ nextRuns: [def.runAt],
290
+ };
291
+ } else if (triggerType === "cron" && def.schedule) {
292
+ const runs: string[] = [];
293
+ try {
294
+ let cursor = new Date();
295
+ for (let i = 0; i < 3; i++) {
296
+ const next = nextRun(def.schedule, cursor, def.timezone);
297
+ if (!next) break;
298
+ runs.push(next.toISOString());
299
+ cursor = next;
300
+ }
301
+ } catch {
302
+ taskWarnings.push(`Не удалось разобрать cron "${def.schedule}" для расчёта ближайших запусков.`);
303
+ }
304
+ scheduleDetails = {
305
+ cron: def.schedule,
306
+ timezone: def.timezone ?? null,
307
+ notBefore: def.notBefore ?? null,
308
+ notAfter: def.notAfter ?? null,
309
+ pausedUntil: def.pausedUntil ?? null,
310
+ nextRuns: runs,
311
+ };
312
+ }
313
+
256
314
  tasks.push({
257
315
  name: def.name,
258
316
  order: index,
259
317
  trigger,
318
+ session: def.session ?? "new",
319
+ sessionId: def.session === "reuse" ? def.sessionId ?? null : null,
260
320
  cwd,
261
321
  command,
262
322
  workspace: workspace ? { name: workspace.name, path: workspace.path } : undefined,
@@ -268,6 +328,7 @@ export async function simulatePipeline(taskName: string): Promise<DryRunReport>
268
328
  estimatedCostUsd: estimatedCostUsd != null ? Math.round(estimatedCostUsd * 10000) / 10000 : null,
269
329
  estimatedTokens: estimatedTokens != null ? Math.round(estimatedTokens) : null,
270
330
  ...(matrixParent ? { matrixParent } : {}),
331
+ ...(scheduleDetails ? { scheduleDetails } : {}),
271
332
  });
272
333
 
273
334
  if (taskWarnings.length > 0) {
@@ -18,6 +18,7 @@ import {
18
18
  saveTask,
19
19
  } from "../db/tasks-repo.js";
20
20
  import { getHistory, recordRun } from "../db/history-repo.js";
21
+ import { notifyMatrixCompletion } from "../notifications.js";
21
22
  import { getWorkspace } from "../workspaces.js";
22
23
  import { createSchedulerBackend } from "./scheduler/index.js";
23
24
 
@@ -879,6 +880,15 @@ export async function finalizeMatrixIfComplete(
879
880
  "skipped",
880
881
  "skipped"
881
882
  );
883
+ // Спринт 20: уведомление о завершении матрицы (partial / все упали / успех).
884
+ void notifyMatrixCompletion({
885
+ parentName: parent.name,
886
+ status: finalStatus,
887
+ total: aggregate.totalCount,
888
+ success: aggregate.successCount,
889
+ error: aggregate.errorCount,
890
+ message: aggregate.message,
891
+ });
882
892
  } catch (err: any) {
883
893
  console.log(
884
894
  `[matrix] ${parent.name}: не удалось записать агрегат: ${
@@ -0,0 +1,173 @@
1
+ /**
2
+ * One-shot расписание (Спринт 23).
3
+ *
4
+ * Задача с triggerType "once" выполняется ровно один раз в момент runAt.
5
+ * Абсолютное время хранится в ISO-8601 (UTC), а delaySeconds — удобный
6
+ * способ задать его относительно момента создания.
7
+ *
8
+ * Модуль намеренно не зависит от планировщика ОС: здесь только нормализация
9
+ * времени и преобразование в родные форматы Windows/Linux/macOS. Это
10
+ * позволяет тестировать one-shot без создания реальных задач.
11
+ */
12
+
13
+ /** Максимальная задержка — 5 лет. Защита от опечаток вроде 999999999. */
14
+ export const MAX_ONESHOT_DELAY_SECONDS = 5 * 365 * 24 * 60 * 60;
15
+
16
+ /** Минимальная задержка — 1 секунда. */
17
+ export const MIN_ONESHOT_DELAY_SECONDS = 1;
18
+
19
+ export interface OneShotInput {
20
+ /** Абсолютное время запуска (ISO-8601). */
21
+ runAt?: unknown;
22
+ /** Задержка от текущего момента в секундах. */
23
+ delaySeconds?: unknown;
24
+ }
25
+
26
+ export type OneShotNormalization =
27
+ | {
28
+ ok: true;
29
+ /** Нормализованное абсолютное время в ISO-8601 (UTC). */
30
+ runAt: string;
31
+ /** Исходная задержка, если она была задана. */
32
+ delaySeconds?: number;
33
+ }
34
+ | { ok: false; error: string };
35
+
36
+ function asDelaySeconds(value: unknown): number | undefined | "invalid" {
37
+ if (value === undefined || value === null || value === "") return undefined;
38
+ if (typeof value !== "number" || !Number.isFinite(value)) return "invalid";
39
+ const seconds = Math.floor(value);
40
+ if (seconds < MIN_ONESHOT_DELAY_SECONDS || seconds > MAX_ONESHOT_DELAY_SECONDS) {
41
+ return "invalid";
42
+ }
43
+ return seconds;
44
+ }
45
+
46
+ /**
47
+ * Приводит runAt/delaySeconds к абсолютному ISO-времени.
48
+ *
49
+ * Если заданы оба поля, приоритет у runAt: delaySeconds сохраняется только
50
+ * как исходная подсказка. Так импорт экспортированной задачи с обоими полями
51
+ * не меняет момент запуска.
52
+ */
53
+ export function normalizeOneShotRunAt(
54
+ input: OneShotInput,
55
+ nowMs: number = Date.now()
56
+ ): OneShotNormalization {
57
+ const rawRunAt =
58
+ typeof input.runAt === "string" ? input.runAt.trim() : undefined;
59
+ const delaySeconds = asDelaySeconds(input.delaySeconds);
60
+
61
+ if (delaySeconds === "invalid") {
62
+ return {
63
+ ok: false,
64
+ error:
65
+ `delaySeconds должен быть целым числом от ${MIN_ONESHOT_DELAY_SECONDS} ` +
66
+ `до ${MAX_ONESHOT_DELAY_SECONDS} секунд.`,
67
+ };
68
+ }
69
+
70
+ if (rawRunAt) {
71
+ const timestamp = Date.parse(rawRunAt);
72
+ if (!Number.isFinite(timestamp)) {
73
+ return {
74
+ ok: false,
75
+ error:
76
+ `runAt должен быть датой в формате ISO-8601, например ` +
77
+ `2026-12-01T09:00:00Z (получено «${rawRunAt}»).`,
78
+ };
79
+ }
80
+ if (timestamp <= nowMs) {
81
+ return {
82
+ ok: false,
83
+ error:
84
+ `runAt должен быть в будущем (получено «${rawRunAt}»). ` +
85
+ `Для запуска сразу используйте run_task_now.`,
86
+ };
87
+ }
88
+ return {
89
+ ok: true,
90
+ runAt: new Date(timestamp).toISOString(),
91
+ ...(delaySeconds !== undefined ? { delaySeconds } : {}),
92
+ };
93
+ }
94
+
95
+ if (delaySeconds !== undefined) {
96
+ return {
97
+ ok: true,
98
+ runAt: new Date(nowMs + delaySeconds * 1000).toISOString(),
99
+ delaySeconds,
100
+ };
101
+ }
102
+
103
+ return {
104
+ ok: false,
105
+ error:
106
+ "Для однократного запуска укажите runAt (ISO-8601) или delaySeconds.",
107
+ };
108
+ }
109
+
110
+ function pad(value: number): string {
111
+ return String(value).padStart(2, "0");
112
+ }
113
+
114
+ /**
115
+ * Формат даты/времени для schtasks /sd и /st.
116
+ *
117
+ * Windows Task Scheduler ожидает дату в формате текущей локали. Плагин уже
118
+ * использует DD.MM.YYYY для ONCE-заглушки, поэтому сохраняем этот формат
119
+ * для совместимости с русской локалью (основной сценарий проекта).
120
+ */
121
+ export function buildWindowsOneShotFlags(
122
+ runAt: string
123
+ ): ["/sc", "ONCE", "/sd", string, "/st", string] {
124
+ const date = new Date(runAt);
125
+ return [
126
+ "/sc",
127
+ "ONCE",
128
+ "/sd",
129
+ `${pad(date.getDate())}.${pad(date.getMonth() + 1)}.${date.getFullYear()}`,
130
+ "/st",
131
+ `${pad(date.getHours())}:${pad(date.getMinutes())}`,
132
+ ];
133
+ }
134
+
135
+ /** Формат `at -t`: YYYYMMDDHHMM в локальном времени системы. */
136
+ export function buildAtTimestamp(runAt: string): string {
137
+ const date = new Date(runAt);
138
+ return (
139
+ `${date.getFullYear()}` +
140
+ `${pad(date.getMonth() + 1)}` +
141
+ `${pad(date.getDate())}` +
142
+ `${pad(date.getHours())}` +
143
+ `${pad(date.getMinutes())}`
144
+ );
145
+ }
146
+
147
+ /**
148
+ * StartCalendarInterval для launchd. launchd не поддерживает год, поэтому
149
+ * плагин дополнительно выгружает plist после первого запуска (см. обёртку).
150
+ */
151
+ export function buildLaunchdCalendar(runAt: string): {
152
+ Month: number;
153
+ Day: number;
154
+ Hour: number;
155
+ Minute: number;
156
+ } {
157
+ const date = new Date(runAt);
158
+ return {
159
+ Month: date.getMonth() + 1,
160
+ Day: date.getDate(),
161
+ Hour: date.getHours(),
162
+ Minute: date.getMinutes(),
163
+ };
164
+ }
165
+
166
+ /** Команда самоочистки launchd-агента после единственного запуска. */
167
+ export function buildLaunchdOneShotCleanup(sanitizedName: string): string {
168
+ return (
169
+ `launchctl bootout "gui/$(id -u)" ` +
170
+ `"$HOME/Library/LaunchAgents/com.opencode.scheduler.${sanitizedName}.plist" ` +
171
+ `>/dev/null 2>&1 || true`
172
+ );
173
+ }
@@ -0,0 +1,128 @@
1
+ import crypto from "node:crypto";
2
+ import { getPluginVersion } from "../version.js";
3
+ import { getProfileName } from "../profiles.js";
4
+ import { getSchedulerTitle } from "./scheduler/index.js";
5
+ import type { StoredHistoryRecord } from "../db/history-repo.js";
6
+
7
+ /**
8
+ * Экспорт истории в OpenTelemetry-совместимом виде (Спринт 22).
9
+ *
10
+ * Формат — OTLP/JSON (`resourceSpans` → `scopeSpans` → `spans`), который
11
+ * принимают Collector, Jaeger, Tempo и большинство бэкендов после
12
+ * `otlp`-приёмника. Один запуск = один span.
13
+ *
14
+ * Идентификаторы детерминированы: sha256 от задачи, времени старта и id,
15
+ * поэтому повторный экспорт даёт стабильные traceId/spanId.
16
+ */
17
+
18
+ interface OtlpAttributeValue {
19
+ stringValue?: string;
20
+ intValue?: string;
21
+ doubleValue?: number;
22
+ boolValue?: boolean;
23
+ }
24
+
25
+ interface OtlpAttribute {
26
+ key: string;
27
+ value: OtlpAttributeValue;
28
+ }
29
+
30
+ function stringAttr(key: string, value: string | null | undefined): OtlpAttribute | null {
31
+ if (value == null || value === "") return null;
32
+ return { key, value: { stringValue: String(value) } };
33
+ }
34
+
35
+ function intAttr(key: string, value: number | null | undefined): OtlpAttribute | null {
36
+ if (typeof value !== "number" || !Number.isFinite(value)) return null;
37
+ return { key, value: { intValue: String(Math.trunc(value)) } };
38
+ }
39
+
40
+ function doubleAttr(key: string, value: number | null | undefined): OtlpAttribute | null {
41
+ if (typeof value !== "number" || !Number.isFinite(value)) return null;
42
+ return { key, value: { doubleValue: value } };
43
+ }
44
+
45
+ function compact(attrs: Array<OtlpAttribute | null>): OtlpAttribute[] {
46
+ return attrs.filter((attr): attr is OtlpAttribute => attr != null);
47
+ }
48
+
49
+ function toUnixNano(value: string | null | undefined): string | null {
50
+ if (!value) return null;
51
+ const ms = new Date(value).getTime();
52
+ if (!Number.isFinite(ms)) return null;
53
+ return (BigInt(Math.trunc(ms)) * 1000000n).toString();
54
+ }
55
+
56
+ function hashIds(record: StoredHistoryRecord): { traceId: string; spanId: string } {
57
+ const digest = crypto
58
+ .createHash("sha256")
59
+ .update(
60
+ `${record.taskName}|${record.startedAt}|${record.id ?? 0}`,
61
+ "utf8"
62
+ )
63
+ .digest("hex");
64
+ return { traceId: digest.slice(0, 32), spanId: digest.slice(32, 48) };
65
+ }
66
+
67
+ /** Строит OTLP/JSON-документ из записей истории. */
68
+ export function buildOtlpExport(records: StoredHistoryRecord[]): Record<string, unknown> {
69
+ const version = getPluginVersion();
70
+ const spans = records.map((record) => {
71
+ const { traceId, spanId } = hashIds(record);
72
+ const start = toUnixNano(record.startedAt) ?? "0";
73
+ const end = toUnixNano(record.finishedAt) ?? start;
74
+ const isRunning = record.status === "running";
75
+ const isError = !isRunning && record.status !== "success";
76
+ const attributes = compact([
77
+ stringAttr("task.name", record.taskName),
78
+ intAttr("run.id", record.id),
79
+ stringAttr("run.status", record.status),
80
+ intAttr("run.duration_ms", record.durationMs),
81
+ intAttr("run.tokens", record.tokens),
82
+ doubleAttr("run.cost_usd", record.costUsd),
83
+ stringAttr("llm.model", record.model),
84
+ stringAttr("error.message", record.error),
85
+ stringAttr("next.task", record.nextTask),
86
+ stringAttr("workspace.id", record.workspaceId),
87
+ stringAttr("pre_flight.status", record.preFlightStatus),
88
+ stringAttr("post_flight.status", record.postFlightStatus),
89
+ ]);
90
+ return {
91
+ traceId,
92
+ spanId,
93
+ name: `${record.taskName} run`,
94
+ kind: 1,
95
+ startTimeUnixNano: start,
96
+ endTimeUnixNano: end,
97
+ attributes,
98
+ status: {
99
+ code: isRunning ? 0 : isError ? 2 : 1,
100
+ ...(isError && record.error ? { message: String(record.error) } : {}),
101
+ },
102
+ };
103
+ });
104
+
105
+ return {
106
+ resourceSpans: [
107
+ {
108
+ resource: {
109
+ attributes: compact([
110
+ stringAttr("service.name", "opencode-windows-scheduler"),
111
+ stringAttr("service.version", version),
112
+ stringAttr("scheduler.profile", getProfileName()),
113
+ stringAttr("scheduler.backend", getSchedulerTitle()),
114
+ ]),
115
+ },
116
+ scopeSpans: [
117
+ {
118
+ scope: {
119
+ name: "opencode-windows-scheduler",
120
+ version,
121
+ },
122
+ spans,
123
+ },
124
+ ],
125
+ },
126
+ ],
127
+ };
128
+ }