opencode-windows-scheduler 1.2.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 (111) hide show
  1. package/CHANGELOG.md +16 -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/gui-experimental.cjs +1 -0
  55. package/dist/history.d.ts +7 -0
  56. package/dist/history.d.ts.map +1 -1
  57. package/dist/history.js +13 -0
  58. package/dist/index.d.ts +22 -3
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/index.js +330 -41
  61. package/dist/integrations.d.ts +64 -0
  62. package/dist/integrations.d.ts.map +1 -0
  63. package/dist/integrations.js +205 -0
  64. package/dist/rpc.d.ts +81 -4
  65. package/dist/rpc.d.ts.map +1 -1
  66. package/dist/rpc.js +43 -4
  67. package/dist/server.d.ts +2 -0
  68. package/dist/server.d.ts.map +1 -1
  69. package/dist/server.js +468 -56
  70. package/dist/settings.d.ts +38 -0
  71. package/dist/settings.d.ts.map +1 -1
  72. package/dist/settings.js +68 -0
  73. package/dist/shared/jobs-view.d.ts +43 -5
  74. package/dist/shared/jobs-view.d.ts.map +1 -1
  75. package/dist/shared/jobs-view.js +125 -7
  76. package/dist/task-transfer.d.ts +19 -3
  77. package/dist/task-transfer.d.ts.map +1 -1
  78. package/dist/task-transfer.js +75 -3
  79. package/docs/FEATURES.md +101 -4
  80. package/gui-experimental.cjs +4 -4
  81. package/package.json +11 -2
  82. package/scripts/demo-dashboard.mjs +12 -2
  83. package/src/core/dry-run.ts +24 -5
  84. package/src/core/one-shot.ts +173 -0
  85. package/src/core/otel.ts +128 -0
  86. package/src/core/prometheus.ts +215 -0
  87. package/src/core/ps-wrapper.ts +29 -3
  88. package/src/core/record-history.ts +13 -0
  89. package/src/core/scheduler/linux.ts +90 -3
  90. package/src/core/scheduler/mac.ts +35 -4
  91. package/src/core/scheduler/posix.ts +3 -0
  92. package/src/core/scheduler/registry.ts +4 -0
  93. package/src/core/scheduler/types.ts +5 -3
  94. package/src/core/scheduler/windows.ts +11 -1
  95. package/src/core/session.ts +115 -0
  96. package/src/core/structured-log.ts +205 -0
  97. package/src/core/wrappers/bash.ts +38 -2
  98. package/src/db/history-repo.ts +67 -7
  99. package/src/db/metrics-repo.ts +19 -7
  100. package/src/db/migrate.ts +7 -1
  101. package/src/db/schema.ts +11 -0
  102. package/src/gui.tsx +3832 -3613
  103. package/src/history.ts +17 -0
  104. package/src/index.ts +426 -47
  105. package/src/integrations.ts +253 -0
  106. package/src/rpc.ts +43 -4
  107. package/src/server.ts +501 -56
  108. package/src/settings.ts +122 -0
  109. package/src/shared/jobs-view.ts +158 -8
  110. package/src/task-transfer.ts +107 -5
  111. package/src/tui.tsx +290 -14
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-windows-scheduler",
3
- "version": "1.2.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-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-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",
@@ -79,6 +79,15 @@
79
79
  "test:env": "node test-env.mjs",
80
80
  "test:agent": "node test-agent-tools.mjs",
81
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",
82
91
  "test:docs": "node test-docs.mjs"
83
92
  },
84
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 });
@@ -21,7 +21,7 @@ export interface DryRunRoleScoped {
21
21
  export interface DryRunTaskItem {
22
22
  name: string;
23
23
  order: number;
24
- trigger: "manual" | "cron" | "dag";
24
+ trigger: "manual" | "cron" | "dag" | "once";
25
25
  cwd: string;
26
26
  command: string;
27
27
  workspace?: { name: string; path: string };
@@ -34,6 +34,10 @@ export interface DryRunTaskItem {
34
34
  estimatedTokens?: number | null;
35
35
  /** Для клона матрицы — имя родителя-шаблона (Спринт 15). */
36
36
  matrixParent?: string;
37
+ /** Режим сессии OpenCode (Спринт 24): new (по умолчанию), reuse, last. */
38
+ session?: string | null;
39
+ /** Идентификатор переиспользуемой сессии (только для session=reuse). */
40
+ sessionId?: string | null;
37
41
  /**
38
42
  * Эффективное расписание cron-задачи (Спринт 19): пояс, окно запуска и
39
43
  * ближайшие срабатывания с учётом часового пояса. Позволяет проверить
@@ -218,10 +222,13 @@ export async function simulatePipeline(taskName: string): Promise<DryRunReport>
218
222
 
219
223
  // Триггер: корневая задача (или клон корневой матрицы) — manual,
220
224
  // остальные попали в конвейер через dependsOn — dag.
225
+ const triggerType = def.triggerType ?? "cron";
221
226
  const trigger: DryRunTaskItem["trigger"] =
222
- lower === rootLower || (matrixParent && matrixParent.toLowerCase() === rootLower)
223
- ? "manual"
224
- : "dag";
227
+ triggerType === "once"
228
+ ? "once"
229
+ : lower === rootLower || (matrixParent && matrixParent.toLowerCase() === rootLower)
230
+ ? "manual"
231
+ : "dag";
225
232
 
226
233
  // Команда, которую выполнит обёртка.
227
234
  const modelArg = def.model ? ` --model ${def.model}` : "";
@@ -271,7 +278,17 @@ export async function simulatePipeline(taskName: string): Promise<DryRunReport>
271
278
  // считаем в часовом поясе задачи, чтобы dry-run показывал то же время, что
272
279
  // увидит планировщик после регистрации.
273
280
  let scheduleDetails: DryRunTaskItem["scheduleDetails"];
274
- if ((def.triggerType ?? "cron") === "cron" && def.schedule) {
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) {
275
292
  const runs: string[] = [];
276
293
  try {
277
294
  let cursor = new Date();
@@ -298,6 +315,8 @@ export async function simulatePipeline(taskName: string): Promise<DryRunReport>
298
315
  name: def.name,
299
316
  order: index,
300
317
  trigger,
318
+ session: def.session ?? "new",
319
+ sessionId: def.session === "reuse" ? def.sessionId ?? null : null,
301
320
  cwd,
302
321
  command,
303
322
  workspace: workspace ? { name: workspace.name, path: workspace.path } : undefined,
@@ -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
+ }
@@ -0,0 +1,215 @@
1
+ import { getAllMetrics } from "../db/metrics-repo.js";
2
+ import { countHistory, countRunningRecords, getHistory } from "../db/history-repo.js";
3
+ import { getPluginVersion } from "../version.js";
4
+ import { getProfileName } from "../profiles.js";
5
+ import { getSchedulerTitle } from "./scheduler/index.js";
6
+
7
+ /**
8
+ * Prometheus-метрики (Спринт 22).
9
+ *
10
+ * Формат — текстовый exposition format 0.0.4, отдаётся по GET /metrics.
11
+ * Никаких клиентских библиотек: собираем снимок из SQLite и рендерим строку.
12
+ *
13
+ * Имена метрик стабильны и документированы в docs/FEATURES.md:
14
+ * opencode_scheduler_info
15
+ * opencode_scheduler_up
16
+ * opencode_scheduler_queue_depth
17
+ * opencode_scheduler_history_records
18
+ * opencode_scheduler_runs_total{task,status}
19
+ * opencode_scheduler_errors_total{task}
20
+ * opencode_scheduler_tokens_total{task}
21
+ * opencode_scheduler_cost_usd_total{task}
22
+ * opencode_scheduler_run_duration_seconds{task,le} (+ _sum/_count)
23
+ */
24
+
25
+ export const PROMETHEUS_CONTENT_TYPE = "text/plain; version=0.0.4; charset=utf-8";
26
+
27
+ const DURATION_BUCKETS_SECONDS = [1, 5, 15, 30, 60, 120, 300, 600, 1800, 3600];
28
+
29
+ /** Экранирование значения label по правилам Prometheus. */
30
+ export function escapePrometheusLabel(value: string): string {
31
+ return String(value)
32
+ .replace(/\\/g, "\\\\")
33
+ .replace(/"/g, '\\"')
34
+ .replace(/\n/g, "\\n");
35
+ }
36
+
37
+ function labels(pairs: Record<string, string | number>): string {
38
+ const entries = Object.entries(pairs);
39
+ if (entries.length === 0) return "";
40
+ return `{${entries
41
+ .map(([key, value]) => `${key}="${escapePrometheusLabel(String(value))}"`)
42
+ .join(",")}}`;
43
+ }
44
+
45
+ function formatNumber(value: number): string {
46
+ if (!Number.isFinite(value)) return "0";
47
+ if (Number.isInteger(value)) return String(value);
48
+ return value.toFixed(6).replace(/0+$/, "").replace(/\.$/, "");
49
+ }
50
+
51
+ function metric(
52
+ lines: string[],
53
+ name: string,
54
+ type: "counter" | "gauge" | "histogram",
55
+ help: string,
56
+ samples: Array<{ labels?: Record<string, string | number>; value: number }>
57
+ ): void {
58
+ lines.push(`# HELP ${name} ${help}`);
59
+ lines.push(`# TYPE ${name} ${type}`);
60
+ for (const sample of samples) {
61
+ lines.push(`${name}${labels(sample.labels ?? {})} ${formatNumber(sample.value)}`);
62
+ }
63
+ }
64
+
65
+ interface DurationStats {
66
+ buckets: number[];
67
+ sumSeconds: number;
68
+ count: number;
69
+ }
70
+
71
+ function emptyDurationStats(): DurationStats {
72
+ return { buckets: new Array(DURATION_BUCKETS_SECONDS.length).fill(0), sumSeconds: 0, count: 0 };
73
+ }
74
+
75
+ /** Собирает и рендерит снимок метрик. Чистая функция от состояния БД. */
76
+ export function renderPrometheusMetrics(): string {
77
+ const metrics = getAllMetrics(false);
78
+ const history = getHistory(null, 100000);
79
+ const queueDepth = countRunningRecords();
80
+ const historyRecords = countHistory();
81
+
82
+ const durations = new Map<string, DurationStats>();
83
+ for (const record of history) {
84
+ if (record.status === "running") continue;
85
+ const durationMs = Number(record.durationMs ?? 0);
86
+ if (!Number.isFinite(durationMs) || durationMs < 0) continue;
87
+ const task = record.taskName;
88
+ const stats = durations.get(task) ?? emptyDurationStats();
89
+ const seconds = durationMs / 1000;
90
+ stats.sumSeconds += seconds;
91
+ stats.count += 1;
92
+ for (let i = 0; i < DURATION_BUCKETS_SECONDS.length; i += 1) {
93
+ if (seconds <= DURATION_BUCKETS_SECONDS[i]) stats.buckets[i] += 1;
94
+ }
95
+ durations.set(task, stats);
96
+ }
97
+
98
+ const lines: string[] = [];
99
+
100
+ metric(lines, "opencode_scheduler_info", "gauge", "Информация о планировщике.", [
101
+ {
102
+ labels: {
103
+ version: getPluginVersion(),
104
+ profile: getProfileName(),
105
+ scheduler: getSchedulerTitle(),
106
+ },
107
+ value: 1,
108
+ },
109
+ ]);
110
+ metric(lines, "opencode_scheduler_up", "gauge", "1 — HTTP-сервер метрик доступен.", [
111
+ { value: 1 },
112
+ ]);
113
+ metric(
114
+ lines,
115
+ "opencode_scheduler_queue_depth",
116
+ "gauge",
117
+ "Количество незавершённых запусков (глубина очереди).",
118
+ [{ value: queueDepth }]
119
+ );
120
+ metric(
121
+ lines,
122
+ "opencode_scheduler_history_records",
123
+ "gauge",
124
+ "Количество записей в истории запусков.",
125
+ [{ value: historyRecords }]
126
+ );
127
+
128
+ const runSamples: Array<{ labels: Record<string, string | number>; value: number }> = [];
129
+ const errorSamples: Array<{ labels: Record<string, string | number>; value: number }> = [];
130
+ const tokenSamples: Array<{ labels: Record<string, string | number>; value: number }> = [];
131
+ const costSamples: Array<{ labels: Record<string, string | number>; value: number }> = [];
132
+ for (const row of metrics) {
133
+ runSamples.push({
134
+ labels: { task: row.taskName, status: "success" },
135
+ value: row.success,
136
+ });
137
+ runSamples.push({
138
+ labels: { task: row.taskName, status: "error" },
139
+ value: row.error,
140
+ });
141
+ runSamples.push({
142
+ labels: { task: row.taskName, status: "partial" },
143
+ value: row.partial,
144
+ });
145
+ errorSamples.push({ labels: { task: row.taskName }, value: row.error });
146
+ tokenSamples.push({ labels: { task: row.taskName }, value: row.tokens });
147
+ costSamples.push({ labels: { task: row.taskName }, value: row.costUsd });
148
+ }
149
+ metric(
150
+ lines,
151
+ "opencode_scheduler_runs_total",
152
+ "counter",
153
+ "Количество завершённых запусков по задачам и статусам.",
154
+ runSamples
155
+ );
156
+ metric(
157
+ lines,
158
+ "opencode_scheduler_errors_total",
159
+ "counter",
160
+ "Количество ошибок и таймаутов по задачам (partial не входит).",
161
+ errorSamples
162
+ );
163
+ metric(
164
+ lines,
165
+ "opencode_scheduler_tokens_total",
166
+ "counter",
167
+ "Суммарное количество токенов по задачам.",
168
+ tokenSamples
169
+ );
170
+ metric(
171
+ lines,
172
+ "opencode_scheduler_cost_usd_total",
173
+ "counter",
174
+ "Суммарная стоимость запусков в USD по задачам.",
175
+ costSamples
176
+ );
177
+
178
+ lines.push(
179
+ "# HELP opencode_scheduler_run_duration_seconds Длительность запусков в секундах."
180
+ );
181
+ lines.push("# TYPE opencode_scheduler_run_duration_seconds histogram");
182
+ const taskNames = Array.from(durations.keys()).sort((a, b) => a.localeCompare(b));
183
+ for (const task of taskNames) {
184
+ const stats = durations.get(task)!;
185
+ let cumulative = 0;
186
+ for (let i = 0; i < DURATION_BUCKETS_SECONDS.length; i += 1) {
187
+ cumulative += stats.buckets[i];
188
+ lines.push(
189
+ `opencode_scheduler_run_duration_seconds_bucket${labels({
190
+ task,
191
+ le: DURATION_BUCKETS_SECONDS[i],
192
+ })} ${cumulative}`
193
+ );
194
+ }
195
+ lines.push(
196
+ `opencode_scheduler_run_duration_seconds_bucket${labels({ task, le: "+Inf" })} ${stats.count}`
197
+ );
198
+ lines.push(
199
+ `opencode_scheduler_run_duration_seconds_sum${labels({ task })} ${formatNumber(
200
+ stats.sumSeconds
201
+ )}`
202
+ );
203
+ lines.push(
204
+ `opencode_scheduler_run_duration_seconds_count${labels({ task })} ${stats.count}`
205
+ );
206
+ }
207
+ if (taskNames.length === 0) {
208
+ // Пустой histogram всё равно должен быть валидным: отдаём +Inf = 0.
209
+ lines.push(`opencode_scheduler_run_duration_seconds_bucket${labels({ le: "+Inf" })} 0`);
210
+ lines.push("opencode_scheduler_run_duration_seconds_sum 0");
211
+ lines.push("opencode_scheduler_run_duration_seconds_count 0");
212
+ }
213
+
214
+ return `${lines.join("\n")}\n`;
215
+ }