agent-steward 0.0.2 → 0.0.3
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 +25 -2
- package/CROSS_PLATFORM.md +11 -9
- package/README.md +9 -8
- package/ROADMAP-STRATEGY.md +93 -44
- package/ROADMAP.md +114 -999
- package/dist/core/cron-to-schtasks.d.ts +0 -8
- package/dist/core/cron-to-schtasks.d.ts.map +1 -1
- package/dist/core/cron-to-schtasks.js +11 -86
- package/dist/core/dry-run.js +1 -1
- package/dist/core/file-watcher.js +9 -9
- package/dist/core/git-trigger.js +4 -4
- package/dist/core/lock.js +2 -4
- package/dist/core/one-shot.d.ts +27 -5
- package/dist/core/one-shot.d.ts.map +1 -1
- package/dist/core/one-shot.js +53 -10
- package/dist/core/otel.js +2 -2
- package/dist/core/ps-wrapper.d.ts +1 -1
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +55 -35
- package/dist/core/record-history.js +22 -22
- package/dist/core/schedule-v2.d.ts +2 -2
- package/dist/core/schedule-v2.d.ts.map +1 -1
- package/dist/core/schedule-v2.js +7 -7
- package/dist/core/scheduler/at-fallback.d.ts +42 -0
- package/dist/core/scheduler/at-fallback.d.ts.map +1 -0
- package/dist/core/scheduler/at-fallback.js +70 -0
- package/dist/core/scheduler/linux.d.ts +3 -1
- package/dist/core/scheduler/linux.d.ts.map +1 -1
- package/dist/core/scheduler/linux.js +43 -7
- package/dist/core/scheduler/mac.d.ts +14 -8
- package/dist/core/scheduler/mac.d.ts.map +1 -1
- package/dist/core/scheduler/mac.js +71 -22
- package/dist/core/scheduler/posix.d.ts.map +1 -1
- package/dist/core/scheduler/posix.js +12 -1
- package/dist/core/scheduler/registry.d.ts +2 -0
- package/dist/core/scheduler/registry.d.ts.map +1 -1
- package/dist/core/scheduler/windows.d.ts +16 -3
- package/dist/core/scheduler/windows.d.ts.map +1 -1
- package/dist/core/scheduler/windows.js +249 -96
- package/dist/core/secrets.js +2 -2
- package/dist/core/self-analysis.js +55 -55
- package/dist/core/summary.js +1 -1
- package/dist/core/triage-chain.js +1 -1
- package/dist/core/triage-worker.js +2 -2
- package/dist/core/triage.js +1 -1
- package/dist/core/wrappers/bash.js +33 -33
- package/dist/db/index.d.ts +2 -0
- package/dist/db/index.d.ts.map +1 -1
- package/dist/db/index.js +9 -1
- package/dist/db/run-journal.d.ts +60 -0
- package/dist/db/run-journal.d.ts.map +1 -0
- package/dist/db/run-journal.js +143 -0
- package/dist/db/run-resume.d.ts +48 -0
- package/dist/db/run-resume.d.ts.map +1 -0
- package/dist/db/run-resume.js +137 -0
- package/dist/db/runs-repo.d.ts +120 -0
- package/dist/db/runs-repo.d.ts.map +1 -0
- package/dist/db/runs-repo.js +319 -0
- package/dist/db/schema.d.ts +16 -2
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +190 -35
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +66 -36
- package/dist/notifications.js +18 -18
- package/dist/profiles.d.ts +7 -3
- package/dist/profiles.d.ts.map +1 -1
- package/dist/profiles.js +85 -7
- package/dist/rpc.d.ts +109 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +89 -0
- package/dist/server.d.ts +2 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +20 -19
- package/dist/shared/jobs-view.d.ts.map +1 -1
- package/dist/skill.js +1 -1
- package/dist/task-transfer.d.ts +1 -1
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +14 -10
- package/dist/types.d.ts +20 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +37 -9
- package/dist/workspaces.js +1 -1
- package/docs/ARCHITECTURE.md +110 -8
- package/docs/COMPATIBILITY.md +10 -6
- package/docs/CONCEPT.md +15 -3
- package/docs/CROSS_PLATFORM.ru.md +11 -9
- package/docs/CROSS_PLATFORM.zh.md +11 -9
- package/docs/FAQ.md +2 -2
- package/docs/FAQ.ru.md +2 -2
- package/docs/FAQ.zh.md +2 -2
- package/docs/FEATURES.md +5 -4
- package/docs/FEATURES.zh.md +5 -4
- package/docs/MIGRATION.md +34 -26
- package/docs/README.ru.md +26 -7
- package/docs/README.zh.md +9 -8
- package/docs/V1-V2-COMPATIBILITY-PLAN.md +6 -6
- package/gui-experimental.cjs +8 -8
- package/index.js +1 -0
- package/locales/en.json +1 -0
- package/locales/ru.json +1 -0
- package/locales/zh.json +1 -0
- package/package.json +31 -10
- package/src/core/analytics.ts +2 -2
- package/src/core/audit.ts +17 -17
- package/src/core/cron-to-schtasks.ts +14 -93
- package/src/core/dry-run.ts +26 -26
- package/src/core/file-watcher.ts +17 -17
- package/src/core/git-trigger.ts +9 -9
- package/src/core/glob.ts +1 -1
- package/src/core/local-ai.ts +2 -2
- package/src/core/lock.ts +9 -9
- package/src/core/matrix.ts +31 -31
- package/src/core/native-notify.ts +2 -2
- package/src/core/one-shot.ts +63 -13
- package/src/core/otel.ts +4 -4
- package/src/core/permissions.ts +5 -5
- package/src/core/prometheus.ts +17 -17
- package/src/core/ps-wrapper.ts +57 -37
- package/src/core/record-history.ts +40 -40
- package/src/core/retention.ts +3 -3
- package/src/core/savings.ts +1 -1
- package/src/core/schedule-gate.ts +12 -12
- package/src/core/schedule-v2.ts +24 -24
- package/src/core/scheduler/at-fallback.ts +113 -0
- package/src/core/scheduler/index.ts +3 -3
- package/src/core/scheduler/linux.ts +64 -13
- package/src/core/scheduler/logs.ts +1 -1
- package/src/core/scheduler/mac.ts +112 -60
- package/src/core/scheduler/posix.ts +15 -1
- package/src/core/scheduler/registry.ts +6 -4
- package/src/core/scheduler/windows.ts +295 -125
- package/src/core/secrets.ts +13 -13
- package/src/core/self-analysis.ts +61 -61
- package/src/core/session.ts +3 -3
- package/src/core/structured-log.ts +3 -3
- package/src/core/summary.ts +25 -25
- package/src/core/telegram.ts +16 -16
- package/src/core/triage-chain.ts +4 -4
- package/src/core/triage-compare.ts +8 -8
- package/src/core/triage-rules.ts +4 -4
- package/src/core/triage-shadow.ts +7 -7
- package/src/core/triage-worker.ts +6 -6
- package/src/core/triage.ts +23 -23
- package/src/core/watch-paths.ts +1 -1
- package/src/core/wrappers/bash.ts +41 -41
- package/src/db/git-state-repo.ts +1 -1
- package/src/db/history-repo.ts +22 -22
- package/src/db/index.ts +16 -6
- package/src/db/metrics-repo.ts +10 -10
- package/src/db/migrate.ts +10 -10
- package/src/db/recovery.ts +3 -3
- package/src/db/run-journal.ts +212 -0
- package/src/db/run-resume.ts +220 -0
- package/src/db/runs-repo.ts +481 -0
- package/src/db/schema.ts +205 -44
- package/src/db/settings-repo.ts +2 -2
- package/src/db/tasks-repo.ts +10 -10
- package/src/db/templates-repo.ts +7 -7
- package/src/gui.tsx +1 -1
- package/src/history.ts +4 -4
- package/src/i18n.ts +7 -7
- package/src/index.ts +341 -304
- package/src/integrations.ts +6 -6
- package/src/notifications.ts +76 -76
- package/src/profiles.ts +98 -7
- package/src/rpc.ts +96 -1
- package/src/schtasks.ts +2 -2
- package/src/server.ts +43 -42
- package/src/settings.ts +44 -44
- package/src/shared/jobs-view.ts +60 -60
- package/src/skill.ts +1 -1
- package/src/task-transfer.ts +58 -56
- package/src/templates.ts +1 -1
- package/src/types.ts +45 -10
- package/src/workspaces.ts +16 -16
- package/dist/core/self-analysis.test.d.ts +0 -2
- package/dist/core/self-analysis.test.d.ts.map +0 -1
- package/dist/core/self-analysis.test.js +0 -219
- package/dist/gui-experimental.cjs +0 -1
|
@@ -2,10 +2,16 @@ import { execFile, spawn } from "node:child_process";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { promisify } from "node:util";
|
|
4
4
|
import { buildAtTimestamp } from "../one-shot.js";
|
|
5
|
+
import {
|
|
6
|
+
cancelAtFallback,
|
|
7
|
+
isAtMissingError,
|
|
8
|
+
isPidJobId,
|
|
9
|
+
scheduleAtFallback,
|
|
10
|
+
} from "./at-fallback.js";
|
|
5
11
|
import { needsPollMode } from "../schedule-v2.js";
|
|
6
12
|
import { LockManager, withLockWait } from "../lock.js";
|
|
7
13
|
import { getBasePluginDir, getProfileName } from "../../profiles.js";
|
|
8
|
-
import { taskFolderNameForProfile } from "../../types.js";
|
|
14
|
+
import { taskFolderNameForProfile, legacyTaskFolderNameForProfile } from "../../types.js";
|
|
9
15
|
import { PosixSchedulerBase, shellQuote } from "./posix.js";
|
|
10
16
|
import type { RegistryEntry } from "./registry.js";
|
|
11
17
|
|
|
@@ -24,18 +30,24 @@ const execFileAsync = promisify(execFile);
|
|
|
24
30
|
*/
|
|
25
31
|
export class LinuxScheduler extends PosixSchedulerBase {
|
|
26
32
|
readonly platform: NodeJS.Platform = "linux";
|
|
27
|
-
readonly title = "
|
|
33
|
+
readonly title = "agent-steward by DeadSno";
|
|
28
34
|
|
|
29
35
|
private readonly blockBegin: string;
|
|
30
36
|
private readonly blockEnd: string;
|
|
37
|
+
private readonly legacyBlockBegin: string;
|
|
38
|
+
private readonly legacyBlockEnd: string;
|
|
31
39
|
private readonly ownsLegacyBlock: boolean;
|
|
32
40
|
|
|
33
41
|
constructor(profile: string = getProfileName()) {
|
|
34
42
|
super("linux", profile);
|
|
35
43
|
const folderName = taskFolderNameForProfile(profile);
|
|
44
|
+
const legacyFolderName = legacyTaskFolderNameForProfile(profile);
|
|
36
45
|
this.blockBegin = `# >>> opencode-scheduler:${folderName} >>>`;
|
|
37
46
|
this.blockEnd = `# <<< opencode-scheduler:${folderName} <<<`;
|
|
38
|
-
this.
|
|
47
|
+
this.legacyBlockBegin = `# >>> opencode-scheduler:${legacyFolderName} >>>`;
|
|
48
|
+
this.legacyBlockEnd = `# <<< opencode-scheduler:${legacyFolderName} <<<`;
|
|
49
|
+
// Древний бессуффиксный блок принадлежит только профилю default.
|
|
50
|
+
this.ownsLegacyBlock = profile === "default";
|
|
39
51
|
}
|
|
40
52
|
|
|
41
53
|
private cronLine(entry: RegistryEntry): string {
|
|
@@ -48,7 +60,11 @@ export class LinuxScheduler extends PosixSchedulerBase {
|
|
|
48
60
|
// crontab понимает только 5-полевой cron. Расширенные выражения (L, #,
|
|
49
61
|
// списки, @daily и т.п.) нельзя писать в crontab как есть — опрашиваем
|
|
50
62
|
// каждую минуту, а решение о запуске принимает gate во враппере.
|
|
51
|
-
|
|
63
|
+
// Задачи с чужой IANA-таймзоной (не системной) тоже уходят в poll-режим,
|
|
64
|
+
// иначе crontab сработает по системному времени, а не по таймзоне задачи.
|
|
65
|
+
const schedule = needsPollMode(entry.schedule, entry.timezone)
|
|
66
|
+
? "* * * * *"
|
|
67
|
+
: entry.schedule;
|
|
52
68
|
return `${schedule} ${cmd}`;
|
|
53
69
|
}
|
|
54
70
|
|
|
@@ -91,9 +107,13 @@ export class LinuxScheduler extends PosixSchedulerBase {
|
|
|
91
107
|
const legacyEnd = "# <<< opencode-scheduler <<<";
|
|
92
108
|
const ownsLegacy = this.ownsLegacyBlock;
|
|
93
109
|
const isBegin = (line: string) =>
|
|
94
|
-
line === this.blockBegin ||
|
|
110
|
+
line === this.blockBegin ||
|
|
111
|
+
line === this.legacyBlockBegin ||
|
|
112
|
+
(ownsLegacy && line === legacyBegin);
|
|
95
113
|
const isEnd = (line: string) =>
|
|
96
|
-
line === this.blockEnd ||
|
|
114
|
+
line === this.blockEnd ||
|
|
115
|
+
line === this.legacyBlockEnd ||
|
|
116
|
+
(ownsLegacy && line === legacyEnd);
|
|
97
117
|
const lines = content.split(/\r?\n/);
|
|
98
118
|
const result: string[] = [];
|
|
99
119
|
let inside = false;
|
|
@@ -135,7 +155,7 @@ export class LinuxScheduler extends PosixSchedulerBase {
|
|
|
135
155
|
// друг друга. Кросс-процессный замок живёт в базовой директории плагина
|
|
136
156
|
// (общей для всех профилей) и ждёт освобождения вместо пропуска.
|
|
137
157
|
const crontabLock = new LockManager(
|
|
138
|
-
path.join(getBasePluginDir(), "locks")
|
|
158
|
+
path.join(getBasePluginDir(), "locks"),
|
|
139
159
|
);
|
|
140
160
|
await withLockWait(
|
|
141
161
|
crontabLock,
|
|
@@ -153,7 +173,7 @@ export class LinuxScheduler extends PosixSchedulerBase {
|
|
|
153
173
|
const next = [base, hasTasks ? block : ""].filter(Boolean).join("\n");
|
|
154
174
|
await this.writeCrontab(next);
|
|
155
175
|
},
|
|
156
|
-
{ timeoutMs: 15000, staleMs: 60000 }
|
|
176
|
+
{ timeoutMs: 15000, staleMs: 60000 },
|
|
157
177
|
);
|
|
158
178
|
}
|
|
159
179
|
|
|
@@ -185,24 +205,49 @@ export class LinuxScheduler extends PosixSchedulerBase {
|
|
|
185
205
|
stderr += String(chunk);
|
|
186
206
|
});
|
|
187
207
|
child.on("error", (err) => {
|
|
208
|
+
// P1-7.T1.2: `at` может отсутствовать (минимальные образы, Alpine и
|
|
209
|
+
// т.п.). Не роняем задачу — планируем отвязанный bash-процесс.
|
|
210
|
+
if (isAtMissingError(err)) {
|
|
211
|
+
void scheduleAtFallback(entry, this.atCommand(entry))
|
|
212
|
+
.then((jobId) => {
|
|
213
|
+
console.warn(
|
|
214
|
+
`[agent-steward] at не найден — задача "${entry.name}" запланирована через fallback (${jobId}). ` +
|
|
215
|
+
"Fallback не переживает перезагрузку; установите пакет at.",
|
|
216
|
+
);
|
|
217
|
+
resolve(jobId);
|
|
218
|
+
})
|
|
219
|
+
.catch((fallbackErr) => {
|
|
220
|
+
reject(
|
|
221
|
+
new Error(
|
|
222
|
+
`Не удалось вызвать at и fallback-планировщик: ${
|
|
223
|
+
fallbackErr instanceof Error
|
|
224
|
+
? fallbackErr.message
|
|
225
|
+
: String(fallbackErr)
|
|
226
|
+
}`,
|
|
227
|
+
),
|
|
228
|
+
);
|
|
229
|
+
});
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
188
232
|
reject(
|
|
189
233
|
new Error(
|
|
190
234
|
`Не удалось вызвать at (установите пакет at): ${
|
|
191
235
|
err instanceof Error ? err.message : String(err)
|
|
192
|
-
}
|
|
193
|
-
)
|
|
236
|
+
}`,
|
|
237
|
+
),
|
|
194
238
|
);
|
|
195
239
|
});
|
|
196
240
|
child.on("close", (code) => {
|
|
197
241
|
if (code !== 0) {
|
|
198
242
|
reject(
|
|
199
243
|
new Error(
|
|
200
|
-
`at завершился с кодом ${code}: ${stderr.trim() || stdout.trim()}
|
|
201
|
-
)
|
|
244
|
+
`at завершился с кодом ${code}: ${stderr.trim() || stdout.trim()}`,
|
|
245
|
+
),
|
|
202
246
|
);
|
|
203
247
|
return;
|
|
204
248
|
}
|
|
205
|
-
|
|
249
|
+
// GNU at пишет «job N at …» в stderr, а не в stdout — ищем в обоих потоках.
|
|
250
|
+
const match = /job\s+(\d+)/i.exec(stdout + "\n" + stderr);
|
|
206
251
|
if (!match) {
|
|
207
252
|
reject(new Error(`at не вернул id задания: ${stdout.trim()}`));
|
|
208
253
|
return;
|
|
@@ -216,6 +261,12 @@ export class LinuxScheduler extends PosixSchedulerBase {
|
|
|
216
261
|
/** Отменяет задание at, если оно ещё существует. */
|
|
217
262
|
private async cancelAt(entry: RegistryEntry): Promise<void> {
|
|
218
263
|
if (!entry.atJobId) return;
|
|
264
|
+
if (isPidJobId(entry.atJobId)) {
|
|
265
|
+
// P1-7.T1.2: снимаем fallback-процесс, а не at-задание.
|
|
266
|
+
cancelAtFallback(entry.atJobId);
|
|
267
|
+
delete entry.atJobId;
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
219
270
|
try {
|
|
220
271
|
await execFileAsync("atrm", [entry.atJobId]);
|
|
221
272
|
} catch {
|
|
@@ -10,7 +10,7 @@ import { LOG_DIR, sanitizeName } from "../../types.js";
|
|
|
10
10
|
*/
|
|
11
11
|
export async function getTaskLogs(
|
|
12
12
|
name: string,
|
|
13
|
-
limit = 50
|
|
13
|
+
limit = 50,
|
|
14
14
|
): Promise<{ logs: string; error?: string }> {
|
|
15
15
|
const logPath = path.join(LOG_DIR, `${sanitizeName(name)}.log`);
|
|
16
16
|
try {
|
|
@@ -6,7 +6,11 @@ import path from "node:path";
|
|
|
6
6
|
import { promisify } from "node:util";
|
|
7
7
|
import { sanitizeName } from "../../types.js";
|
|
8
8
|
import { getProfileDir, getProfileName } from "../../profiles.js";
|
|
9
|
-
import { buildLaunchdCalendar, launchdLabel } from "../one-shot.js";
|
|
9
|
+
import { buildLaunchdCalendar, buildOneShotGuardCommand, launchdLabel } from "../one-shot.js";
|
|
10
|
+
import {
|
|
11
|
+
needsPollMode,
|
|
12
|
+
systemTimeZone,
|
|
13
|
+
} from "../schedule-v2.js";
|
|
10
14
|
import { PosixSchedulerBase } from "./posix.js";
|
|
11
15
|
import type { RegistryEntry } from "./registry.js";
|
|
12
16
|
|
|
@@ -24,12 +28,23 @@ function xmlEscape(value: string): string {
|
|
|
24
28
|
.replace(/"/g, """);
|
|
25
29
|
}
|
|
26
30
|
|
|
31
|
+
/** Один элемент StartCalendarInterval. */
|
|
32
|
+
interface LaunchdCalendar {
|
|
33
|
+
Minute?: number;
|
|
34
|
+
Hour?: number;
|
|
35
|
+
Weekday?: number;
|
|
36
|
+
Month?: number;
|
|
37
|
+
Day?: number;
|
|
38
|
+
}
|
|
39
|
+
|
|
27
40
|
/** Расписание launchd, полученное из cron-выражения. */
|
|
28
41
|
interface LaunchdSchedule {
|
|
29
|
-
/** StartInterval в секундах (для
|
|
42
|
+
/** StartInterval в секундах (для poll-режима «каждую минуту»). */
|
|
30
43
|
interval?: number;
|
|
31
|
-
/** StartCalendarInterval (
|
|
32
|
-
calendar?:
|
|
44
|
+
/** Одиночный StartCalendarInterval (фиксированное время). */
|
|
45
|
+
calendar?: LaunchdCalendar;
|
|
46
|
+
/** Массив StartCalendarInterval (например, минуты 0,15,30,45). */
|
|
47
|
+
calendars?: LaunchdCalendar[];
|
|
33
48
|
}
|
|
34
49
|
|
|
35
50
|
/**
|
|
@@ -40,7 +55,7 @@ export function cronToLaunchdSchedule(cron: string): LaunchdSchedule {
|
|
|
40
55
|
const fields = cron.trim().split(/\s+/);
|
|
41
56
|
if (fields.length !== 5) {
|
|
42
57
|
throw new Error(
|
|
43
|
-
`Ожидалось 5 полей cron-выражения, получено ${fields.length}
|
|
58
|
+
`Ожидалось 5 полей cron-выражения, получено ${fields.length}.`,
|
|
44
59
|
);
|
|
45
60
|
}
|
|
46
61
|
|
|
@@ -61,7 +76,14 @@ export function cronToLaunchdSchedule(cron: string): LaunchdSchedule {
|
|
|
61
76
|
const step = /^\*\/(\d+)$/.exec(minute);
|
|
62
77
|
if (step && star(hour) && star(dayOfMonth) && star(month) && star(dayOfWeek)) {
|
|
63
78
|
const n = parseInt(step[1], 10);
|
|
64
|
-
if (n > 0)
|
|
79
|
+
if (n > 0) {
|
|
80
|
+
// P1-6: выравниваем по cron-сетке (0, N, 2N, …), а не отсчитываем
|
|
81
|
+
// интервал от момента загрузки агента. launchd принимает массив
|
|
82
|
+
// StartCalendarInterval — по dict на каждую минуту.
|
|
83
|
+
const calendars: LaunchdCalendar[] = [];
|
|
84
|
+
for (let m = 0; m < 60; m += n) calendars.push({ Minute: m });
|
|
85
|
+
return { calendars };
|
|
86
|
+
}
|
|
65
87
|
}
|
|
66
88
|
|
|
67
89
|
const m = intIn(minute, 0, 59);
|
|
@@ -92,84 +114,115 @@ export function cronToLaunchdSchedule(cron: string): LaunchdSchedule {
|
|
|
92
114
|
return { calendar: { Minute: m, Hour: h, Weekday: d } };
|
|
93
115
|
}
|
|
94
116
|
|
|
117
|
+
/** Добавляет поля одного StartCalendarInterval-dict с заданным отступом. */
|
|
118
|
+
function pushCalendarFields(
|
|
119
|
+
out: string[],
|
|
120
|
+
cal: LaunchdCalendar,
|
|
121
|
+
indent: string,
|
|
122
|
+
): void {
|
|
123
|
+
const fields: [string, number | undefined][] = [
|
|
124
|
+
["Minute", cal.Minute],
|
|
125
|
+
["Hour", cal.Hour],
|
|
126
|
+
["Weekday", cal.Weekday],
|
|
127
|
+
["Month", cal.Month],
|
|
128
|
+
["Day", cal.Day],
|
|
129
|
+
];
|
|
130
|
+
for (const [key, value] of fields) {
|
|
131
|
+
if (value === undefined) continue;
|
|
132
|
+
out.push(`${indent}<key>${key}</key>`, `${indent}<integer>${value}</integer>`);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
95
136
|
/** Собирает XML plist для задачи. */
|
|
96
137
|
function buildPlist(label: string, entry: RegistryEntry): string {
|
|
97
138
|
const schedule: {
|
|
98
139
|
interval?: number;
|
|
99
|
-
calendar?:
|
|
100
|
-
|
|
101
|
-
Hour?: number;
|
|
102
|
-
Weekday?: number;
|
|
103
|
-
Month?: number;
|
|
104
|
-
Day?: number;
|
|
105
|
-
};
|
|
140
|
+
calendar?: LaunchdCalendar;
|
|
141
|
+
calendars?: LaunchdCalendar[];
|
|
106
142
|
} =
|
|
107
143
|
entry.triggerType === "once"
|
|
108
144
|
? (() => {
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
145
|
+
if (!entry.runAt) {
|
|
146
|
+
throw new Error(
|
|
147
|
+
`Задача "${entry.name}": для one-shot не задано runAt.`,
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
return { calendar: buildLaunchdCalendar(entry.runAt) };
|
|
151
|
+
})()
|
|
116
152
|
: entry.triggerType !== "cron"
|
|
117
153
|
? { interval: 315_360_000 } // file/mcp-event: 10 лет — фактически «никогда».
|
|
118
|
-
:
|
|
154
|
+
: (() => {
|
|
155
|
+
// P1-5: чужой IANA-таймзона — poll-режим (StartInterval 60 + gate во враппере),
|
|
156
|
+
// иначе crontab сработает по системному времени, а не по таймзоне задачи.
|
|
157
|
+
const tz = entry.timezone?.trim();
|
|
158
|
+
if (tz && tz !== systemTimeZone()) return { interval: 60 };
|
|
159
|
+
// P1-6: неконвертируемый cron (списки, диапазоны, L, #, @daily и т.п.)
|
|
160
|
+
// — poll-режим вместо бросания ошибки. Gate во враппере уже есть
|
|
161
|
+
// (buildScheduleGate), поэтому достаточно StartInterval 60.
|
|
162
|
+
try {
|
|
163
|
+
return cronToLaunchdSchedule(entry.schedule);
|
|
164
|
+
} catch {
|
|
165
|
+
return { interval: 60 };
|
|
166
|
+
}
|
|
167
|
+
})();
|
|
119
168
|
|
|
120
169
|
const scheduleXml: string[] = [];
|
|
121
170
|
if (schedule.interval !== undefined) {
|
|
122
171
|
scheduleXml.push(
|
|
123
172
|
" <key>StartInterval</key>",
|
|
124
|
-
` <integer>${schedule.interval}</integer
|
|
173
|
+
` <integer>${schedule.interval}</integer>`,
|
|
125
174
|
);
|
|
126
175
|
}
|
|
127
176
|
if (schedule.calendar) {
|
|
128
177
|
scheduleXml.push(" <key>StartCalendarInterval</key>", " <dict>");
|
|
129
|
-
|
|
130
|
-
scheduleXml.push(
|
|
131
|
-
" <key>Minute</key>",
|
|
132
|
-
` <integer>${schedule.calendar.Minute}</integer>`
|
|
133
|
-
);
|
|
134
|
-
}
|
|
135
|
-
if (schedule.calendar.Hour !== undefined) {
|
|
136
|
-
scheduleXml.push(
|
|
137
|
-
" <key>Hour</key>",
|
|
138
|
-
` <integer>${schedule.calendar.Hour}</integer>`
|
|
139
|
-
);
|
|
140
|
-
}
|
|
141
|
-
if (schedule.calendar.Weekday !== undefined) {
|
|
142
|
-
scheduleXml.push(
|
|
143
|
-
" <key>Weekday</key>",
|
|
144
|
-
` <integer>${schedule.calendar.Weekday}</integer>`
|
|
145
|
-
);
|
|
146
|
-
}
|
|
147
|
-
if (schedule.calendar.Month !== undefined) {
|
|
148
|
-
scheduleXml.push(
|
|
149
|
-
" <key>Month</key>",
|
|
150
|
-
` <integer>${schedule.calendar.Month}</integer>`
|
|
151
|
-
);
|
|
152
|
-
}
|
|
153
|
-
if (schedule.calendar.Day !== undefined) {
|
|
154
|
-
scheduleXml.push(
|
|
155
|
-
" <key>Day</key>",
|
|
156
|
-
` <integer>${schedule.calendar.Day}</integer>`
|
|
157
|
-
);
|
|
158
|
-
}
|
|
178
|
+
pushCalendarFields(scheduleXml, schedule.calendar, " ");
|
|
159
179
|
scheduleXml.push(" </dict>");
|
|
160
180
|
}
|
|
181
|
+
if (schedule.calendars && schedule.calendars.length > 0) {
|
|
182
|
+
scheduleXml.push(" <key>StartCalendarInterval</key>", " <array>");
|
|
183
|
+
for (const cal of schedule.calendars) {
|
|
184
|
+
scheduleXml.push(" <dict>");
|
|
185
|
+
pushCalendarFields(scheduleXml, cal, " ");
|
|
186
|
+
scheduleXml.push(" </dict>");
|
|
187
|
+
}
|
|
188
|
+
scheduleXml.push(" </array>");
|
|
189
|
+
}
|
|
161
190
|
|
|
162
191
|
const workdir = entry.workingDirectory || process.cwd();
|
|
163
192
|
const log = entry.logFile;
|
|
164
193
|
const logXml = log
|
|
165
194
|
? [
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
195
|
+
" <key>StandardOutPath</key>",
|
|
196
|
+
` <string>${xmlEscape(log)}</string>`,
|
|
197
|
+
" <key>StandardErrorPath</key>",
|
|
198
|
+
` <string>${xmlEscape(log)}</string>`,
|
|
199
|
+
]
|
|
171
200
|
: [];
|
|
172
201
|
|
|
202
|
+
// P2-12.T2: launchd не умеет год в StartCalendarInterval. Для one-shot
|
|
203
|
+
// запускаем bash -c с проверкой runAt и маркером выполнения, иначе задача
|
|
204
|
+
// сработает в ближайшую годовщину и повторится через год.
|
|
205
|
+
const programArgsXml =
|
|
206
|
+
entry.triggerType === "once" && entry.runAt
|
|
207
|
+
? (() => {
|
|
208
|
+
const epoch = Math.floor(Date.parse(entry.runAt) / 1000);
|
|
209
|
+
const stamp = path.join(
|
|
210
|
+
LAUNCH_AGENTS_DIR,
|
|
211
|
+
`${label}.once-${epoch}.done`,
|
|
212
|
+
);
|
|
213
|
+
return [
|
|
214
|
+
" <string>/bin/bash</string>",
|
|
215
|
+
" <string>-c</string>",
|
|
216
|
+
` <string>${xmlEscape(
|
|
217
|
+
buildOneShotGuardCommand(entry.command, entry.runAt, stamp),
|
|
218
|
+
)}</string>`,
|
|
219
|
+
];
|
|
220
|
+
})()
|
|
221
|
+
: [
|
|
222
|
+
" <string>/bin/bash</string>",
|
|
223
|
+
` <string>${xmlEscape(entry.command)}</string>`,
|
|
224
|
+
];
|
|
225
|
+
|
|
173
226
|
return [
|
|
174
227
|
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
175
228
|
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" ' +
|
|
@@ -180,8 +233,7 @@ function buildPlist(label: string, entry: RegistryEntry): string {
|
|
|
180
233
|
` <string>${xmlEscape(label)}</string>`,
|
|
181
234
|
" <key>ProgramArguments</key>",
|
|
182
235
|
" <array>",
|
|
183
|
-
|
|
184
|
-
` <string>${xmlEscape(entry.command)}</string>`,
|
|
236
|
+
...programArgsXml,
|
|
185
237
|
" </array>",
|
|
186
238
|
" <key>WorkingDirectory</key>",
|
|
187
239
|
` <string>${xmlEscape(workdir)}</string>`,
|
|
@@ -204,7 +256,7 @@ function buildPlist(label: string, entry: RegistryEntry): string {
|
|
|
204
256
|
*/
|
|
205
257
|
export class MacScheduler extends PosixSchedulerBase {
|
|
206
258
|
readonly platform: NodeJS.Platform = "darwin";
|
|
207
|
-
readonly title = "
|
|
259
|
+
readonly title = "agent-steward by DeadSno";
|
|
208
260
|
|
|
209
261
|
constructor(profile: string = getProfileName()) {
|
|
210
262
|
super("mac", profile);
|
|
@@ -45,6 +45,7 @@ export abstract class PosixSchedulerBase implements SchedulerBackend {
|
|
|
45
45
|
createdAt: new Date().toISOString(),
|
|
46
46
|
...(options.model ? { model: options.model } : {}),
|
|
47
47
|
...(options.priority !== undefined ? { priority: options.priority } : {}),
|
|
48
|
+
...(options.timezone ? { timezone: options.timezone } : {}),
|
|
48
49
|
};
|
|
49
50
|
|
|
50
51
|
await this.registry.upsert(entry);
|
|
@@ -98,6 +99,19 @@ export abstract class PosixSchedulerBase implements SchedulerBackend {
|
|
|
98
99
|
stdio: "ignore",
|
|
99
100
|
cwd: entry.workingDirectory || process.cwd(),
|
|
100
101
|
});
|
|
102
|
+
|
|
103
|
+
// spawn не бросает синхронно: ошибки (например, удалённый
|
|
104
|
+
// workingDirectory → ENOENT) приходят событием 'error'. Без слушателя
|
|
105
|
+
// это uncaught exception в plugin-host. Ждём 'spawn' либо 'error'.
|
|
106
|
+
const spawnError = await new Promise<Error | null>((resolve) => {
|
|
107
|
+
child.once("spawn", () => resolve(null));
|
|
108
|
+
child.once("error", (error) => resolve(error));
|
|
109
|
+
});
|
|
110
|
+
if (spawnError) {
|
|
111
|
+
throw new Error(
|
|
112
|
+
`Не удалось запустить задачу "${name}": ${spawnError.message}`,
|
|
113
|
+
);
|
|
114
|
+
}
|
|
101
115
|
child.unref();
|
|
102
116
|
|
|
103
117
|
return { alreadyRunning: false };
|
|
@@ -110,5 +124,5 @@ export abstract class PosixSchedulerBase implements SchedulerBackend {
|
|
|
110
124
|
*/
|
|
111
125
|
export function shellQuote(value: string): string {
|
|
112
126
|
if (value === "") return "''";
|
|
113
|
-
return `'${value.replace(/'/g,
|
|
127
|
+
return `'${value.replace(/'/g, "'\\''")}'`;
|
|
114
128
|
}
|
|
@@ -27,6 +27,8 @@ export interface RegistryEntry {
|
|
|
27
27
|
model?: string;
|
|
28
28
|
/** Приоритет задачи 0..10 (опционально). */
|
|
29
29
|
priority?: number;
|
|
30
|
+
/** IANA-таймзона задачи (опционально, undefined — системная). */
|
|
31
|
+
timezone?: string;
|
|
30
32
|
}
|
|
31
33
|
|
|
32
34
|
/** Реестр задач конкретного бэкенда: <pluginDir>/scheduler-<backend>.json. */
|
|
@@ -51,7 +53,7 @@ export class TaskRegistry {
|
|
|
51
53
|
if (!Array.isArray(parsed)) return [];
|
|
52
54
|
return parsed.filter(
|
|
53
55
|
(entry): entry is RegistryEntry =>
|
|
54
|
-
entry && typeof entry.name === "string" && typeof entry.command === "string"
|
|
56
|
+
entry && typeof entry.name === "string" && typeof entry.command === "string",
|
|
55
57
|
);
|
|
56
58
|
} catch {
|
|
57
59
|
return [];
|
|
@@ -73,7 +75,7 @@ export class TaskRegistry {
|
|
|
73
75
|
async upsert(entry: RegistryEntry): Promise<void> {
|
|
74
76
|
const entries = await this.load();
|
|
75
77
|
const index = entries.findIndex(
|
|
76
|
-
(e) => e.name.toLowerCase() === entry.name.toLowerCase()
|
|
78
|
+
(e) => e.name.toLowerCase() === entry.name.toLowerCase(),
|
|
77
79
|
);
|
|
78
80
|
if (index === -1) entries.push(entry);
|
|
79
81
|
else entries[index] = entry;
|
|
@@ -83,14 +85,14 @@ export class TaskRegistry {
|
|
|
83
85
|
async remove(name: string): Promise<void> {
|
|
84
86
|
const entries = await this.load();
|
|
85
87
|
await this.save(
|
|
86
|
-
entries.filter((e) => e.name.toLowerCase() !== name.toLowerCase())
|
|
88
|
+
entries.filter((e) => e.name.toLowerCase() !== name.toLowerCase()),
|
|
87
89
|
);
|
|
88
90
|
}
|
|
89
91
|
|
|
90
92
|
async setPaused(name: string, paused: boolean): Promise<void> {
|
|
91
93
|
const entries = await this.load();
|
|
92
94
|
const entry = entries.find(
|
|
93
|
-
(e) => e.name.toLowerCase() === name.toLowerCase()
|
|
95
|
+
(e) => e.name.toLowerCase() === name.toLowerCase(),
|
|
94
96
|
);
|
|
95
97
|
if (!entry) return;
|
|
96
98
|
entry.paused = paused;
|