opencode-windows-scheduler 0.0.0-stage → 1.0.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.
- package/CHANGELOG.md +45 -0
- package/CROSS_PLATFORM.md +113 -0
- package/LICENSE +21 -0
- package/README.md +173 -2
- package/README.ru.md +131 -0
- package/ROADMAP-STRATEGY.md +217 -0
- package/ROADMAP.md +87 -0
- package/dist/core/cron-to-schtasks.d.ts +20 -0
- package/dist/core/cron-to-schtasks.d.ts.map +1 -0
- package/dist/core/cron-to-schtasks.js +233 -0
- package/dist/core/dry-run.d.ts +44 -0
- package/dist/core/dry-run.d.ts.map +1 -0
- package/dist/core/dry-run.js +252 -0
- package/dist/core/file-watcher.d.ts +31 -0
- package/dist/core/file-watcher.d.ts.map +1 -0
- package/dist/core/file-watcher.js +128 -0
- package/dist/core/lock.d.ts +43 -0
- package/dist/core/lock.d.ts.map +1 -0
- package/dist/core/lock.js +118 -0
- package/dist/core/matrix.d.ts +167 -0
- package/dist/core/matrix.d.ts.map +1 -0
- package/dist/core/matrix.js +687 -0
- package/dist/core/ps-wrapper.d.ts +60 -0
- package/dist/core/ps-wrapper.d.ts.map +1 -0
- package/dist/core/ps-wrapper.js +538 -0
- package/dist/core/record-history.d.ts +14 -0
- package/dist/core/record-history.d.ts.map +1 -0
- package/dist/core/record-history.js +360 -0
- package/dist/core/scheduler/index.d.ts +20 -0
- package/dist/core/scheduler/index.d.ts.map +1 -0
- package/dist/core/scheduler/index.js +32 -0
- package/dist/core/scheduler/linux.d.ts +32 -0
- package/dist/core/scheduler/linux.d.ts.map +1 -0
- package/dist/core/scheduler/linux.js +115 -0
- package/dist/core/scheduler/logs.d.ts +11 -0
- package/dist/core/scheduler/logs.d.ts.map +1 -0
- package/dist/core/scheduler/logs.js +34 -0
- package/dist/core/scheduler/mac.d.ts +39 -0
- package/dist/core/scheduler/mac.d.ts.map +1 -0
- package/dist/core/scheduler/mac.js +175 -0
- package/dist/core/scheduler/posix.d.ts +40 -0
- package/dist/core/scheduler/posix.d.ts.map +1 -0
- package/dist/core/scheduler/posix.js +86 -0
- package/dist/core/scheduler/registry.d.ts +36 -0
- package/dist/core/scheduler/registry.d.ts.map +1 -0
- package/dist/core/scheduler/registry.js +56 -0
- package/dist/core/scheduler/types.d.ts +63 -0
- package/dist/core/scheduler/types.d.ts.map +1 -0
- package/dist/core/scheduler/types.js +1 -0
- package/dist/core/scheduler/windows.d.ts +47 -0
- package/dist/core/scheduler/windows.d.ts.map +1 -0
- package/dist/core/scheduler/windows.js +375 -0
- package/dist/core/wrappers/bash.d.ts +58 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -0
- package/dist/core/wrappers/bash.js +223 -0
- package/dist/db/history-repo.d.ts +69 -0
- package/dist/db/history-repo.d.ts.map +1 -0
- package/dist/db/history-repo.js +150 -0
- package/dist/db/index.d.ts +47 -0
- package/dist/db/index.d.ts.map +1 -0
- package/dist/db/index.js +120 -0
- package/dist/db/metrics-repo.d.ts +43 -0
- package/dist/db/metrics-repo.d.ts.map +1 -0
- package/dist/db/metrics-repo.js +95 -0
- package/dist/db/migrate.d.ts +24 -0
- package/dist/db/migrate.d.ts.map +1 -0
- package/dist/db/migrate.js +237 -0
- package/dist/db/recovery.d.ts +11 -0
- package/dist/db/recovery.d.ts.map +1 -0
- package/dist/db/recovery.js +38 -0
- package/dist/db/schema.d.ts +24 -0
- package/dist/db/schema.d.ts.map +1 -0
- package/dist/db/schema.js +97 -0
- package/dist/db/settings-repo.d.ts +8 -0
- package/dist/db/settings-repo.d.ts.map +1 -0
- package/dist/db/settings-repo.js +27 -0
- package/dist/db/tasks-repo.d.ts +26 -0
- package/dist/db/tasks-repo.d.ts.map +1 -0
- package/dist/db/tasks-repo.js +120 -0
- package/dist/db/templates-repo.d.ts +17 -0
- package/dist/db/templates-repo.d.ts.map +1 -0
- package/dist/db/templates-repo.js +57 -0
- package/dist/gui-experimental.cjs +1 -0
- package/dist/history.d.ts +53 -0
- package/dist/history.d.ts.map +1 -0
- package/dist/history.js +57 -0
- package/dist/index.d.ts +156 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2077 -0
- package/dist/notifications.d.ts +45 -0
- package/dist/notifications.d.ts.map +1 -0
- package/dist/notifications.js +135 -0
- package/dist/rpc.d.ts +2052 -0
- package/dist/rpc.d.ts.map +1 -0
- package/dist/rpc.js +863 -0
- package/dist/schtasks.d.ts +32 -0
- package/dist/schtasks.d.ts.map +1 -0
- package/dist/schtasks.js +45 -0
- package/dist/server.d.ts +106 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +1478 -0
- package/dist/settings.d.ts +43 -0
- package/dist/settings.d.ts.map +1 -0
- package/dist/settings.js +96 -0
- package/dist/shared/jobs-view.d.ts +21 -0
- package/dist/shared/jobs-view.d.ts.map +1 -0
- package/dist/shared/jobs-view.js +28 -0
- package/dist/skill.d.ts +15 -0
- package/dist/skill.d.ts.map +1 -0
- package/dist/skill.js +93 -0
- package/dist/task-transfer.d.ts +176 -0
- package/dist/task-transfer.d.ts.map +1 -0
- package/dist/task-transfer.js +442 -0
- package/dist/templates.d.ts +57 -0
- package/dist/templates.d.ts.map +1 -0
- package/dist/templates.js +16 -0
- package/dist/types.d.ts +78 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +88 -0
- package/dist/workspaces.d.ts +55 -0
- package/dist/workspaces.d.ts.map +1 -0
- package/dist/workspaces.js +183 -0
- package/docs/ARCHITECTURE.md +302 -0
- package/docs/FEATURES.md +288 -0
- package/docs/MIGRATION.md +266 -0
- package/docs/dashboard.png +0 -0
- package/gui-experimental.cjs +2 -0
- package/index.js +1 -0
- package/package.json +92 -4
- package/scripts/demo-dashboard.mjs +199 -0
- package/skills/scheduled-job-best-practices/SKILL.md +155 -0
- package/skills/scheduled-job-best-practices/references/recipes.md +123 -0
- package/src/core/cron-to-schtasks.ts +269 -0
- package/src/core/dry-run.ts +315 -0
- package/src/core/file-watcher.ts +171 -0
- package/src/core/lock.ts +134 -0
- package/src/core/matrix.ts +907 -0
- package/src/core/ps-wrapper.ts +572 -0
- package/src/core/record-history.ts +493 -0
- package/src/core/scheduler/index.ts +44 -0
- package/src/core/scheduler/linux.ts +125 -0
- package/src/core/scheduler/logs.ts +37 -0
- package/src/core/scheduler/mac.ts +222 -0
- package/src/core/scheduler/posix.ts +111 -0
- package/src/core/scheduler/registry.ts +93 -0
- package/src/core/scheduler/types.ts +67 -0
- package/src/core/scheduler/windows.ts +469 -0
- package/src/core/wrappers/bash.ts +282 -0
- package/src/db/history-repo.ts +303 -0
- package/src/db/index.ts +166 -0
- package/src/db/metrics-repo.ts +158 -0
- package/src/db/migrate.ts +322 -0
- package/src/db/recovery.ts +46 -0
- package/src/db/schema.ts +109 -0
- package/src/db/settings-repo.ts +31 -0
- package/src/db/tasks-repo.ts +162 -0
- package/src/db/templates-repo.ts +77 -0
- package/src/gui.tsx +2725 -0
- package/src/history.ts +107 -0
- package/src/index.ts +2672 -0
- package/src/notifications.ts +174 -0
- package/src/rpc.ts +933 -0
- package/src/schtasks.ts +75 -0
- package/src/server.ts +1663 -0
- package/src/settings.ts +157 -0
- package/src/shared/jobs-view.ts +38 -0
- package/src/skill.ts +113 -0
- package/src/task-transfer.ts +648 -0
- package/src/templates.ts +67 -0
- package/src/tui.tsx +46 -0
- package/src/types.ts +145 -0
- package/src/workspaces.ts +236 -0
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import { sanitizeName } from "../../types.js";
|
|
7
|
+
import { PosixSchedulerBase } from "./posix.js";
|
|
8
|
+
import type { RegistryEntry } from "./registry.js";
|
|
9
|
+
|
|
10
|
+
const execFileAsync = promisify(execFile);
|
|
11
|
+
|
|
12
|
+
/** Папка пользовательских LaunchAgents. */
|
|
13
|
+
const LAUNCH_AGENTS_DIR = path.join(os.homedir(), "Library", "LaunchAgents");
|
|
14
|
+
|
|
15
|
+
/** Префикс label/файлов плагина. */
|
|
16
|
+
const LABEL_PREFIX = "com.opencode.scheduler";
|
|
17
|
+
|
|
18
|
+
/** Экранирует текст для XML. */
|
|
19
|
+
function xmlEscape(value: string): string {
|
|
20
|
+
return value
|
|
21
|
+
.replace(/&/g, "&")
|
|
22
|
+
.replace(/</g, "<")
|
|
23
|
+
.replace(/>/g, ">")
|
|
24
|
+
.replace(/"/g, """);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Расписание launchd, полученное из cron-выражения. */
|
|
28
|
+
interface LaunchdSchedule {
|
|
29
|
+
/** StartInterval в секундах (для «каждые N минут»). */
|
|
30
|
+
interval?: number;
|
|
31
|
+
/** StartCalendarInterval (для фиксированного времени). */
|
|
32
|
+
calendar?: { Minute?: number; Hour?: number; Weekday?: number };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Преобразует поддерживаемое 5-полевое cron-выражение в расписание launchd.
|
|
37
|
+
* Поддерживается то же подмножество, что и у Windows-бэкенда.
|
|
38
|
+
*/
|
|
39
|
+
export function cronToLaunchdSchedule(cron: string): LaunchdSchedule {
|
|
40
|
+
const fields = cron.trim().split(/\s+/);
|
|
41
|
+
if (fields.length !== 5) {
|
|
42
|
+
throw new Error(
|
|
43
|
+
`Ожидалось 5 полей cron-выражения, получено ${fields.length}.`
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const [minute, hour, dayOfMonth, month, dayOfWeek] = fields;
|
|
48
|
+
const star = (v: string) => v === "*";
|
|
49
|
+
const intIn = (v: string, min: number, max: number): number | undefined => {
|
|
50
|
+
if (!/^\d+$/.test(v)) return undefined;
|
|
51
|
+
const n = parseInt(v, 10);
|
|
52
|
+
return n >= min && n <= max ? n : undefined;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
if (
|
|
56
|
+
star(minute) && star(hour) && star(dayOfMonth) && star(month) && star(dayOfWeek)
|
|
57
|
+
) {
|
|
58
|
+
return { interval: 60 };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const step = /^\*\/(\d+)$/.exec(minute);
|
|
62
|
+
if (step && star(hour) && star(dayOfMonth) && star(month) && star(dayOfWeek)) {
|
|
63
|
+
const n = parseInt(step[1], 10);
|
|
64
|
+
if (n > 0) return { interval: n * 60 };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const m = intIn(minute, 0, 59);
|
|
68
|
+
const h = intIn(hour, 0, 23);
|
|
69
|
+
if (m === undefined) {
|
|
70
|
+
throw new Error("Неподдерживаемое cron-выражение для launchd.");
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// M * * * * — каждый час в минуту M.
|
|
74
|
+
if (star(hour) && star(dayOfMonth) && star(month) && star(dayOfWeek)) {
|
|
75
|
+
return { calendar: { Minute: m } };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
if (h === undefined || !star(dayOfMonth) || !star(month)) {
|
|
79
|
+
throw new Error("Неподдерживаемое cron-выражение для launchd.");
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// M H * * * — ежедневно.
|
|
83
|
+
if (star(dayOfWeek)) {
|
|
84
|
+
return { calendar: { Minute: m, Hour: h } };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// M H * * D — еженедельно (0 и 7 — воскресенье).
|
|
88
|
+
const d = intIn(dayOfWeek, 0, 7);
|
|
89
|
+
if (d === undefined) {
|
|
90
|
+
throw new Error("Неподдерживаемое cron-выражение для launchd.");
|
|
91
|
+
}
|
|
92
|
+
return { calendar: { Minute: m, Hour: h, Weekday: d } };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Собирает XML plist для задачи. */
|
|
96
|
+
function buildPlist(label: string, entry: RegistryEntry): string {
|
|
97
|
+
const schedule =
|
|
98
|
+
entry.triggerType !== "cron"
|
|
99
|
+
? { interval: 315_360_000 } // file/mcp-event: 10 лет — фактически «никогда».
|
|
100
|
+
: cronToLaunchdSchedule(entry.schedule);
|
|
101
|
+
|
|
102
|
+
const scheduleXml: string[] = [];
|
|
103
|
+
if (schedule.interval !== undefined) {
|
|
104
|
+
scheduleXml.push(
|
|
105
|
+
" <key>StartInterval</key>",
|
|
106
|
+
` <integer>${schedule.interval}</integer>`
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
if (schedule.calendar) {
|
|
110
|
+
scheduleXml.push(" <key>StartCalendarInterval</key>", " <dict>");
|
|
111
|
+
if (schedule.calendar.Minute !== undefined) {
|
|
112
|
+
scheduleXml.push(
|
|
113
|
+
" <key>Minute</key>",
|
|
114
|
+
` <integer>${schedule.calendar.Minute}</integer>`
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
if (schedule.calendar.Hour !== undefined) {
|
|
118
|
+
scheduleXml.push(
|
|
119
|
+
" <key>Hour</key>",
|
|
120
|
+
` <integer>${schedule.calendar.Hour}</integer>`
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
if (schedule.calendar.Weekday !== undefined) {
|
|
124
|
+
scheduleXml.push(
|
|
125
|
+
" <key>Weekday</key>",
|
|
126
|
+
` <integer>${schedule.calendar.Weekday}</integer>`
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
scheduleXml.push(" </dict>");
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const workdir = entry.workingDirectory || process.cwd();
|
|
133
|
+
const log = entry.logFile;
|
|
134
|
+
const logXml = log
|
|
135
|
+
? [
|
|
136
|
+
" <key>StandardOutPath</key>",
|
|
137
|
+
` <string>${xmlEscape(log)}</string>`,
|
|
138
|
+
" <key>StandardErrorPath</key>",
|
|
139
|
+
` <string>${xmlEscape(log)}</string>`,
|
|
140
|
+
]
|
|
141
|
+
: [];
|
|
142
|
+
|
|
143
|
+
return [
|
|
144
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
145
|
+
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" ' +
|
|
146
|
+
'"http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
|
147
|
+
'<plist version="1.0">',
|
|
148
|
+
"<dict>",
|
|
149
|
+
" <key>Label</key>",
|
|
150
|
+
` <string>${xmlEscape(label)}</string>`,
|
|
151
|
+
" <key>ProgramArguments</key>",
|
|
152
|
+
" <array>",
|
|
153
|
+
" <string>/bin/bash</string>",
|
|
154
|
+
` <string>${xmlEscape(entry.command)}</string>`,
|
|
155
|
+
" </array>",
|
|
156
|
+
" <key>WorkingDirectory</key>",
|
|
157
|
+
` <string>${xmlEscape(workdir)}</string>`,
|
|
158
|
+
...logXml,
|
|
159
|
+
" <key>RunAtLoad</key>",
|
|
160
|
+
" <false/>",
|
|
161
|
+
...scheduleXml,
|
|
162
|
+
"</dict>",
|
|
163
|
+
"</plist>",
|
|
164
|
+
"",
|
|
165
|
+
].join("\n");
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Бэкенд планировщика macOS на основе launchd.
|
|
170
|
+
*
|
|
171
|
+
* Каждая задача — отдельный LaunchAgent:
|
|
172
|
+
* ~/Library/LaunchAgents/com.opencode.scheduler.<name>.plist
|
|
173
|
+
* Управление — через launchctl load/unload -w.
|
|
174
|
+
*/
|
|
175
|
+
export class MacScheduler extends PosixSchedulerBase {
|
|
176
|
+
readonly platform: NodeJS.Platform = "darwin";
|
|
177
|
+
readonly title = "OpenCode Scheduler";
|
|
178
|
+
|
|
179
|
+
constructor() {
|
|
180
|
+
super("mac");
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
private label(name: string): string {
|
|
184
|
+
return `${LABEL_PREFIX}.${sanitizeName(name)}`;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
private plistPath(name: string): string {
|
|
188
|
+
return path.join(LAUNCH_AGENTS_DIR, `${this.label(name)}.plist`);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Выполняет launchctl, не считая ошибку фатальной (unload несуществующего). */
|
|
192
|
+
private async launchctl(args: string[]): Promise<void> {
|
|
193
|
+
try {
|
|
194
|
+
await execFileAsync("launchctl", args, { maxBuffer: 1024 * 1024 });
|
|
195
|
+
} catch {
|
|
196
|
+
// launchctl возвращает ошибку, если агент ещё не загружен — это нормально.
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
protected async installEntry(entry: RegistryEntry): Promise<void> {
|
|
201
|
+
await fs.mkdir(LAUNCH_AGENTS_DIR, { recursive: true });
|
|
202
|
+
const plistPath = this.plistPath(entry.name);
|
|
203
|
+
await this.launchctl(["unload", plistPath]);
|
|
204
|
+
await fs.writeFile(plistPath, buildPlist(this.label(entry.name), entry), "utf8");
|
|
205
|
+
await this.launchctl(["load", "-w", plistPath]);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
protected async uninstallEntry(entry: RegistryEntry): Promise<void> {
|
|
209
|
+
const plistPath = this.plistPath(entry.name);
|
|
210
|
+
await this.launchctl(["unload", "-w", plistPath]);
|
|
211
|
+
await fs.unlink(plistPath).catch(() => {});
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
protected async applyPause(entry: RegistryEntry, paused: boolean): Promise<void> {
|
|
215
|
+
const plistPath = this.plistPath(entry.name);
|
|
216
|
+
if (paused) {
|
|
217
|
+
await this.launchctl(["unload", "-w", plistPath]);
|
|
218
|
+
} else {
|
|
219
|
+
await this.launchctl(["load", "-w", plistPath]);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import type { ScheduledTaskInfo } from "../../types.js";
|
|
3
|
+
import { TaskRegistry, type RegistryEntry } from "./registry.js";
|
|
4
|
+
import type {
|
|
5
|
+
CreateTaskOptions,
|
|
6
|
+
RunTaskResult,
|
|
7
|
+
SchedulerBackend,
|
|
8
|
+
} from "./types.js";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Общая база для LinuxScheduler и MacScheduler.
|
|
12
|
+
*
|
|
13
|
+
* Инкапсулирует всё, что одинаково на POSIX: реестр задач, немедленный запуск
|
|
14
|
+
* bash-обёртки detached-процессом, список задач и удаление.
|
|
15
|
+
* Различия (crontab vs launchd) реализуют наследники через installEntry,
|
|
16
|
+
* uninstallEntry и applyPause.
|
|
17
|
+
*/
|
|
18
|
+
export abstract class PosixSchedulerBase implements SchedulerBackend {
|
|
19
|
+
abstract readonly platform: NodeJS.Platform;
|
|
20
|
+
abstract readonly title: string;
|
|
21
|
+
|
|
22
|
+
protected readonly registry: TaskRegistry;
|
|
23
|
+
|
|
24
|
+
constructor(backendId: string) {
|
|
25
|
+
this.registry = new TaskRegistry(backendId);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Регистрирует запись в планировщике ОС (crontab-строка или plist). */
|
|
29
|
+
protected abstract installEntry(entry: RegistryEntry): Promise<void>;
|
|
30
|
+
/** Убирает запись из планировщика ОС. */
|
|
31
|
+
protected abstract uninstallEntry(entry: RegistryEntry): Promise<void>;
|
|
32
|
+
/** Применяет состояние паузы к записи в планировщике ОС. */
|
|
33
|
+
protected abstract applyPause(entry: RegistryEntry, paused: boolean): Promise<void>;
|
|
34
|
+
|
|
35
|
+
async createTask(options: CreateTaskOptions): Promise<void> {
|
|
36
|
+
const entry: RegistryEntry = {
|
|
37
|
+
name: options.name,
|
|
38
|
+
schedule: options.schedule,
|
|
39
|
+
command: options.command,
|
|
40
|
+
logFile: options.logFile,
|
|
41
|
+
workingDirectory: options.workingDirectory,
|
|
42
|
+
triggerType: options.triggerType ?? "cron",
|
|
43
|
+
paused: false,
|
|
44
|
+
createdAt: new Date().toISOString(),
|
|
45
|
+
...(options.model ? { model: options.model } : {}),
|
|
46
|
+
...(options.priority !== undefined ? { priority: options.priority } : {}),
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
await this.registry.upsert(entry);
|
|
50
|
+
await this.installEntry(entry);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async deleteTask(name: string): Promise<void> {
|
|
54
|
+
const entry = await this.registry.find(name);
|
|
55
|
+
await this.registry.remove(name);
|
|
56
|
+
if (entry) {
|
|
57
|
+
await this.uninstallEntry(entry);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async pauseTask(name: string): Promise<void> {
|
|
62
|
+
const entry = await this.registry.find(name);
|
|
63
|
+
if (!entry) throw new Error(`Задача "${name}" не найдена.`);
|
|
64
|
+
await this.registry.setPaused(name, true);
|
|
65
|
+
await this.applyPause(entry, true);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async resumeTask(name: string): Promise<void> {
|
|
69
|
+
const entry = await this.registry.find(name);
|
|
70
|
+
if (!entry) throw new Error(`Задача "${name}" не найдена.`);
|
|
71
|
+
await this.registry.setPaused(name, false);
|
|
72
|
+
await this.applyPause(entry, false);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async listTasks(): Promise<ScheduledTaskInfo[]> {
|
|
76
|
+
const entries = await this.registry.load();
|
|
77
|
+
return entries.map((entry) => ({
|
|
78
|
+
taskName: entry.name,
|
|
79
|
+
status: entry.paused ? "Disabled" : "Ready",
|
|
80
|
+
paused: entry.paused,
|
|
81
|
+
}));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Запускает обёртку напрямую, минуя планировщик ОС. Это одинаково работает
|
|
86
|
+
* и для cron-, и для файловых задач. Сама обёртка отвечает за lock-файл,
|
|
87
|
+
* таймаут и запись истории.
|
|
88
|
+
*/
|
|
89
|
+
async runTask(name: string): Promise<RunTaskResult> {
|
|
90
|
+
const entry = await this.registry.find(name);
|
|
91
|
+
if (!entry) throw new Error(`Задача "${name}" не найдена.`);
|
|
92
|
+
|
|
93
|
+
const child = spawn("/bin/bash", [entry.command], {
|
|
94
|
+
detached: true,
|
|
95
|
+
stdio: "ignore",
|
|
96
|
+
cwd: entry.workingDirectory || process.cwd(),
|
|
97
|
+
});
|
|
98
|
+
child.unref();
|
|
99
|
+
|
|
100
|
+
return { alreadyRunning: false };
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Экранирует строку для безопасной вставки в POSIX shell
|
|
106
|
+
* (одинарные кавычки: ' -> '\'').
|
|
107
|
+
*/
|
|
108
|
+
export function shellQuote(value: string): string {
|
|
109
|
+
if (value === "") return "''";
|
|
110
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
111
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { PLUGIN_DIR } from "../../types.js";
|
|
4
|
+
import type { TriggerType } from "./types.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Запись реестра задач POSIX-бэкендов.
|
|
8
|
+
*
|
|
9
|
+
* crontab и launchd не хранят исходный cron-текст в удобном виде, а для
|
|
10
|
+
* файловых триггеров вообще не создают расписание. Поэтому источником правды
|
|
11
|
+
* для Linux/macOS служит собственный JSON-реестр плагина.
|
|
12
|
+
*/
|
|
13
|
+
export interface RegistryEntry {
|
|
14
|
+
name: string;
|
|
15
|
+
schedule: string;
|
|
16
|
+
command: string;
|
|
17
|
+
logFile?: string;
|
|
18
|
+
workingDirectory?: string;
|
|
19
|
+
triggerType: TriggerType;
|
|
20
|
+
paused: boolean;
|
|
21
|
+
createdAt: string;
|
|
22
|
+
/** LLM-модель задачи (опционально). */
|
|
23
|
+
model?: string;
|
|
24
|
+
/** Приоритет задачи 0..10 (опционально). */
|
|
25
|
+
priority?: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Реестр задач конкретного бэкенда: PLUGIN_DIR/scheduler-<backend>.json. */
|
|
29
|
+
export class TaskRegistry {
|
|
30
|
+
private readonly file: string;
|
|
31
|
+
|
|
32
|
+
constructor(backendId: string) {
|
|
33
|
+
this.file = path.join(PLUGIN_DIR, `scheduler-${backendId}.json`);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Путь к файлу реестра (для диагностики). */
|
|
37
|
+
get path(): string {
|
|
38
|
+
return this.file;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async load(): Promise<RegistryEntry[]> {
|
|
42
|
+
try {
|
|
43
|
+
const raw = await fs.readFile(this.file, "utf8");
|
|
44
|
+
const parsed = JSON.parse(raw);
|
|
45
|
+
if (!Array.isArray(parsed)) return [];
|
|
46
|
+
return parsed.filter(
|
|
47
|
+
(entry): entry is RegistryEntry =>
|
|
48
|
+
entry && typeof entry.name === "string" && typeof entry.command === "string"
|
|
49
|
+
);
|
|
50
|
+
} catch {
|
|
51
|
+
return [];
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async save(entries: RegistryEntry[]): Promise<void> {
|
|
56
|
+
await fs.mkdir(PLUGIN_DIR, { recursive: true });
|
|
57
|
+
const tmp = `${this.file}.tmp`;
|
|
58
|
+
await fs.writeFile(tmp, JSON.stringify(entries, null, 2), "utf8");
|
|
59
|
+
await fs.rename(tmp, this.file);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async find(name: string): Promise<RegistryEntry | undefined> {
|
|
63
|
+
const entries = await this.load();
|
|
64
|
+
return entries.find((e) => e.name.toLowerCase() === name.toLowerCase());
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async upsert(entry: RegistryEntry): Promise<void> {
|
|
68
|
+
const entries = await this.load();
|
|
69
|
+
const index = entries.findIndex(
|
|
70
|
+
(e) => e.name.toLowerCase() === entry.name.toLowerCase()
|
|
71
|
+
);
|
|
72
|
+
if (index === -1) entries.push(entry);
|
|
73
|
+
else entries[index] = entry;
|
|
74
|
+
await this.save(entries);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async remove(name: string): Promise<void> {
|
|
78
|
+
const entries = await this.load();
|
|
79
|
+
await this.save(
|
|
80
|
+
entries.filter((e) => e.name.toLowerCase() !== name.toLowerCase())
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async setPaused(name: string, paused: boolean): Promise<void> {
|
|
85
|
+
const entries = await this.load();
|
|
86
|
+
const entry = entries.find(
|
|
87
|
+
(e) => e.name.toLowerCase() === name.toLowerCase()
|
|
88
|
+
);
|
|
89
|
+
if (!entry) return;
|
|
90
|
+
entry.paused = paused;
|
|
91
|
+
await this.save(entries);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { ScheduledTaskInfo } from "../../types.js";
|
|
2
|
+
|
|
3
|
+
/** Чем запускается задача. */
|
|
4
|
+
export type TriggerType = "cron" | "file" | "mcp-event";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Параметры создания задачи. Бэкенд сам решает, как преобразовать cron
|
|
8
|
+
* в родное расписание ОС и как зарегистрировать команду запуска.
|
|
9
|
+
*/
|
|
10
|
+
export interface CreateTaskOptions {
|
|
11
|
+
/** Уникальное имя задачи (без папки планировщика). */
|
|
12
|
+
name: string;
|
|
13
|
+
/**
|
|
14
|
+
* Абсолютный путь к исполняемой обёртке:
|
|
15
|
+
* - Windows: .cmd, вызывающий PowerShell-обёртку;
|
|
16
|
+
* - Linux/macOS: .sh с вызовом `opencode run`.
|
|
17
|
+
*/
|
|
18
|
+
command: string;
|
|
19
|
+
/** 5-полевое cron-выражение. Игнорируется при триггерах file/mcp-event. */
|
|
20
|
+
schedule: string;
|
|
21
|
+
/** Таймаут выполнения в секундах (используется обёрткой). */
|
|
22
|
+
timeoutSeconds?: number;
|
|
23
|
+
/** "cron" (по умолчанию), "file" или "mcp-event". */
|
|
24
|
+
triggerType?: TriggerType;
|
|
25
|
+
/** Рабочая директория задачи (для POSIX-бэкендов попадает в cron/plist). */
|
|
26
|
+
workingDirectory?: string;
|
|
27
|
+
/** Путь к файлу лога (для POSIX-бэкендов — перенаправление вывода). */
|
|
28
|
+
logFile?: string;
|
|
29
|
+
/** LLM-модель задачи (хранится в реестре; используется обёрткой). */
|
|
30
|
+
model?: string;
|
|
31
|
+
/** Приоритет задачи 0..10 (хранится в реестре для диагностики). */
|
|
32
|
+
priority?: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Результат немедленного запуска. */
|
|
36
|
+
export interface RunTaskResult {
|
|
37
|
+
/** true — задача уже выполняется, повторный запуск не потребовался. */
|
|
38
|
+
alreadyRunning: boolean;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Абстрактный бэкенд планировщика ОС.
|
|
43
|
+
*
|
|
44
|
+
* Реализации:
|
|
45
|
+
* - WindowsScheduler — schtasks;
|
|
46
|
+
* - LinuxScheduler — crontab;
|
|
47
|
+
* - MacScheduler — launchd.
|
|
48
|
+
*/
|
|
49
|
+
export interface SchedulerBackend {
|
|
50
|
+
/** Платформа Node.js, для которой предназначен бэкенд. */
|
|
51
|
+
readonly platform: NodeJS.Platform;
|
|
52
|
+
/** Человекочитаемое название планировщика (для GUI и логов). */
|
|
53
|
+
readonly title: string;
|
|
54
|
+
|
|
55
|
+
/** Создаёт (или пересоздаёт) задачу. */
|
|
56
|
+
createTask(options: CreateTaskOptions): Promise<void>;
|
|
57
|
+
/** Удаляет задачу. Повторное удаление не считается ошибкой. */
|
|
58
|
+
deleteTask(name: string): Promise<void>;
|
|
59
|
+
/** Запускает задачу немедленно. */
|
|
60
|
+
runTask(name: string): Promise<RunTaskResult>;
|
|
61
|
+
/** Возвращает список задач плагина (короткие имена). */
|
|
62
|
+
listTasks(): Promise<ScheduledTaskInfo[]>;
|
|
63
|
+
/** Ставит задачу на паузу (disable). */
|
|
64
|
+
pauseTask(name: string): Promise<void>;
|
|
65
|
+
/** Снимает задачу с паузы (enable). */
|
|
66
|
+
resumeTask(name: string): Promise<void>;
|
|
67
|
+
}
|