agent-steward 0.0.0-stage → 0.0.2
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 +376 -0
- package/CROSS_PLATFORM.md +149 -0
- package/LICENSE +21 -0
- package/README.md +314 -2
- package/ROADMAP-STRATEGY.md +147 -0
- package/ROADMAP.md +1069 -0
- package/dist/core/analytics.d.ts +132 -0
- package/dist/core/analytics.d.ts.map +1 -0
- package/dist/core/analytics.js +290 -0
- package/dist/core/audit.d.ts +96 -0
- package/dist/core/audit.d.ts.map +1 -0
- package/dist/core/audit.js +297 -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 +250 -0
- package/dist/core/dry-run.d.ts +102 -0
- package/dist/core/dry-run.d.ts.map +1 -0
- package/dist/core/dry-run.js +447 -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 +186 -0
- package/dist/core/git-trigger.d.ts +82 -0
- package/dist/core/git-trigger.d.ts.map +1 -0
- package/dist/core/git-trigger.js +312 -0
- package/dist/core/glob.d.ts +38 -0
- package/dist/core/glob.d.ts.map +1 -0
- package/dist/core/glob.js +233 -0
- package/dist/core/local-ai.d.ts +52 -0
- package/dist/core/local-ai.d.ts.map +1 -0
- package/dist/core/local-ai.js +119 -0
- package/dist/core/lock.d.ts +57 -0
- package/dist/core/lock.d.ts.map +1 -0
- package/dist/core/lock.js +195 -0
- package/dist/core/matrix.d.ts +167 -0
- package/dist/core/matrix.d.ts.map +1 -0
- package/dist/core/matrix.js +724 -0
- package/dist/core/native-notify.d.ts +36 -0
- package/dist/core/native-notify.d.ts.map +1 -0
- package/dist/core/native-notify.js +113 -0
- package/dist/core/one-shot.d.ts +68 -0
- package/dist/core/one-shot.d.ts.map +1 -0
- package/dist/core/one-shot.js +139 -0
- package/dist/core/otel.d.ts +4 -0
- package/dist/core/otel.d.ts.map +1 -0
- package/dist/core/otel.js +98 -0
- package/dist/core/permissions.d.ts +69 -0
- package/dist/core/permissions.d.ts.map +1 -0
- package/dist/core/permissions.js +143 -0
- package/dist/core/prometheus.d.ts +23 -0
- package/dist/core/prometheus.d.ts.map +1 -0
- package/dist/core/prometheus.js +146 -0
- package/dist/core/ps-wrapper.d.ts +73 -0
- package/dist/core/ps-wrapper.d.ts.map +1 -0
- package/dist/core/ps-wrapper.js +1071 -0
- package/dist/core/record-history.d.ts +25 -0
- package/dist/core/record-history.d.ts.map +1 -0
- package/dist/core/record-history.js +471 -0
- package/dist/core/retention.d.ts +29 -0
- package/dist/core/retention.d.ts.map +1 -0
- package/dist/core/retention.js +98 -0
- package/dist/core/savings.d.ts +70 -0
- package/dist/core/savings.d.ts.map +1 -0
- package/dist/core/savings.js +87 -0
- package/dist/core/schedule-gate.d.ts +2 -0
- package/dist/core/schedule-gate.d.ts.map +1 -0
- package/dist/core/schedule-gate.js +211 -0
- package/dist/core/schedule-v2.d.ts +116 -0
- package/dist/core/schedule-v2.d.ts.map +1 -0
- package/dist/core/schedule-v2.js +586 -0
- package/dist/core/scheduler/index.d.ts +32 -0
- package/dist/core/scheduler/index.d.ts.map +1 -0
- package/dist/core/scheduler/index.js +63 -0
- package/dist/core/scheduler/linux.d.ts +44 -0
- package/dist/core/scheduler/linux.d.ts.map +1 -0
- package/dist/core/scheduler/linux.js +225 -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 +40 -0
- package/dist/core/scheduler/mac.d.ts.map +1 -0
- package/dist/core/scheduler/mac.js +207 -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 +89 -0
- package/dist/core/scheduler/registry.d.ts +41 -0
- package/dist/core/scheduler/registry.d.ts.map +1 -0
- package/dist/core/scheduler/registry.js +57 -0
- package/dist/core/scheduler/types.d.ts +86 -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 +99 -0
- package/dist/core/scheduler/windows.d.ts.map +1 -0
- package/dist/core/scheduler/windows.js +596 -0
- package/dist/core/secrets.d.ts +66 -0
- package/dist/core/secrets.d.ts.map +1 -0
- package/dist/core/secrets.js +433 -0
- package/dist/core/self-analysis.d.ts +117 -0
- package/dist/core/self-analysis.d.ts.map +1 -0
- package/dist/core/self-analysis.js +539 -0
- package/dist/core/self-analysis.test.d.ts +2 -0
- package/dist/core/self-analysis.test.d.ts.map +1 -0
- package/dist/core/self-analysis.test.js +219 -0
- package/dist/core/session.d.ts +42 -0
- package/dist/core/session.d.ts.map +1 -0
- package/dist/core/session.js +134 -0
- package/dist/core/shutdown.d.ts +26 -0
- package/dist/core/shutdown.d.ts.map +1 -0
- package/dist/core/shutdown.js +49 -0
- package/dist/core/structured-log.d.ts +84 -0
- package/dist/core/structured-log.d.ts.map +1 -0
- package/dist/core/structured-log.js +146 -0
- package/dist/core/summary.d.ts +69 -0
- package/dist/core/summary.d.ts.map +1 -0
- package/dist/core/summary.js +250 -0
- package/dist/core/telegram.d.ts +55 -0
- package/dist/core/telegram.d.ts.map +1 -0
- package/dist/core/telegram.js +344 -0
- package/dist/core/triage-chain.d.ts +40 -0
- package/dist/core/triage-chain.d.ts.map +1 -0
- package/dist/core/triage-chain.js +80 -0
- package/dist/core/triage-compare.d.ts +68 -0
- package/dist/core/triage-compare.d.ts.map +1 -0
- package/dist/core/triage-compare.js +184 -0
- package/dist/core/triage-rules.d.ts +23 -0
- package/dist/core/triage-rules.d.ts.map +1 -0
- package/dist/core/triage-rules.js +196 -0
- package/dist/core/triage-shadow.d.ts +91 -0
- package/dist/core/triage-shadow.d.ts.map +1 -0
- package/dist/core/triage-shadow.js +160 -0
- package/dist/core/triage-worker.d.ts +55 -0
- package/dist/core/triage-worker.d.ts.map +1 -0
- package/dist/core/triage-worker.js +314 -0
- package/dist/core/triage.d.ts +76 -0
- package/dist/core/triage.d.ts.map +1 -0
- package/dist/core/triage.js +271 -0
- package/dist/core/watch-paths.d.ts +6 -0
- package/dist/core/watch-paths.d.ts.map +1 -0
- package/dist/core/watch-paths.js +62 -0
- package/dist/core/wrappers/bash.d.ts +95 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -0
- package/dist/core/wrappers/bash.js +413 -0
- package/dist/db/git-state-repo.d.ts +16 -0
- package/dist/db/git-state-repo.d.ts.map +1 -0
- package/dist/db/git-state-repo.js +38 -0
- package/dist/db/history-repo.d.ts +110 -0
- package/dist/db/history-repo.d.ts.map +1 -0
- package/dist/db/history-repo.js +300 -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 +46 -0
- package/dist/db/metrics-repo.d.ts.map +1 -0
- package/dist/db/metrics-repo.js +103 -0
- package/dist/db/migrate.d.ts +24 -0
- package/dist/db/migrate.d.ts.map +1 -0
- package/dist/db/migrate.js +244 -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 +170 -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 +60 -0
- package/dist/history.d.ts.map +1 -0
- package/dist/history.js +70 -0
- package/dist/i18n.d.ts +75 -0
- package/dist/i18n.d.ts.map +1 -0
- package/dist/i18n.js +357 -0
- package/dist/index.d.ts +858 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5179 -0
- package/dist/integrations.d.ts +72 -0
- package/dist/integrations.d.ts.map +1 -0
- package/dist/integrations.js +233 -0
- package/dist/notifications.d.ts +199 -0
- package/dist/notifications.d.ts.map +1 -0
- package/dist/notifications.js +967 -0
- package/dist/profiles.d.ts +60 -0
- package/dist/profiles.d.ts.map +1 -0
- package/dist/profiles.js +227 -0
- package/dist/rpc.d.ts +3806 -0
- package/dist/rpc.d.ts.map +1 -0
- package/dist/rpc.js +1507 -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 +128 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +2413 -0
- package/dist/settings.d.ts +389 -0
- package/dist/settings.d.ts.map +1 -0
- package/dist/settings.js +770 -0
- package/dist/shared/jobs-view.d.ts +59 -0
- package/dist/shared/jobs-view.d.ts.map +1 -0
- package/dist/shared/jobs-view.js +146 -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 +252 -0
- package/dist/task-transfer.d.ts.map +1 -0
- package/dist/task-transfer.js +628 -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 +96 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +130 -0
- package/dist/version.d.ts +8 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +27 -0
- package/dist/workspaces.d.ts +113 -0
- package/dist/workspaces.d.ts.map +1 -0
- package/dist/workspaces.js +393 -0
- package/docs/ARCHITECTURE.md +457 -0
- package/docs/COMPATIBILITY.md +233 -0
- package/docs/CONCEPT.md +230 -0
- package/docs/CROSS_PLATFORM.ru.md +150 -0
- package/docs/CROSS_PLATFORM.zh.md +146 -0
- package/docs/FAQ.md +52 -0
- package/docs/FAQ.ru.md +53 -0
- package/docs/FAQ.zh.md +43 -0
- package/docs/FEATURES.md +698 -0
- package/docs/FEATURES.zh.md +655 -0
- package/docs/LOCAL-AI.md +300 -0
- package/docs/MIGRATION.md +355 -0
- package/docs/README.ru.md +268 -0
- package/docs/README.zh.md +305 -0
- package/docs/SAVINGS.md +61 -0
- package/docs/SAVINGS.ru.md +60 -0
- package/docs/SAVINGS.zh.md +52 -0
- package/docs/V1-V2-COMPATIBILITY-PLAN.md +366 -0
- package/docs/ZH-LOCALE-PLAN.md +324 -0
- package/docs/dashboard.png +0 -0
- package/docs/spikes/local-model-structured-output.md +81 -0
- package/docs/spikes/ollama-qwen3-4b-smoke.json +28 -0
- package/docs/spikes/ollama-qwen3-4b.json +163 -0
- package/gui-experimental.cjs +9 -0
- package/index.js +1 -0
- package/locales/en.json +780 -0
- package/locales/ru.json +780 -0
- package/locales/zh.json +780 -0
- package/package.json +149 -4
- package/scripts/bench-local.mjs +321 -0
- package/scripts/check-zh-locale.mjs +218 -0
- package/scripts/demo-dashboard.mjs +209 -0
- package/scripts/run-tests.mjs +236 -0
- package/scripts/spike-local-structured.mjs +182 -0
- package/scripts/test-locale.mjs +45 -0
- package/skills/scheduled-job-best-practices/SKILL.md +158 -0
- package/skills/scheduled-job-best-practices/references/recipes.md +163 -0
- package/src/core/analytics.ts +424 -0
- package/src/core/audit.ts +418 -0
- package/src/core/cron-to-schtasks.ts +288 -0
- package/src/core/dry-run.ts +601 -0
- package/src/core/file-watcher.ts +245 -0
- package/src/core/git-trigger.ts +391 -0
- package/src/core/glob.ts +226 -0
- package/src/core/local-ai.ts +173 -0
- package/src/core/lock.ts +219 -0
- package/src/core/matrix.ts +947 -0
- package/src/core/native-notify.ts +157 -0
- package/src/core/one-shot.ts +189 -0
- package/src/core/otel.ts +128 -0
- package/src/core/permissions.ts +200 -0
- package/src/core/prometheus.ts +215 -0
- package/src/core/ps-wrapper.ts +1140 -0
- package/src/core/record-history.ts +615 -0
- package/src/core/retention.ts +141 -0
- package/src/core/savings.ts +150 -0
- package/src/core/schedule-gate.ts +253 -0
- package/src/core/schedule-v2.ts +668 -0
- package/src/core/scheduler/index.ts +82 -0
- package/src/core/scheduler/linux.ts +257 -0
- package/src/core/scheduler/logs.ts +37 -0
- package/src/core/scheduler/mac.ts +270 -0
- package/src/core/scheduler/posix.ts +114 -0
- package/src/core/scheduler/registry.ts +99 -0
- package/src/core/scheduler/types.ts +90 -0
- package/src/core/scheduler/windows.ts +711 -0
- package/src/core/secrets.ts +503 -0
- package/src/core/self-analysis.ts +744 -0
- package/src/core/session.ts +150 -0
- package/src/core/shutdown.ts +69 -0
- package/src/core/structured-log.ts +214 -0
- package/src/core/summary.ts +318 -0
- package/src/core/telegram.ts +436 -0
- package/src/core/triage-chain.ts +125 -0
- package/src/core/triage-compare.ts +277 -0
- package/src/core/triage-rules.ts +238 -0
- package/src/core/triage-shadow.ts +240 -0
- package/src/core/triage-worker.ts +344 -0
- package/src/core/triage.ts +366 -0
- package/src/core/watch-paths.ts +70 -0
- package/src/core/wrappers/bash.ts +532 -0
- package/src/db/git-state-repo.ts +62 -0
- package/src/db/history-repo.ts +492 -0
- package/src/db/index.ts +166 -0
- package/src/db/metrics-repo.ts +170 -0
- package/src/db/migrate.ts +328 -0
- package/src/db/recovery.ts +46 -0
- package/src/db/schema.ts +188 -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 +5222 -0
- package/src/history.ts +128 -0
- package/src/i18n.ts +413 -0
- package/src/index.ts +6605 -0
- package/src/integrations.ts +297 -0
- package/src/notifications.ts +1346 -0
- package/src/profiles.ts +254 -0
- package/src/rpc.ts +1609 -0
- package/src/schtasks.ts +75 -0
- package/src/server.ts +2662 -0
- package/src/settings.ts +1369 -0
- package/src/shared/jobs-view.ts +188 -0
- package/src/skill.ts +113 -0
- package/src/task-transfer.ts +944 -0
- package/src/templates.ts +67 -0
- package/src/tui-v1.tsx +341 -0
- package/src/tui.tsx +329 -0
- package/src/types.ts +191 -0
- package/src/version.ts +27 -0
- package/src/workspaces.ts +487 -0
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { WindowsScheduler } from "./windows.js";
|
|
2
|
+
import { LinuxScheduler } from "./linux.js";
|
|
3
|
+
import { MacScheduler } from "./mac.js";
|
|
4
|
+
import type { SchedulerBackend } from "./types.js";
|
|
5
|
+
|
|
6
|
+
export type {
|
|
7
|
+
SchedulerBackend,
|
|
8
|
+
CreateTaskOptions,
|
|
9
|
+
RunTaskResult,
|
|
10
|
+
TriggerType,
|
|
11
|
+
} from "./types.js";
|
|
12
|
+
export { WindowsScheduler, SchtasksError, WINDOWS_TASK_PREFIX } from "./windows.js";
|
|
13
|
+
export { LinuxScheduler } from "./linux.js";
|
|
14
|
+
export { MacScheduler } from "./mac.js";
|
|
15
|
+
export { TaskRegistry } from "./registry.js";
|
|
16
|
+
export type { RegistryEntry } from "./registry.js";
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Фабрика бэкендов планировщика по платформе.
|
|
20
|
+
*
|
|
21
|
+
* - win32 → WindowsScheduler (schtasks);
|
|
22
|
+
* - darwin → MacScheduler (launchd);
|
|
23
|
+
* - linux (и прочие POSIX) → LinuxScheduler (crontab).
|
|
24
|
+
*/
|
|
25
|
+
export function createSchedulerBackend(
|
|
26
|
+
platform: NodeJS.Platform = process.platform,
|
|
27
|
+
profile?: string
|
|
28
|
+
): SchedulerBackend {
|
|
29
|
+
if (platform === "win32") return new WindowsScheduler(profile);
|
|
30
|
+
if (platform === "darwin") return new MacScheduler(profile);
|
|
31
|
+
return new LinuxScheduler(profile);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Бэкенд планировщика в пространстве имён конкретного профиля — в том числе
|
|
36
|
+
* неактивного. Нужен, чтобы удаление профиля снимало ЕГО задачи, а не задачи
|
|
37
|
+
* активного профиля (T-05).
|
|
38
|
+
*/
|
|
39
|
+
export function createSchedulerBackendForProfile(
|
|
40
|
+
profile: string,
|
|
41
|
+
platform: NodeJS.Platform = process.platform
|
|
42
|
+
): SchedulerBackend {
|
|
43
|
+
return createSchedulerBackend(platform, profile);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Снимает все задачи профиля из планировщика ОС перед удалением его файлов.
|
|
48
|
+
* Ошибки по отдельным задачам игнорируются; бросает только если сам список
|
|
49
|
+
* задач получить не удалось.
|
|
50
|
+
*/
|
|
51
|
+
export async function removeScheduledTasksForProfile(
|
|
52
|
+
profile: string,
|
|
53
|
+
platform: NodeJS.Platform = process.platform
|
|
54
|
+
): Promise<number> {
|
|
55
|
+
const scheduler = createSchedulerBackendForProfile(profile, platform);
|
|
56
|
+
const tasks = await scheduler.listTasks();
|
|
57
|
+
let removed = 0;
|
|
58
|
+
for (const task of tasks) {
|
|
59
|
+
const name = task.taskName ?? "";
|
|
60
|
+
if (!name) continue;
|
|
61
|
+
try {
|
|
62
|
+
await scheduler.deleteTask(name);
|
|
63
|
+
removed++;
|
|
64
|
+
} catch {
|
|
65
|
+
// Задача уже удалена или недоступна — продолжаем чистить остальные.
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return removed;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
let cached: SchedulerBackend | null = null;
|
|
72
|
+
|
|
73
|
+
/** Возвращает общий (закэшированный) бэкенд текущей платформы. */
|
|
74
|
+
export function getSchedulerBackend(): SchedulerBackend {
|
|
75
|
+
if (!cached) cached = createSchedulerBackend();
|
|
76
|
+
return cached;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Название планировщика для текущей платформы (для GUI/логов). */
|
|
80
|
+
export function getSchedulerTitle(platform: NodeJS.Platform = process.platform): string {
|
|
81
|
+
return createSchedulerBackend(platform).title;
|
|
82
|
+
}
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import { execFile, spawn } from "node:child_process";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { promisify } from "node:util";
|
|
4
|
+
import { buildAtTimestamp } from "../one-shot.js";
|
|
5
|
+
import { needsPollMode } from "../schedule-v2.js";
|
|
6
|
+
import { LockManager, withLockWait } from "../lock.js";
|
|
7
|
+
import { getBasePluginDir, getProfileName } from "../../profiles.js";
|
|
8
|
+
import { taskFolderNameForProfile } from "../../types.js";
|
|
9
|
+
import { PosixSchedulerBase, shellQuote } from "./posix.js";
|
|
10
|
+
import type { RegistryEntry } from "./registry.js";
|
|
11
|
+
|
|
12
|
+
const execFileAsync = promisify(execFile);
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Бэкенд планировщика Linux на основе пользовательского crontab.
|
|
16
|
+
*
|
|
17
|
+
* Все задачи плагина живут в одном управляемом блоке:
|
|
18
|
+
* # >>> opencode-scheduler >>>
|
|
19
|
+
* # task: <имя>
|
|
20
|
+
* <cron> /bin/bash '<обёртка>' >> '<лог>' 2>&1
|
|
21
|
+
* # <<< opencode-scheduler <<<
|
|
22
|
+
* При паузе строка задачи комментируется ("# PAUSED: ..."), при удалении —
|
|
23
|
+
* блок перегенерируется из реестра.
|
|
24
|
+
*/
|
|
25
|
+
export class LinuxScheduler extends PosixSchedulerBase {
|
|
26
|
+
readonly platform: NodeJS.Platform = "linux";
|
|
27
|
+
readonly title = "OpenCode Scheduler";
|
|
28
|
+
|
|
29
|
+
private readonly blockBegin: string;
|
|
30
|
+
private readonly blockEnd: string;
|
|
31
|
+
private readonly ownsLegacyBlock: boolean;
|
|
32
|
+
|
|
33
|
+
constructor(profile: string = getProfileName()) {
|
|
34
|
+
super("linux", profile);
|
|
35
|
+
const folderName = taskFolderNameForProfile(profile);
|
|
36
|
+
this.blockBegin = `# >>> opencode-scheduler:${folderName} >>>`;
|
|
37
|
+
this.blockEnd = `# <<< opencode-scheduler:${folderName} <<<`;
|
|
38
|
+
this.ownsLegacyBlock = folderName === "windows-scheduler";
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
private cronLine(entry: RegistryEntry): string {
|
|
42
|
+
if (entry.triggerType !== "cron") {
|
|
43
|
+
// Файловый/MCP-триггер не имеет расписания — держим задачу только в реестре.
|
|
44
|
+
return "";
|
|
45
|
+
}
|
|
46
|
+
const log = entry.logFile ? ` >> ${shellQuote(entry.logFile)} 2>&1` : "";
|
|
47
|
+
const cmd = `/bin/bash ${shellQuote(entry.command)}${log}`;
|
|
48
|
+
// crontab понимает только 5-полевой cron. Расширенные выражения (L, #,
|
|
49
|
+
// списки, @daily и т.п.) нельзя писать в crontab как есть — опрашиваем
|
|
50
|
+
// каждую минуту, а решение о запуске принимает gate во враппере.
|
|
51
|
+
const schedule = needsPollMode(entry.schedule) ? "* * * * *" : entry.schedule;
|
|
52
|
+
return `${schedule} ${cmd}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
private renderBlock(entries: RegistryEntry[]): string {
|
|
56
|
+
const lines: string[] = [this.blockBegin];
|
|
57
|
+
for (const entry of entries) {
|
|
58
|
+
const line = this.cronLine(entry);
|
|
59
|
+
if (!line) continue;
|
|
60
|
+
lines.push(`# task: ${entry.name}`);
|
|
61
|
+
lines.push(entry.paused ? `# PAUSED: ${line}` : line);
|
|
62
|
+
}
|
|
63
|
+
lines.push(this.blockEnd);
|
|
64
|
+
return lines.join("\n");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Читает текущий crontab (пустая строка, если crontab ещё не создан). */
|
|
68
|
+
private async readCrontab(): Promise<string> {
|
|
69
|
+
try {
|
|
70
|
+
const { stdout } = await execFileAsync("crontab", ["-l"], {
|
|
71
|
+
maxBuffer: 10 * 1024 * 1024,
|
|
72
|
+
});
|
|
73
|
+
return stdout;
|
|
74
|
+
} catch (err: any) {
|
|
75
|
+
const stderr = String(err?.stderr ?? "");
|
|
76
|
+
// "no crontab for user" — это нормальное состояние. Любую другую ошибку
|
|
77
|
+
// (нет доступа, сбой crontab) нельзя превращать в пустой crontab: иначе
|
|
78
|
+
// последующая запись затрёт пользовательские задания.
|
|
79
|
+
if (/no crontab/i.test(stderr) || /no crontab/i.test(String(err?.message ?? ""))) {
|
|
80
|
+
return "";
|
|
81
|
+
}
|
|
82
|
+
throw new Error(`Не удалось прочитать crontab: ${stderr.trim() || err?.message || err}`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Убирает управляемый блок плагина из текста crontab. */
|
|
87
|
+
private stripBlock(content: string): string {
|
|
88
|
+
// Совместимость: до появления профилей блок назывался без суффикса.
|
|
89
|
+
// Он принадлежит профилю default; другие профили его не трогают.
|
|
90
|
+
const legacyBegin = "# >>> opencode-scheduler >>>";
|
|
91
|
+
const legacyEnd = "# <<< opencode-scheduler <<<";
|
|
92
|
+
const ownsLegacy = this.ownsLegacyBlock;
|
|
93
|
+
const isBegin = (line: string) =>
|
|
94
|
+
line === this.blockBegin || (ownsLegacy && line === legacyBegin);
|
|
95
|
+
const isEnd = (line: string) =>
|
|
96
|
+
line === this.blockEnd || (ownsLegacy && line === legacyEnd);
|
|
97
|
+
const lines = content.split(/\r?\n/);
|
|
98
|
+
const result: string[] = [];
|
|
99
|
+
let inside = false;
|
|
100
|
+
for (const line of lines) {
|
|
101
|
+
if (isBegin(line.trim())) {
|
|
102
|
+
inside = true;
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
if (isEnd(line.trim())) {
|
|
106
|
+
inside = false;
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
if (!inside) result.push(line);
|
|
110
|
+
}
|
|
111
|
+
return result.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd();
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Записывает crontab через stdin: `crontab -`. */
|
|
115
|
+
private async writeCrontab(content: string): Promise<void> {
|
|
116
|
+
await new Promise<void>((resolve, reject) => {
|
|
117
|
+
const child = spawn("crontab", ["-"], { stdio: ["pipe", "ignore", "pipe"] });
|
|
118
|
+
let stderr = "";
|
|
119
|
+
child.stderr.on("data", (chunk) => {
|
|
120
|
+
stderr += String(chunk);
|
|
121
|
+
});
|
|
122
|
+
child.on("error", reject);
|
|
123
|
+
child.on("close", (code) => {
|
|
124
|
+
if (code === 0) resolve();
|
|
125
|
+
else reject(new Error(`crontab - завершился с кодом ${code}: ${stderr.trim()}`));
|
|
126
|
+
});
|
|
127
|
+
child.stdin.end(content.endsWith("\n") ? content : `${content}\n`);
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Перегенерирует блок плагина из реестра. */
|
|
132
|
+
private async rebuildCrontab(): Promise<void> {
|
|
133
|
+
// T-17: crontab общий для всех профилей пользователя, а read-modify-write
|
|
134
|
+
// не атомарен — параллельные операции разных профилей могли затирать блоки
|
|
135
|
+
// друг друга. Кросс-процессный замок живёт в базовой директории плагина
|
|
136
|
+
// (общей для всех профилей) и ждёт освобождения вместо пропуска.
|
|
137
|
+
const crontabLock = new LockManager(
|
|
138
|
+
path.join(getBasePluginDir(), "locks")
|
|
139
|
+
);
|
|
140
|
+
await withLockWait(
|
|
141
|
+
crontabLock,
|
|
142
|
+
"crontab",
|
|
143
|
+
async () => {
|
|
144
|
+
const entries = await this.registry.load();
|
|
145
|
+
const current = await this.readCrontab();
|
|
146
|
+
const base = this.stripBlock(current);
|
|
147
|
+
const block = this.renderBlock(entries);
|
|
148
|
+
|
|
149
|
+
// Пустой блок (нет задач) не пишем, чтобы не оставлять мусор в crontab.
|
|
150
|
+
const hasTasks = block
|
|
151
|
+
.split("\n")
|
|
152
|
+
.some((line) => line.trim().startsWith("# task:"));
|
|
153
|
+
const next = [base, hasTasks ? block : ""].filter(Boolean).join("\n");
|
|
154
|
+
await this.writeCrontab(next);
|
|
155
|
+
},
|
|
156
|
+
{ timeoutMs: 15000, staleMs: 60000 }
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Строка команды one-shot для stdin `at`. */
|
|
161
|
+
private atCommand(entry: RegistryEntry): string {
|
|
162
|
+
const log = entry.logFile ? ` >> ${shellQuote(entry.logFile)} 2>&1` : "";
|
|
163
|
+
return `/bin/bash ${shellQuote(entry.command)}${log}`;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Ставит one-shot в `at` и возвращает id задания.
|
|
168
|
+
* `at -t` принимает локальное время системы в формате YYYYMMDDHHMM.
|
|
169
|
+
*/
|
|
170
|
+
private async scheduleAt(entry: RegistryEntry): Promise<string> {
|
|
171
|
+
if (!entry.runAt) {
|
|
172
|
+
throw new Error(`Задача "${entry.name}": не задано runAt для one-shot.`);
|
|
173
|
+
}
|
|
174
|
+
const timestamp = buildAtTimestamp(entry.runAt);
|
|
175
|
+
return new Promise<string>((resolve, reject) => {
|
|
176
|
+
const child = spawn("at", ["-t", timestamp], {
|
|
177
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
178
|
+
});
|
|
179
|
+
let stdout = "";
|
|
180
|
+
let stderr = "";
|
|
181
|
+
child.stdout.on("data", (chunk) => {
|
|
182
|
+
stdout += String(chunk);
|
|
183
|
+
});
|
|
184
|
+
child.stderr.on("data", (chunk) => {
|
|
185
|
+
stderr += String(chunk);
|
|
186
|
+
});
|
|
187
|
+
child.on("error", (err) => {
|
|
188
|
+
reject(
|
|
189
|
+
new Error(
|
|
190
|
+
`Не удалось вызвать at (установите пакет at): ${
|
|
191
|
+
err instanceof Error ? err.message : String(err)
|
|
192
|
+
}`
|
|
193
|
+
)
|
|
194
|
+
);
|
|
195
|
+
});
|
|
196
|
+
child.on("close", (code) => {
|
|
197
|
+
if (code !== 0) {
|
|
198
|
+
reject(
|
|
199
|
+
new Error(
|
|
200
|
+
`at завершился с кодом ${code}: ${stderr.trim() || stdout.trim()}`
|
|
201
|
+
)
|
|
202
|
+
);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
const match = /job\s+(\d+)/i.exec(stdout);
|
|
206
|
+
if (!match) {
|
|
207
|
+
reject(new Error(`at не вернул id задания: ${stdout.trim()}`));
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
resolve(match[1]);
|
|
211
|
+
});
|
|
212
|
+
child.stdin.end(`${this.atCommand(entry)}\n`);
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Отменяет задание at, если оно ещё существует. */
|
|
217
|
+
private async cancelAt(entry: RegistryEntry): Promise<void> {
|
|
218
|
+
if (!entry.atJobId) return;
|
|
219
|
+
try {
|
|
220
|
+
await execFileAsync("atrm", [entry.atJobId]);
|
|
221
|
+
} catch {
|
|
222
|
+
// Задание уже выполнилось или было удалено — это не ошибка.
|
|
223
|
+
}
|
|
224
|
+
delete entry.atJobId;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
protected async installEntry(entry: RegistryEntry): Promise<void> {
|
|
228
|
+
if (entry.triggerType === "once") {
|
|
229
|
+
if (!entry.paused) {
|
|
230
|
+
entry.atJobId = await this.scheduleAt(entry);
|
|
231
|
+
}
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
await this.rebuildCrontab();
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
protected async uninstallEntry(entry: RegistryEntry): Promise<void> {
|
|
238
|
+
if (entry.triggerType === "once") {
|
|
239
|
+
await this.cancelAt(entry);
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
await this.rebuildCrontab();
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
protected async applyPause(entry: RegistryEntry, paused: boolean): Promise<void> {
|
|
246
|
+
if (entry.triggerType === "once") {
|
|
247
|
+
if (paused) {
|
|
248
|
+
await this.cancelAt(entry);
|
|
249
|
+
} else if (entry.runAt && Date.parse(entry.runAt) > Date.now()) {
|
|
250
|
+
entry.atJobId = await this.scheduleAt(entry);
|
|
251
|
+
}
|
|
252
|
+
await this.registry.upsert(entry);
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
await this.rebuildCrontab();
|
|
256
|
+
}
|
|
257
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { LOG_DIR, sanitizeName } from "../../types.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Читает файл лога задачи и возвращает последние 50 строк.
|
|
7
|
+
*
|
|
8
|
+
* Лог пишут обёртки (PowerShell на Windows, bash на POSIX) в
|
|
9
|
+
* ${LOG_DIR}/<sanitizedName>.log — тот же путь, что передаётся при создании.
|
|
10
|
+
*/
|
|
11
|
+
export async function getTaskLogs(
|
|
12
|
+
name: string,
|
|
13
|
+
limit = 50
|
|
14
|
+
): Promise<{ logs: string; error?: string }> {
|
|
15
|
+
const logPath = path.join(LOG_DIR, `${sanitizeName(name)}.log`);
|
|
16
|
+
try {
|
|
17
|
+
// PowerShell 5.1 пишет UTF-8 с BOM — убираем его, чтобы GUI не показывал мусор.
|
|
18
|
+
const content = (await fs.readFile(logPath, "utf8")).replace(/^\uFEFF/, "");
|
|
19
|
+
const lines = content.split(/\r?\n/).filter((line) => line.trim());
|
|
20
|
+
if (lines.length === 0) {
|
|
21
|
+
return {
|
|
22
|
+
logs: "",
|
|
23
|
+
error: `Лог задачи "${name}" пуст. Задача ещё не писала вывод — запустите её и повторите.`,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
const last = lines.slice(-Math.max(1, Math.min(limit, 1000)));
|
|
27
|
+
return { logs: last.join("\n") };
|
|
28
|
+
} catch (err: any) {
|
|
29
|
+
if (err.code === "ENOENT") {
|
|
30
|
+
return {
|
|
31
|
+
logs: "",
|
|
32
|
+
error: `Лог задачи "${name}" не найден по пути ${logPath} (задача ещё не запускалась).`,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
return { logs: "", error: err instanceof Error ? err.message : String(err) };
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import fsSync from "node:fs";
|
|
3
|
+
import fs from "node:fs/promises";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { promisify } from "node:util";
|
|
7
|
+
import { sanitizeName } from "../../types.js";
|
|
8
|
+
import { getProfileDir, getProfileName } from "../../profiles.js";
|
|
9
|
+
import { buildLaunchdCalendar, launchdLabel } from "../one-shot.js";
|
|
10
|
+
import { PosixSchedulerBase } from "./posix.js";
|
|
11
|
+
import type { RegistryEntry } from "./registry.js";
|
|
12
|
+
|
|
13
|
+
const execFileAsync = promisify(execFile);
|
|
14
|
+
|
|
15
|
+
/** Папка пользовательских LaunchAgents. */
|
|
16
|
+
const LAUNCH_AGENTS_DIR = path.join(os.homedir(), "Library", "LaunchAgents");
|
|
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
|
+
interval?: number;
|
|
99
|
+
calendar?: {
|
|
100
|
+
Minute?: number;
|
|
101
|
+
Hour?: number;
|
|
102
|
+
Weekday?: number;
|
|
103
|
+
Month?: number;
|
|
104
|
+
Day?: number;
|
|
105
|
+
};
|
|
106
|
+
} =
|
|
107
|
+
entry.triggerType === "once"
|
|
108
|
+
? (() => {
|
|
109
|
+
if (!entry.runAt) {
|
|
110
|
+
throw new Error(
|
|
111
|
+
`Задача "${entry.name}": для one-shot не задано runAt.`
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
return { calendar: buildLaunchdCalendar(entry.runAt) };
|
|
115
|
+
})()
|
|
116
|
+
: entry.triggerType !== "cron"
|
|
117
|
+
? { interval: 315_360_000 } // file/mcp-event: 10 лет — фактически «никогда».
|
|
118
|
+
: cronToLaunchdSchedule(entry.schedule);
|
|
119
|
+
|
|
120
|
+
const scheduleXml: string[] = [];
|
|
121
|
+
if (schedule.interval !== undefined) {
|
|
122
|
+
scheduleXml.push(
|
|
123
|
+
" <key>StartInterval</key>",
|
|
124
|
+
` <integer>${schedule.interval}</integer>`
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
if (schedule.calendar) {
|
|
128
|
+
scheduleXml.push(" <key>StartCalendarInterval</key>", " <dict>");
|
|
129
|
+
if (schedule.calendar.Minute !== undefined) {
|
|
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
|
+
}
|
|
159
|
+
scheduleXml.push(" </dict>");
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const workdir = entry.workingDirectory || process.cwd();
|
|
163
|
+
const log = entry.logFile;
|
|
164
|
+
const logXml = log
|
|
165
|
+
? [
|
|
166
|
+
" <key>StandardOutPath</key>",
|
|
167
|
+
` <string>${xmlEscape(log)}</string>`,
|
|
168
|
+
" <key>StandardErrorPath</key>",
|
|
169
|
+
` <string>${xmlEscape(log)}</string>`,
|
|
170
|
+
]
|
|
171
|
+
: [];
|
|
172
|
+
|
|
173
|
+
return [
|
|
174
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
175
|
+
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" ' +
|
|
176
|
+
'"http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
|
177
|
+
'<plist version="1.0">',
|
|
178
|
+
"<dict>",
|
|
179
|
+
" <key>Label</key>",
|
|
180
|
+
` <string>${xmlEscape(label)}</string>`,
|
|
181
|
+
" <key>ProgramArguments</key>",
|
|
182
|
+
" <array>",
|
|
183
|
+
" <string>/bin/bash</string>",
|
|
184
|
+
` <string>${xmlEscape(entry.command)}</string>`,
|
|
185
|
+
" </array>",
|
|
186
|
+
" <key>WorkingDirectory</key>",
|
|
187
|
+
` <string>${xmlEscape(workdir)}</string>`,
|
|
188
|
+
...logXml,
|
|
189
|
+
" <key>RunAtLoad</key>",
|
|
190
|
+
" <false/>",
|
|
191
|
+
...scheduleXml,
|
|
192
|
+
"</dict>",
|
|
193
|
+
"</plist>",
|
|
194
|
+
"",
|
|
195
|
+
].join("\n");
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Бэкенд планировщика macOS на основе launchd.
|
|
200
|
+
*
|
|
201
|
+
* Каждая задача — отдельный LaunchAgent:
|
|
202
|
+
* ~/Library/LaunchAgents/com.opencode.scheduler.<name>.plist
|
|
203
|
+
* Управление — через launchctl load/unload -w.
|
|
204
|
+
*/
|
|
205
|
+
export class MacScheduler extends PosixSchedulerBase {
|
|
206
|
+
readonly platform: NodeJS.Platform = "darwin";
|
|
207
|
+
readonly title = "OpenCode Scheduler";
|
|
208
|
+
|
|
209
|
+
constructor(profile: string = getProfileName()) {
|
|
210
|
+
super("mac", profile);
|
|
211
|
+
this.profile = profile;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
private readonly profile: string;
|
|
215
|
+
|
|
216
|
+
private label(name: string): string {
|
|
217
|
+
const sanitized = sanitizeName(name);
|
|
218
|
+
// Совместимость: до 1.5.6 plist не-default профилей назывался без scope.
|
|
219
|
+
// Используем старое имя, только если plist реально принадлежит этому
|
|
220
|
+
// профилю (в его команде есть директория профиля), иначе можно удалить
|
|
221
|
+
// одноимённый plist активного профиля.
|
|
222
|
+
if (this.profile !== "default") {
|
|
223
|
+
const legacy = launchdLabel(sanitized, "default");
|
|
224
|
+
const legacyPath = path.join(LAUNCH_AGENTS_DIR, `${legacy}.plist`);
|
|
225
|
+
try {
|
|
226
|
+
const text = fsSync.readFileSync(legacyPath, "utf8");
|
|
227
|
+
if (text.includes(getProfileDir(this.profile))) return legacy;
|
|
228
|
+
} catch {
|
|
229
|
+
// Старого plist нет — используем профильное имя.
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return launchdLabel(sanitized, this.profile);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
private plistPath(name: string): string {
|
|
236
|
+
return path.join(LAUNCH_AGENTS_DIR, `${this.label(name)}.plist`);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** Выполняет launchctl, не считая ошибку фатальной (unload несуществующего). */
|
|
240
|
+
private async launchctl(args: string[]): Promise<void> {
|
|
241
|
+
try {
|
|
242
|
+
await execFileAsync("launchctl", args, { maxBuffer: 1024 * 1024 });
|
|
243
|
+
} catch {
|
|
244
|
+
// launchctl возвращает ошибку, если агент ещё не загружен — это нормально.
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
protected async installEntry(entry: RegistryEntry): Promise<void> {
|
|
249
|
+
await fs.mkdir(LAUNCH_AGENTS_DIR, { recursive: true });
|
|
250
|
+
const plistPath = this.plistPath(entry.name);
|
|
251
|
+
await this.launchctl(["unload", plistPath]);
|
|
252
|
+
await fs.writeFile(plistPath, buildPlist(this.label(entry.name), entry), "utf8");
|
|
253
|
+
await this.launchctl(["load", "-w", plistPath]);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
protected async uninstallEntry(entry: RegistryEntry): Promise<void> {
|
|
257
|
+
const plistPath = this.plistPath(entry.name);
|
|
258
|
+
await this.launchctl(["unload", "-w", plistPath]);
|
|
259
|
+
await fs.unlink(plistPath).catch(() => {});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
protected async applyPause(entry: RegistryEntry, paused: boolean): Promise<void> {
|
|
263
|
+
const plistPath = this.plistPath(entry.name);
|
|
264
|
+
if (paused) {
|
|
265
|
+
await this.launchctl(["unload", "-w", plistPath]);
|
|
266
|
+
} else {
|
|
267
|
+
await this.launchctl(["load", "-w", plistPath]);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|