agent-steward 0.0.2 → 0.0.4
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 -2
- package/CROSS_PLATFORM.md +11 -9
- package/README.md +11 -10
- package/ROADMAP-STRATEGY.md +93 -44
- package/ROADMAP.md +148 -1017
- 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/dlq-api.d.ts +44 -0
- package/dist/core/dlq-api.d.ts.map +1 -0
- package/dist/core/dlq-api.js +68 -0
- package/dist/core/dry-run.d.ts.map +1 -1
- package/dist/core/dry-run.js +19 -2
- package/dist/core/file-watcher.js +9 -9
- package/dist/core/git-trigger.js +4 -4
- package/dist/core/lock.d.ts +20 -4
- package/dist/core/lock.d.ts.map +1 -1
- package/dist/core/lock.js +99 -26
- package/dist/core/one-shot.d.ts +31 -5
- package/dist/core/one-shot.d.ts.map +1 -1
- package/dist/core/one-shot.js +78 -10
- package/dist/core/opencode-cli.d.ts +28 -0
- package/dist/core/opencode-cli.d.ts.map +1 -0
- package/dist/core/opencode-cli.js +74 -0
- package/dist/core/opencode-models.d.ts +62 -0
- package/dist/core/opencode-models.d.ts.map +1 -0
- package/dist/core/opencode-models.js +277 -0
- 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 +66 -36
- package/dist/core/record-history.d.ts +15 -0
- package/dist/core/record-history.d.ts.map +1 -1
- package/dist/core/record-history.js +78 -54
- package/dist/core/router/dispatch.d.ts +36 -0
- package/dist/core/router/dispatch.d.ts.map +1 -0
- package/dist/core/router/dispatch.js +59 -0
- package/dist/core/router/escalation.d.ts +47 -0
- package/dist/core/router/escalation.d.ts.map +1 -0
- package/dist/core/router/escalation.js +87 -0
- package/dist/core/router/planner.d.ts +53 -0
- package/dist/core/router/planner.d.ts.map +1 -0
- package/dist/core/router/planner.js +113 -0
- package/dist/core/router/rules.d.ts +46 -0
- package/dist/core/router/rules.d.ts.map +1 -0
- package/dist/core/router/rules.js +85 -0
- package/dist/core/run-panel-api.d.ts +94 -0
- package/dist/core/run-panel-api.d.ts.map +1 -0
- package/dist/core/run-panel-api.js +169 -0
- package/dist/core/schedule-gate.js +5 -1
- package/dist/core/schedule-v2.d.ts +36 -2
- package/dist/core/schedule-v2.d.ts.map +1 -1
- package/dist/core/schedule-v2.js +98 -12
- package/dist/core/scheduler/at-fallback.d.ts +95 -0
- package/dist/core/scheduler/at-fallback.d.ts.map +1 -0
- package/dist/core/scheduler/at-fallback.js +200 -0
- package/dist/core/scheduler/linux.d.ts +13 -2
- package/dist/core/scheduler/linux.d.ts.map +1 -1
- package/dist/core/scheduler/linux.js +67 -13
- 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 +37 -2
- package/dist/core/scheduler/registry.d.ts +13 -0
- package/dist/core/scheduler/registry.d.ts.map +1 -1
- package/dist/core/scheduler/registry.js +83 -21
- package/dist/core/scheduler/run-now.d.ts +16 -0
- package/dist/core/scheduler/run-now.d.ts.map +1 -0
- package/dist/core/scheduler/run-now.js +28 -0
- 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.d.ts.map +1 -1
- package/dist/core/secrets.js +127 -30
- package/dist/core/self-analysis.js +55 -55
- package/dist/core/session.d.ts.map +1 -1
- package/dist/core/session.js +18 -11
- package/dist/core/summary.js +1 -1
- package/dist/core/task-name.d.ts +24 -0
- package/dist/core/task-name.d.ts.map +1 -0
- package/dist/core/task-name.js +40 -0
- 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.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +82 -37
- package/dist/db/capability-repo.d.ts +83 -0
- package/dist/db/capability-repo.d.ts.map +1 -0
- package/dist/db/capability-repo.js +182 -0
- package/dist/db/history-repo.d.ts +8 -0
- package/dist/db/history-repo.d.ts.map +1 -1
- package/dist/db/history-repo.js +19 -0
- package/dist/db/index.d.ts +6 -0
- package/dist/db/index.d.ts.map +1 -1
- package/dist/db/index.js +48 -2
- package/dist/db/migrate.d.ts.map +1 -1
- package/dist/db/migrate.js +3 -1
- package/dist/db/run-context.d.ts +103 -0
- package/dist/db/run-context.d.ts.map +1 -0
- package/dist/db/run-context.js +224 -0
- package/dist/db/run-dlq.d.ts +100 -0
- package/dist/db/run-dlq.d.ts.map +1 -0
- package/dist/db/run-dlq.js +191 -0
- 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 +51 -0
- package/dist/db/run-resume.d.ts.map +1 -0
- package/dist/db/run-resume.js +156 -0
- package/dist/db/runs-repo.d.ts +128 -0
- package/dist/db/runs-repo.d.ts.map +1 -0
- package/dist/db/runs-repo.js +342 -0
- package/dist/db/schema.d.ts +16 -2
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +342 -35
- package/dist/db/settings-repo.d.ts +11 -0
- package/dist/db/settings-repo.d.ts.map +1 -1
- package/dist/db/settings-repo.js +25 -0
- package/dist/db/step-idempotency.d.ts +51 -0
- package/dist/db/step-idempotency.d.ts.map +1 -0
- package/dist/db/step-idempotency.js +136 -0
- package/dist/index.d.ts +5 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +168 -40
- 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 +787 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +324 -0
- package/dist/server.d.ts +33 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +115 -54
- 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 +44 -9
- package/dist/workspaces.d.ts +25 -3
- package/dist/workspaces.d.ts.map +1 -1
- package/dist/workspaces.js +44 -9
- package/docs/ARCHITECTURE.md +335 -9
- package/docs/COMPATIBILITY.md +10 -6
- package/docs/CONCEPT.md +183 -91
- package/docs/CROSS_PLATFORM.ru.md +11 -9
- package/docs/CROSS_PLATFORM.zh.md +11 -9
- package/docs/EXECUTION-LOOP.md +196 -0
- 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 +27 -8
- package/docs/README.zh.md +11 -10
- package/docs/SAFETY.md +122 -0
- package/docs/SAVINGS.md +29 -0
- package/docs/SAVINGS.ru.md +29 -0
- package/docs/SAVINGS.zh.md +18 -0
- package/docs/V1-V2-COMPATIBILITY-PLAN.md +6 -6
- package/gui-experimental.cjs +8 -8
- package/index.js +1 -0
- package/locales/en.json +68 -0
- package/locales/ru.json +68 -0
- package/locales/zh.json +68 -0
- package/package.json +57 -11
- package/scripts/audit-bundle.mjs +215 -0
- 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/dlq-api.ts +98 -0
- package/src/core/dry-run.ts +51 -27
- 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 +104 -31
- package/src/core/matrix.ts +31 -31
- package/src/core/native-notify.ts +2 -2
- package/src/core/one-shot.ts +91 -13
- package/src/core/opencode-cli.ts +103 -0
- package/src/core/opencode-models.ts +315 -0
- 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 +68 -38
- package/src/core/record-history.ts +114 -76
- package/src/core/retention.ts +3 -3
- package/src/core/router/dispatch.ts +94 -0
- package/src/core/router/escalation.ts +129 -0
- package/src/core/router/planner.ts +166 -0
- package/src/core/router/rules.ts +109 -0
- package/src/core/run-panel-api.ts +262 -0
- package/src/core/savings.ts +1 -1
- package/src/core/schedule-gate.ts +17 -13
- package/src/core/schedule-v2.ts +138 -29
- package/src/core/scheduler/at-fallback.ts +298 -0
- package/src/core/scheduler/index.ts +3 -3
- package/src/core/scheduler/linux.ts +92 -19
- package/src/core/scheduler/logs.ts +1 -1
- package/src/core/scheduler/mac.ts +112 -60
- package/src/core/scheduler/posix.ts +35 -2
- package/src/core/scheduler/registry.ts +109 -26
- package/src/core/scheduler/run-now.ts +32 -0
- package/src/core/scheduler/windows.ts +295 -125
- package/src/core/secrets.ts +139 -39
- package/src/core/self-analysis.ts +61 -61
- package/src/core/session.ts +26 -13
- package/src/core/structured-log.ts +3 -3
- package/src/core/summary.ts +25 -25
- package/src/core/task-name.ts +67 -0
- 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 +90 -45
- package/src/db/capability-repo.ts +285 -0
- package/src/db/git-state-repo.ts +1 -1
- package/src/db/history-repo.ts +44 -22
- package/src/db/index.ts +53 -7
- package/src/db/metrics-repo.ts +10 -10
- package/src/db/migrate.ts +13 -11
- package/src/db/recovery.ts +3 -3
- package/src/db/run-context.ts +370 -0
- package/src/db/run-dlq.ts +310 -0
- package/src/db/run-journal.ts +212 -0
- package/src/db/run-resume.ts +256 -0
- package/src/db/runs-repo.ts +504 -0
- package/src/db/schema.ts +357 -44
- package/src/db/settings-repo.ts +33 -2
- package/src/db/step-idempotency.ts +185 -0
- package/src/db/tasks-repo.ts +10 -10
- package/src/db/templates-repo.ts +7 -7
- package/src/gui.tsx +516 -1
- package/src/history.ts +4 -4
- package/src/i18n.ts +7 -7
- package/src/index.ts +465 -308
- package/src/integrations.ts +6 -6
- package/src/notifications.ts +76 -76
- package/src/profiles.ts +98 -7
- package/src/rpc.ts +347 -1
- package/src/schtasks.ts +2 -2
- package/src/server.ts +155 -78
- 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 +54 -10
- package/src/workspaces.ts +73 -24
- 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,18 @@ 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 {
|
|
5
|
+
import {
|
|
6
|
+
cancelAtFallback,
|
|
7
|
+
isAtMissingError,
|
|
8
|
+
isPidJobId,
|
|
9
|
+
pruneStaleFallbackEntries,
|
|
10
|
+
scheduleAtFallback,
|
|
11
|
+
type PruneAtFallbackReport,
|
|
12
|
+
} from "./at-fallback.js";
|
|
13
|
+
import { needsPosixPollMode } from "../schedule-v2.js";
|
|
6
14
|
import { LockManager, withLockWait } from "../lock.js";
|
|
7
15
|
import { getBasePluginDir, getProfileName } from "../../profiles.js";
|
|
8
|
-
import { taskFolderNameForProfile } from "../../types.js";
|
|
16
|
+
import { taskFolderNameForProfile, legacyTaskFolderNameForProfile } from "../../types.js";
|
|
9
17
|
import { PosixSchedulerBase, shellQuote } from "./posix.js";
|
|
10
18
|
import type { RegistryEntry } from "./registry.js";
|
|
11
19
|
|
|
@@ -24,18 +32,24 @@ const execFileAsync = promisify(execFile);
|
|
|
24
32
|
*/
|
|
25
33
|
export class LinuxScheduler extends PosixSchedulerBase {
|
|
26
34
|
readonly platform: NodeJS.Platform = "linux";
|
|
27
|
-
readonly title = "
|
|
35
|
+
readonly title = "agent-steward by DeadSno";
|
|
28
36
|
|
|
29
37
|
private readonly blockBegin: string;
|
|
30
38
|
private readonly blockEnd: string;
|
|
39
|
+
private readonly legacyBlockBegin: string;
|
|
40
|
+
private readonly legacyBlockEnd: string;
|
|
31
41
|
private readonly ownsLegacyBlock: boolean;
|
|
32
42
|
|
|
33
43
|
constructor(profile: string = getProfileName()) {
|
|
34
44
|
super("linux", profile);
|
|
35
45
|
const folderName = taskFolderNameForProfile(profile);
|
|
46
|
+
const legacyFolderName = legacyTaskFolderNameForProfile(profile);
|
|
36
47
|
this.blockBegin = `# >>> opencode-scheduler:${folderName} >>>`;
|
|
37
48
|
this.blockEnd = `# <<< opencode-scheduler:${folderName} <<<`;
|
|
38
|
-
this.
|
|
49
|
+
this.legacyBlockBegin = `# >>> opencode-scheduler:${legacyFolderName} >>>`;
|
|
50
|
+
this.legacyBlockEnd = `# <<< opencode-scheduler:${legacyFolderName} <<<`;
|
|
51
|
+
// Древний бессуффиксный блок принадлежит только профилю default.
|
|
52
|
+
this.ownsLegacyBlock = profile === "default";
|
|
39
53
|
}
|
|
40
54
|
|
|
41
55
|
private cronLine(entry: RegistryEntry): string {
|
|
@@ -45,10 +59,14 @@ export class LinuxScheduler extends PosixSchedulerBase {
|
|
|
45
59
|
}
|
|
46
60
|
const log = entry.logFile ? ` >> ${shellQuote(entry.logFile)} 2>&1` : "";
|
|
47
61
|
const cmd = `/bin/bash ${shellQuote(entry.command)}${log}`;
|
|
48
|
-
//
|
|
49
|
-
//
|
|
50
|
-
//
|
|
51
|
-
|
|
62
|
+
// Vixie-совместимый 5-полевой cron crontab выполняет сам: списки,
|
|
63
|
+
// диапазоны, шаги и имена месяцев/дней недели писать как есть можно.
|
|
64
|
+
// Quartz-расширения (L, d#n) и @-макросы (не 5 полей) crontab не понимает —
|
|
65
|
+
// для них "* * * * *" + gate во враппере. Чужая IANA-таймзона тоже уходит
|
|
66
|
+
// в poll: иначе crontab сработает по системному времени задачи.
|
|
67
|
+
const schedule = needsPosixPollMode(entry.schedule, entry.timezone)
|
|
68
|
+
? "* * * * *"
|
|
69
|
+
: entry.schedule;
|
|
52
70
|
return `${schedule} ${cmd}`;
|
|
53
71
|
}
|
|
54
72
|
|
|
@@ -91,9 +109,13 @@ export class LinuxScheduler extends PosixSchedulerBase {
|
|
|
91
109
|
const legacyEnd = "# <<< opencode-scheduler <<<";
|
|
92
110
|
const ownsLegacy = this.ownsLegacyBlock;
|
|
93
111
|
const isBegin = (line: string) =>
|
|
94
|
-
line === this.blockBegin ||
|
|
112
|
+
line === this.blockBegin ||
|
|
113
|
+
line === this.legacyBlockBegin ||
|
|
114
|
+
(ownsLegacy && line === legacyBegin);
|
|
95
115
|
const isEnd = (line: string) =>
|
|
96
|
-
line === this.blockEnd ||
|
|
116
|
+
line === this.blockEnd ||
|
|
117
|
+
line === this.legacyBlockEnd ||
|
|
118
|
+
(ownsLegacy && line === legacyEnd);
|
|
97
119
|
const lines = content.split(/\r?\n/);
|
|
98
120
|
const result: string[] = [];
|
|
99
121
|
let inside = false;
|
|
@@ -135,7 +157,7 @@ export class LinuxScheduler extends PosixSchedulerBase {
|
|
|
135
157
|
// друг друга. Кросс-процессный замок живёт в базовой директории плагина
|
|
136
158
|
// (общей для всех профилей) и ждёт освобождения вместо пропуска.
|
|
137
159
|
const crontabLock = new LockManager(
|
|
138
|
-
path.join(getBasePluginDir(), "locks")
|
|
160
|
+
path.join(getBasePluginDir(), "locks"),
|
|
139
161
|
);
|
|
140
162
|
await withLockWait(
|
|
141
163
|
crontabLock,
|
|
@@ -153,14 +175,17 @@ export class LinuxScheduler extends PosixSchedulerBase {
|
|
|
153
175
|
const next = [base, hasTasks ? block : ""].filter(Boolean).join("\n");
|
|
154
176
|
await this.writeCrontab(next);
|
|
155
177
|
},
|
|
156
|
-
{ timeoutMs: 15000, staleMs: 60000 }
|
|
178
|
+
{ timeoutMs: 15000, staleMs: 60000 },
|
|
157
179
|
);
|
|
158
180
|
}
|
|
159
181
|
|
|
160
|
-
/** Строка команды one-shot для stdin `at`.
|
|
182
|
+
/** Строка команды one-shot для stdin `at`.
|
|
183
|
+
* P1-7.T1.3: без `-c` bash трактует аргумент как ИМЯ ФАЙЛА скрипта
|
|
184
|
+
* (exit 127 «No such file or directory»), поэтому at «выполнял» задание,
|
|
185
|
+
* но команда на самом деле не запускалась. */
|
|
161
186
|
private atCommand(entry: RegistryEntry): string {
|
|
162
187
|
const log = entry.logFile ? ` >> ${shellQuote(entry.logFile)} 2>&1` : "";
|
|
163
|
-
return `/bin/bash ${shellQuote(entry.command)}${log}`;
|
|
188
|
+
return `/bin/bash -c ${shellQuote(entry.command)}${log}`;
|
|
164
189
|
}
|
|
165
190
|
|
|
166
191
|
/**
|
|
@@ -185,24 +210,49 @@ export class LinuxScheduler extends PosixSchedulerBase {
|
|
|
185
210
|
stderr += String(chunk);
|
|
186
211
|
});
|
|
187
212
|
child.on("error", (err) => {
|
|
213
|
+
// P1-7.T1.2: `at` может отсутствовать (минимальные образы, Alpine и
|
|
214
|
+
// т.п.). Не роняем задачу — планируем отвязанный bash-процесс.
|
|
215
|
+
if (isAtMissingError(err)) {
|
|
216
|
+
void scheduleAtFallback(entry, this.atCommand(entry))
|
|
217
|
+
.then((jobId) => {
|
|
218
|
+
console.warn(
|
|
219
|
+
`[agent-steward] at не найден — задача "${entry.name}" запланирована через fallback (${jobId}). ` +
|
|
220
|
+
"Fallback не переживает перезагрузку; установите пакет at.",
|
|
221
|
+
);
|
|
222
|
+
resolve(jobId);
|
|
223
|
+
})
|
|
224
|
+
.catch((fallbackErr) => {
|
|
225
|
+
reject(
|
|
226
|
+
new Error(
|
|
227
|
+
`Не удалось вызвать at и fallback-планировщик: ${
|
|
228
|
+
fallbackErr instanceof Error
|
|
229
|
+
? fallbackErr.message
|
|
230
|
+
: String(fallbackErr)
|
|
231
|
+
}`,
|
|
232
|
+
),
|
|
233
|
+
);
|
|
234
|
+
});
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
188
237
|
reject(
|
|
189
238
|
new Error(
|
|
190
239
|
`Не удалось вызвать at (установите пакет at): ${
|
|
191
240
|
err instanceof Error ? err.message : String(err)
|
|
192
|
-
}
|
|
193
|
-
)
|
|
241
|
+
}`,
|
|
242
|
+
),
|
|
194
243
|
);
|
|
195
244
|
});
|
|
196
245
|
child.on("close", (code) => {
|
|
197
246
|
if (code !== 0) {
|
|
198
247
|
reject(
|
|
199
248
|
new Error(
|
|
200
|
-
`at завершился с кодом ${code}: ${stderr.trim() || stdout.trim()}
|
|
201
|
-
)
|
|
249
|
+
`at завершился с кодом ${code}: ${stderr.trim() || stdout.trim()}`,
|
|
250
|
+
),
|
|
202
251
|
);
|
|
203
252
|
return;
|
|
204
253
|
}
|
|
205
|
-
|
|
254
|
+
// GNU at пишет «job N at …» в stderr, а не в stdout — ищем в обоих потоках.
|
|
255
|
+
const match = /job\s+(\d+)/i.exec(stdout + "\n" + stderr);
|
|
206
256
|
if (!match) {
|
|
207
257
|
reject(new Error(`at не вернул id задания: ${stdout.trim()}`));
|
|
208
258
|
return;
|
|
@@ -216,6 +266,13 @@ export class LinuxScheduler extends PosixSchedulerBase {
|
|
|
216
266
|
/** Отменяет задание at, если оно ещё существует. */
|
|
217
267
|
private async cancelAt(entry: RegistryEntry): Promise<void> {
|
|
218
268
|
if (!entry.atJobId) return;
|
|
269
|
+
if (isPidJobId(entry.atJobId)) {
|
|
270
|
+
// P1-7.T1.2: снимаем fallback-процесс, а не at-задание.
|
|
271
|
+
// P1-14: передаём имя — без сверки маркера pid мог быть переиспользован.
|
|
272
|
+
cancelAtFallback(entry.atJobId, entry.name);
|
|
273
|
+
delete entry.atJobId;
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
219
276
|
try {
|
|
220
277
|
await execFileAsync("atrm", [entry.atJobId]);
|
|
221
278
|
} catch {
|
|
@@ -224,6 +281,14 @@ export class LinuxScheduler extends PosixSchedulerBase {
|
|
|
224
281
|
delete entry.atJobId;
|
|
225
282
|
}
|
|
226
283
|
|
|
284
|
+
/**
|
|
285
|
+
* P1-14: чистит `pid:`-записи fallback'а, пережившие перезагрузку.
|
|
286
|
+
* Вызывается из старта плагина; на других платформах не используется.
|
|
287
|
+
*/
|
|
288
|
+
async pruneStaleFallbacks(): Promise<PruneAtFallbackReport> {
|
|
289
|
+
return pruneStaleFallbackEntries(this.registry);
|
|
290
|
+
}
|
|
291
|
+
|
|
227
292
|
protected async installEntry(entry: RegistryEntry): Promise<void> {
|
|
228
293
|
if (entry.triggerType === "once") {
|
|
229
294
|
if (!entry.paused) {
|
|
@@ -243,11 +308,19 @@ export class LinuxScheduler extends PosixSchedulerBase {
|
|
|
243
308
|
}
|
|
244
309
|
|
|
245
310
|
protected async applyPause(entry: RegistryEntry, paused: boolean): Promise<void> {
|
|
311
|
+
// P1-12: entry получен из find() ДО setPaused(), поэтому без этой строки
|
|
312
|
+
// upsert ниже возвращал в реестр paused:false, и listTasks() показывал
|
|
313
|
+
// приостановленную one-shot задачу как Ready.
|
|
314
|
+
entry.paused = paused;
|
|
246
315
|
if (entry.triggerType === "once") {
|
|
247
316
|
if (paused) {
|
|
248
317
|
await this.cancelAt(entry);
|
|
249
318
|
} else if (entry.runAt && Date.parse(entry.runAt) > Date.now()) {
|
|
250
319
|
entry.atJobId = await this.scheduleAt(entry);
|
|
320
|
+
} else {
|
|
321
|
+
console.warn(
|
|
322
|
+
`[scheduler] Задача "${entry.name}" не будет перезапущена: время one-shot запуска уже прошло (${entry.runAt ?? "runAt не задан"}). Создайте новую задачу.`,
|
|
323
|
+
);
|
|
251
324
|
}
|
|
252
325
|
await this.registry.upsert(entry);
|
|
253
326
|
return;
|
|
@@ -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,10 +45,30 @@ 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
|
|
|
51
|
+
// P2-17: запись нужна в реестре ДО installEntry — Linux пересобирает crontab
|
|
52
|
+
// из реестра. Но если установка упала, запись-призрак останется навсегда,
|
|
53
|
+
// поэтому откатываем реестр к предыдущему состоянию.
|
|
54
|
+
const previous = await this.registry.find(entry.name);
|
|
50
55
|
await this.registry.upsert(entry);
|
|
51
|
-
|
|
56
|
+
try {
|
|
57
|
+
await this.installEntry(entry);
|
|
58
|
+
} catch (err) {
|
|
59
|
+
try {
|
|
60
|
+
if (previous) await this.registry.upsert(previous);
|
|
61
|
+
else await this.registry.remove(entry.name);
|
|
62
|
+
} catch {
|
|
63
|
+
// Не маскируем исходную ошибку установки ошибкой отката.
|
|
64
|
+
}
|
|
65
|
+
try {
|
|
66
|
+
await this.uninstallEntry(entry);
|
|
67
|
+
} catch {
|
|
68
|
+
// Частичная установка могла не создать запись — это не ошибка отката.
|
|
69
|
+
}
|
|
70
|
+
throw err;
|
|
71
|
+
}
|
|
52
72
|
// installEntry может записать atJobId для Linux one-shot.
|
|
53
73
|
await this.registry.upsert(entry);
|
|
54
74
|
}
|
|
@@ -98,6 +118,19 @@ export abstract class PosixSchedulerBase implements SchedulerBackend {
|
|
|
98
118
|
stdio: "ignore",
|
|
99
119
|
cwd: entry.workingDirectory || process.cwd(),
|
|
100
120
|
});
|
|
121
|
+
|
|
122
|
+
// spawn не бросает синхронно: ошибки (например, удалённый
|
|
123
|
+
// workingDirectory → ENOENT) приходят событием 'error'. Без слушателя
|
|
124
|
+
// это uncaught exception в plugin-host. Ждём 'spawn' либо 'error'.
|
|
125
|
+
const spawnError = await new Promise<Error | null>((resolve) => {
|
|
126
|
+
child.once("spawn", () => resolve(null));
|
|
127
|
+
child.once("error", (error) => resolve(error));
|
|
128
|
+
});
|
|
129
|
+
if (spawnError) {
|
|
130
|
+
throw new Error(
|
|
131
|
+
`Не удалось запустить задачу "${name}": ${spawnError.message}`,
|
|
132
|
+
);
|
|
133
|
+
}
|
|
101
134
|
child.unref();
|
|
102
135
|
|
|
103
136
|
return { alreadyRunning: false };
|
|
@@ -110,5 +143,5 @@ export abstract class PosixSchedulerBase implements SchedulerBackend {
|
|
|
110
143
|
*/
|
|
111
144
|
export function shellQuote(value: string): string {
|
|
112
145
|
if (value === "") return "''";
|
|
113
|
-
return `'${value.replace(/'/g,
|
|
146
|
+
return `'${value.replace(/'/g, "'\\''")}'`;
|
|
114
147
|
}
|