agent-steward 0.0.1 → 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.
Files changed (345) hide show
  1. package/CHANGELOG.md +399 -0
  2. package/CROSS_PLATFORM.md +151 -0
  3. package/README.md +307 -15
  4. package/ROADMAP-STRATEGY.md +196 -0
  5. package/ROADMAP.md +184 -0
  6. package/dist/core/analytics.d.ts +132 -0
  7. package/dist/core/analytics.d.ts.map +1 -0
  8. package/dist/core/analytics.js +290 -0
  9. package/dist/core/audit.d.ts +96 -0
  10. package/dist/core/audit.d.ts.map +1 -0
  11. package/dist/core/audit.js +297 -0
  12. package/dist/core/cron-to-schtasks.d.ts +12 -0
  13. package/dist/core/cron-to-schtasks.d.ts.map +1 -0
  14. package/dist/core/cron-to-schtasks.js +175 -0
  15. package/dist/core/dry-run.d.ts +102 -0
  16. package/dist/core/dry-run.d.ts.map +1 -0
  17. package/dist/core/dry-run.js +447 -0
  18. package/dist/core/file-watcher.d.ts +31 -0
  19. package/dist/core/file-watcher.d.ts.map +1 -0
  20. package/dist/core/file-watcher.js +186 -0
  21. package/dist/core/git-trigger.d.ts +82 -0
  22. package/dist/core/git-trigger.d.ts.map +1 -0
  23. package/dist/core/git-trigger.js +312 -0
  24. package/dist/core/glob.d.ts +38 -0
  25. package/dist/core/glob.d.ts.map +1 -0
  26. package/dist/core/glob.js +233 -0
  27. package/dist/core/local-ai.d.ts +52 -0
  28. package/dist/core/local-ai.d.ts.map +1 -0
  29. package/dist/core/local-ai.js +119 -0
  30. package/dist/core/lock.d.ts +57 -0
  31. package/dist/core/lock.d.ts.map +1 -0
  32. package/dist/core/lock.js +193 -0
  33. package/dist/core/matrix.d.ts +167 -0
  34. package/dist/core/matrix.d.ts.map +1 -0
  35. package/dist/core/matrix.js +724 -0
  36. package/dist/core/native-notify.d.ts +36 -0
  37. package/dist/core/native-notify.d.ts.map +1 -0
  38. package/dist/core/native-notify.js +113 -0
  39. package/dist/core/one-shot.d.ts +90 -0
  40. package/dist/core/one-shot.d.ts.map +1 -0
  41. package/dist/core/one-shot.js +182 -0
  42. package/dist/core/otel.d.ts +4 -0
  43. package/dist/core/otel.d.ts.map +1 -0
  44. package/dist/core/otel.js +98 -0
  45. package/dist/core/permissions.d.ts +69 -0
  46. package/dist/core/permissions.d.ts.map +1 -0
  47. package/dist/core/permissions.js +143 -0
  48. package/dist/core/prometheus.d.ts +23 -0
  49. package/dist/core/prometheus.d.ts.map +1 -0
  50. package/dist/core/prometheus.js +146 -0
  51. package/dist/core/ps-wrapper.d.ts +73 -0
  52. package/dist/core/ps-wrapper.d.ts.map +1 -0
  53. package/dist/core/ps-wrapper.js +1091 -0
  54. package/dist/core/record-history.d.ts +25 -0
  55. package/dist/core/record-history.d.ts.map +1 -0
  56. package/dist/core/record-history.js +471 -0
  57. package/dist/core/retention.d.ts +29 -0
  58. package/dist/core/retention.d.ts.map +1 -0
  59. package/dist/core/retention.js +98 -0
  60. package/dist/core/savings.d.ts +70 -0
  61. package/dist/core/savings.d.ts.map +1 -0
  62. package/dist/core/savings.js +87 -0
  63. package/dist/core/schedule-gate.d.ts +2 -0
  64. package/dist/core/schedule-gate.d.ts.map +1 -0
  65. package/dist/core/schedule-gate.js +211 -0
  66. package/dist/core/schedule-v2.d.ts +116 -0
  67. package/dist/core/schedule-v2.d.ts.map +1 -0
  68. package/dist/core/schedule-v2.js +586 -0
  69. package/dist/core/scheduler/at-fallback.d.ts +42 -0
  70. package/dist/core/scheduler/at-fallback.d.ts.map +1 -0
  71. package/dist/core/scheduler/at-fallback.js +70 -0
  72. package/dist/core/scheduler/index.d.ts +32 -0
  73. package/dist/core/scheduler/index.d.ts.map +1 -0
  74. package/dist/core/scheduler/index.js +63 -0
  75. package/dist/core/scheduler/linux.d.ts +46 -0
  76. package/dist/core/scheduler/linux.d.ts.map +1 -0
  77. package/dist/core/scheduler/linux.js +261 -0
  78. package/dist/core/scheduler/logs.d.ts +11 -0
  79. package/dist/core/scheduler/logs.d.ts.map +1 -0
  80. package/dist/core/scheduler/logs.js +34 -0
  81. package/dist/core/scheduler/mac.d.ts +46 -0
  82. package/dist/core/scheduler/mac.d.ts.map +1 -0
  83. package/dist/core/scheduler/mac.js +256 -0
  84. package/dist/core/scheduler/posix.d.ts +40 -0
  85. package/dist/core/scheduler/posix.d.ts.map +1 -0
  86. package/dist/core/scheduler/posix.js +100 -0
  87. package/dist/core/scheduler/registry.d.ts +43 -0
  88. package/dist/core/scheduler/registry.d.ts.map +1 -0
  89. package/dist/core/scheduler/registry.js +57 -0
  90. package/dist/core/scheduler/types.d.ts +86 -0
  91. package/dist/core/scheduler/types.d.ts.map +1 -0
  92. package/dist/core/scheduler/types.js +1 -0
  93. package/dist/core/scheduler/windows.d.ts +112 -0
  94. package/dist/core/scheduler/windows.d.ts.map +1 -0
  95. package/dist/core/scheduler/windows.js +749 -0
  96. package/dist/core/secrets.d.ts +66 -0
  97. package/dist/core/secrets.d.ts.map +1 -0
  98. package/dist/core/secrets.js +433 -0
  99. package/dist/core/self-analysis.d.ts +117 -0
  100. package/dist/core/self-analysis.d.ts.map +1 -0
  101. package/dist/core/self-analysis.js +539 -0
  102. package/dist/core/session.d.ts +42 -0
  103. package/dist/core/session.d.ts.map +1 -0
  104. package/dist/core/session.js +134 -0
  105. package/dist/core/shutdown.d.ts +26 -0
  106. package/dist/core/shutdown.d.ts.map +1 -0
  107. package/dist/core/shutdown.js +49 -0
  108. package/dist/core/structured-log.d.ts +84 -0
  109. package/dist/core/structured-log.d.ts.map +1 -0
  110. package/dist/core/structured-log.js +146 -0
  111. package/dist/core/summary.d.ts +69 -0
  112. package/dist/core/summary.d.ts.map +1 -0
  113. package/dist/core/summary.js +250 -0
  114. package/dist/core/telegram.d.ts +55 -0
  115. package/dist/core/telegram.d.ts.map +1 -0
  116. package/dist/core/telegram.js +344 -0
  117. package/dist/core/triage-chain.d.ts +40 -0
  118. package/dist/core/triage-chain.d.ts.map +1 -0
  119. package/dist/core/triage-chain.js +80 -0
  120. package/dist/core/triage-compare.d.ts +68 -0
  121. package/dist/core/triage-compare.d.ts.map +1 -0
  122. package/dist/core/triage-compare.js +184 -0
  123. package/dist/core/triage-rules.d.ts +23 -0
  124. package/dist/core/triage-rules.d.ts.map +1 -0
  125. package/dist/core/triage-rules.js +196 -0
  126. package/dist/core/triage-shadow.d.ts +91 -0
  127. package/dist/core/triage-shadow.d.ts.map +1 -0
  128. package/dist/core/triage-shadow.js +160 -0
  129. package/dist/core/triage-worker.d.ts +55 -0
  130. package/dist/core/triage-worker.d.ts.map +1 -0
  131. package/dist/core/triage-worker.js +314 -0
  132. package/dist/core/triage.d.ts +76 -0
  133. package/dist/core/triage.d.ts.map +1 -0
  134. package/dist/core/triage.js +271 -0
  135. package/dist/core/watch-paths.d.ts +6 -0
  136. package/dist/core/watch-paths.d.ts.map +1 -0
  137. package/dist/core/watch-paths.js +62 -0
  138. package/dist/core/wrappers/bash.d.ts +95 -0
  139. package/dist/core/wrappers/bash.d.ts.map +1 -0
  140. package/dist/core/wrappers/bash.js +413 -0
  141. package/dist/db/git-state-repo.d.ts +16 -0
  142. package/dist/db/git-state-repo.d.ts.map +1 -0
  143. package/dist/db/git-state-repo.js +38 -0
  144. package/dist/db/history-repo.d.ts +110 -0
  145. package/dist/db/history-repo.d.ts.map +1 -0
  146. package/dist/db/history-repo.js +300 -0
  147. package/dist/db/index.d.ts +49 -0
  148. package/dist/db/index.d.ts.map +1 -0
  149. package/dist/db/index.js +128 -0
  150. package/dist/db/metrics-repo.d.ts +46 -0
  151. package/dist/db/metrics-repo.d.ts.map +1 -0
  152. package/dist/db/metrics-repo.js +103 -0
  153. package/dist/db/migrate.d.ts +24 -0
  154. package/dist/db/migrate.d.ts.map +1 -0
  155. package/dist/db/migrate.js +244 -0
  156. package/dist/db/recovery.d.ts +11 -0
  157. package/dist/db/recovery.d.ts.map +1 -0
  158. package/dist/db/recovery.js +38 -0
  159. package/dist/db/run-journal.d.ts +60 -0
  160. package/dist/db/run-journal.d.ts.map +1 -0
  161. package/dist/db/run-journal.js +143 -0
  162. package/dist/db/run-resume.d.ts +48 -0
  163. package/dist/db/run-resume.d.ts.map +1 -0
  164. package/dist/db/run-resume.js +137 -0
  165. package/dist/db/runs-repo.d.ts +120 -0
  166. package/dist/db/runs-repo.d.ts.map +1 -0
  167. package/dist/db/runs-repo.js +319 -0
  168. package/dist/db/schema.d.ts +38 -0
  169. package/dist/db/schema.d.ts.map +1 -0
  170. package/dist/db/schema.js +325 -0
  171. package/dist/db/settings-repo.d.ts +8 -0
  172. package/dist/db/settings-repo.d.ts.map +1 -0
  173. package/dist/db/settings-repo.js +27 -0
  174. package/dist/db/tasks-repo.d.ts +26 -0
  175. package/dist/db/tasks-repo.d.ts.map +1 -0
  176. package/dist/db/tasks-repo.js +120 -0
  177. package/dist/db/templates-repo.d.ts +17 -0
  178. package/dist/db/templates-repo.d.ts.map +1 -0
  179. package/dist/db/templates-repo.js +57 -0
  180. package/dist/history.d.ts +60 -0
  181. package/dist/history.d.ts.map +1 -0
  182. package/dist/history.js +70 -0
  183. package/dist/i18n.d.ts +75 -0
  184. package/dist/i18n.d.ts.map +1 -0
  185. package/dist/i18n.js +357 -0
  186. package/dist/index.d.ts +858 -0
  187. package/dist/index.d.ts.map +1 -0
  188. package/dist/index.js +5209 -0
  189. package/dist/integrations.d.ts +72 -0
  190. package/dist/integrations.d.ts.map +1 -0
  191. package/dist/integrations.js +233 -0
  192. package/dist/notifications.d.ts +199 -0
  193. package/dist/notifications.d.ts.map +1 -0
  194. package/dist/notifications.js +967 -0
  195. package/dist/profiles.d.ts +64 -0
  196. package/dist/profiles.d.ts.map +1 -0
  197. package/dist/profiles.js +305 -0
  198. package/dist/rpc.d.ts +3915 -0
  199. package/dist/rpc.d.ts.map +1 -0
  200. package/dist/rpc.js +1596 -0
  201. package/dist/schtasks.d.ts +32 -0
  202. package/dist/schtasks.d.ts.map +1 -0
  203. package/dist/schtasks.js +45 -0
  204. package/dist/server.d.ts +128 -0
  205. package/dist/server.d.ts.map +1 -0
  206. package/dist/server.js +2414 -0
  207. package/dist/settings.d.ts +389 -0
  208. package/dist/settings.d.ts.map +1 -0
  209. package/dist/settings.js +770 -0
  210. package/dist/shared/jobs-view.d.ts +59 -0
  211. package/dist/shared/jobs-view.d.ts.map +1 -0
  212. package/dist/shared/jobs-view.js +146 -0
  213. package/dist/skill.d.ts +15 -0
  214. package/dist/skill.d.ts.map +1 -0
  215. package/dist/skill.js +93 -0
  216. package/dist/task-transfer.d.ts +252 -0
  217. package/dist/task-transfer.d.ts.map +1 -0
  218. package/dist/task-transfer.js +632 -0
  219. package/dist/templates.d.ts +57 -0
  220. package/dist/templates.d.ts.map +1 -0
  221. package/dist/templates.js +16 -0
  222. package/dist/types.d.ts +112 -0
  223. package/dist/types.d.ts.map +1 -0
  224. package/dist/types.js +158 -0
  225. package/dist/version.d.ts +8 -0
  226. package/dist/version.d.ts.map +1 -0
  227. package/dist/version.js +27 -0
  228. package/dist/workspaces.d.ts +113 -0
  229. package/dist/workspaces.d.ts.map +1 -0
  230. package/dist/workspaces.js +393 -0
  231. package/docs/ARCHITECTURE.md +559 -0
  232. package/docs/COMPATIBILITY.md +237 -0
  233. package/docs/CONCEPT.md +242 -0
  234. package/docs/CROSS_PLATFORM.ru.md +152 -0
  235. package/docs/CROSS_PLATFORM.zh.md +148 -0
  236. package/docs/FAQ.md +52 -0
  237. package/docs/FAQ.ru.md +53 -0
  238. package/docs/FAQ.zh.md +43 -0
  239. package/docs/FEATURES.md +699 -0
  240. package/docs/FEATURES.zh.md +656 -0
  241. package/docs/LOCAL-AI.md +300 -0
  242. package/docs/MIGRATION.md +363 -0
  243. package/docs/README.ru.md +287 -0
  244. package/docs/README.zh.md +306 -0
  245. package/docs/SAVINGS.md +61 -0
  246. package/docs/SAVINGS.ru.md +60 -0
  247. package/docs/SAVINGS.zh.md +52 -0
  248. package/docs/V1-V2-COMPATIBILITY-PLAN.md +366 -0
  249. package/docs/ZH-LOCALE-PLAN.md +324 -0
  250. package/docs/dashboard.png +0 -0
  251. package/docs/spikes/local-model-structured-output.md +81 -0
  252. package/docs/spikes/ollama-qwen3-4b-smoke.json +28 -0
  253. package/docs/spikes/ollama-qwen3-4b.json +163 -0
  254. package/gui-experimental.cjs +9 -0
  255. package/index.js +2 -0
  256. package/locales/en.json +781 -0
  257. package/locales/ru.json +781 -0
  258. package/locales/zh.json +781 -0
  259. package/package.json +154 -13
  260. package/scripts/bench-local.mjs +321 -0
  261. package/scripts/check-zh-locale.mjs +218 -0
  262. package/scripts/demo-dashboard.mjs +209 -0
  263. package/scripts/run-tests.mjs +236 -0
  264. package/scripts/spike-local-structured.mjs +182 -0
  265. package/scripts/test-locale.mjs +45 -0
  266. package/skills/scheduled-job-best-practices/SKILL.md +158 -0
  267. package/skills/scheduled-job-best-practices/references/recipes.md +163 -0
  268. package/src/core/analytics.ts +424 -0
  269. package/src/core/audit.ts +418 -0
  270. package/src/core/cron-to-schtasks.ts +209 -0
  271. package/src/core/dry-run.ts +601 -0
  272. package/src/core/file-watcher.ts +245 -0
  273. package/src/core/git-trigger.ts +391 -0
  274. package/src/core/glob.ts +226 -0
  275. package/src/core/local-ai.ts +173 -0
  276. package/src/core/lock.ts +219 -0
  277. package/src/core/matrix.ts +947 -0
  278. package/src/core/native-notify.ts +157 -0
  279. package/src/core/one-shot.ts +239 -0
  280. package/src/core/otel.ts +128 -0
  281. package/src/core/permissions.ts +200 -0
  282. package/src/core/prometheus.ts +215 -0
  283. package/src/core/ps-wrapper.ts +1160 -0
  284. package/src/core/record-history.ts +615 -0
  285. package/src/core/retention.ts +141 -0
  286. package/src/core/savings.ts +150 -0
  287. package/src/core/schedule-gate.ts +253 -0
  288. package/src/core/schedule-v2.ts +668 -0
  289. package/src/core/scheduler/at-fallback.ts +113 -0
  290. package/src/core/scheduler/index.ts +82 -0
  291. package/src/core/scheduler/linux.ts +308 -0
  292. package/src/core/scheduler/logs.ts +37 -0
  293. package/src/core/scheduler/mac.ts +322 -0
  294. package/src/core/scheduler/posix.ts +128 -0
  295. package/src/core/scheduler/registry.ts +101 -0
  296. package/src/core/scheduler/types.ts +90 -0
  297. package/src/core/scheduler/windows.ts +881 -0
  298. package/src/core/secrets.ts +503 -0
  299. package/src/core/self-analysis.ts +744 -0
  300. package/src/core/session.ts +150 -0
  301. package/src/core/shutdown.ts +69 -0
  302. package/src/core/structured-log.ts +214 -0
  303. package/src/core/summary.ts +318 -0
  304. package/src/core/telegram.ts +436 -0
  305. package/src/core/triage-chain.ts +125 -0
  306. package/src/core/triage-compare.ts +277 -0
  307. package/src/core/triage-rules.ts +238 -0
  308. package/src/core/triage-shadow.ts +240 -0
  309. package/src/core/triage-worker.ts +344 -0
  310. package/src/core/triage.ts +366 -0
  311. package/src/core/watch-paths.ts +70 -0
  312. package/src/core/wrappers/bash.ts +532 -0
  313. package/src/db/git-state-repo.ts +62 -0
  314. package/src/db/history-repo.ts +492 -0
  315. package/src/db/index.ts +176 -0
  316. package/src/db/metrics-repo.ts +170 -0
  317. package/src/db/migrate.ts +328 -0
  318. package/src/db/recovery.ts +46 -0
  319. package/src/db/run-journal.ts +212 -0
  320. package/src/db/run-resume.ts +220 -0
  321. package/src/db/runs-repo.ts +481 -0
  322. package/src/db/schema.ts +349 -0
  323. package/src/db/settings-repo.ts +31 -0
  324. package/src/db/tasks-repo.ts +162 -0
  325. package/src/db/templates-repo.ts +77 -0
  326. package/src/gui.tsx +5222 -0
  327. package/src/history.ts +128 -0
  328. package/src/i18n.ts +413 -0
  329. package/src/index.ts +6642 -0
  330. package/src/integrations.ts +297 -0
  331. package/src/notifications.ts +1346 -0
  332. package/src/profiles.ts +345 -0
  333. package/src/rpc.ts +1704 -0
  334. package/src/schtasks.ts +75 -0
  335. package/src/server.ts +2663 -0
  336. package/src/settings.ts +1369 -0
  337. package/src/shared/jobs-view.ts +188 -0
  338. package/src/skill.ts +113 -0
  339. package/src/task-transfer.ts +946 -0
  340. package/src/templates.ts +67 -0
  341. package/src/tui-v1.tsx +341 -0
  342. package/src/tui.tsx +329 -0
  343. package/src/types.ts +226 -0
  344. package/src/version.ts +27 -0
  345. package/src/workspaces.ts +487 -0
@@ -0,0 +1,70 @@
1
+ import { spawn } from "node:child_process";
2
+ const PID_JOB_PREFIX = "pid:";
3
+ /** Ошибка `spawn("at")`, означающая, что бинарник не найден. */
4
+ export function isAtMissingError(err) {
5
+ if (!err || typeof err !== "object")
6
+ return false;
7
+ const code = err.code;
8
+ if (code === "ENOENT")
9
+ return true;
10
+ const message = err.message;
11
+ return typeof message === "string" && /ENOENT|not found|no such file/i.test(message);
12
+ }
13
+ /** Сколько секунд осталось до `runAt` (0, если момент уже прошёл). */
14
+ export function computeDelaySeconds(runAt, nowMs) {
15
+ const target = Date.parse(runAt);
16
+ if (!Number.isFinite(target)) {
17
+ throw new Error(`Некорректное время one-shot: «${runAt}».`);
18
+ }
19
+ return Math.max(0, Math.ceil((target - nowMs) / 1000));
20
+ }
21
+ /** Скрипт для `/bin/bash -c`: подождать и выполнить команду задачи. */
22
+ export function buildDetachedOneShotScript(entry, command, nowMs) {
23
+ if (!entry.runAt) {
24
+ throw new Error(`Задача "${entry.name}": не задано runAt для one-shot.`);
25
+ }
26
+ const delay = computeDelaySeconds(entry.runAt, nowMs);
27
+ return `sleep ${delay}; ${command}`;
28
+ }
29
+ /** Является ли сохранённый id задания pid-ом fallback-процесса. */
30
+ export function isPidJobId(jobId) {
31
+ return typeof jobId === "string" && jobId.startsWith(PID_JOB_PREFIX);
32
+ }
33
+ function pidFromJobId(jobId) {
34
+ return Number.parseInt(jobId.slice(PID_JOB_PREFIX.length), 10);
35
+ }
36
+ /**
37
+ * Запускает отвязанный one-shot и возвращает `pid:<pid>` для `cancelAt`.
38
+ * Промис резолвится сразу после успешного `spawn`, не дожидаясь выполнения.
39
+ */
40
+ export async function scheduleAtFallback(entry, command, deps = {}) {
41
+ const spawnFn = deps.spawnFn ?? spawn;
42
+ const now = deps.now ? deps.now() : Date.now();
43
+ const script = buildDetachedOneShotScript(entry, command, now);
44
+ return new Promise((resolve, reject) => {
45
+ const child = spawnFn("/bin/bash", ["-c", script], {
46
+ detached: true,
47
+ stdio: "ignore",
48
+ });
49
+ child.once("error", reject);
50
+ child.once("spawn", () => {
51
+ child.unref();
52
+ resolve(`${PID_JOB_PREFIX}${child.pid ?? 0}`);
53
+ });
54
+ });
55
+ }
56
+ /** Снимает fallback-процесс. Ошибки (процесс уже завершился) игнорируются. */
57
+ export function cancelAtFallback(jobId) {
58
+ if (!isPidJobId(jobId))
59
+ return false;
60
+ const pid = pidFromJobId(jobId);
61
+ if (!Number.isFinite(pid) || pid <= 0)
62
+ return false;
63
+ try {
64
+ process.kill(pid, "SIGTERM");
65
+ return true;
66
+ }
67
+ catch {
68
+ return false;
69
+ }
70
+ }
@@ -0,0 +1,32 @@
1
+ import type { SchedulerBackend } from "./types.js";
2
+ export type { SchedulerBackend, CreateTaskOptions, RunTaskResult, TriggerType, } from "./types.js";
3
+ export { WindowsScheduler, SchtasksError, WINDOWS_TASK_PREFIX } from "./windows.js";
4
+ export { LinuxScheduler } from "./linux.js";
5
+ export { MacScheduler } from "./mac.js";
6
+ export { TaskRegistry } from "./registry.js";
7
+ export type { RegistryEntry } from "./registry.js";
8
+ /**
9
+ * Фабрика бэкендов планировщика по платформе.
10
+ *
11
+ * - win32 → WindowsScheduler (schtasks);
12
+ * - darwin → MacScheduler (launchd);
13
+ * - linux (и прочие POSIX) → LinuxScheduler (crontab).
14
+ */
15
+ export declare function createSchedulerBackend(platform?: NodeJS.Platform, profile?: string): SchedulerBackend;
16
+ /**
17
+ * Бэкенд планировщика в пространстве имён конкретного профиля — в том числе
18
+ * неактивного. Нужен, чтобы удаление профиля снимало ЕГО задачи, а не задачи
19
+ * активного профиля (T-05).
20
+ */
21
+ export declare function createSchedulerBackendForProfile(profile: string, platform?: NodeJS.Platform): SchedulerBackend;
22
+ /**
23
+ * Снимает все задачи профиля из планировщика ОС перед удалением его файлов.
24
+ * Ошибки по отдельным задачам игнорируются; бросает только если сам список
25
+ * задач получить не удалось.
26
+ */
27
+ export declare function removeScheduledTasksForProfile(profile: string, platform?: NodeJS.Platform): Promise<number>;
28
+ /** Возвращает общий (закэшированный) бэкенд текущей платформы. */
29
+ export declare function getSchedulerBackend(): SchedulerBackend;
30
+ /** Название планировщика для текущей платформы (для GUI/логов). */
31
+ export declare function getSchedulerTitle(platform?: NodeJS.Platform): string;
32
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/core/scheduler/index.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEnD,YAAY,EACV,gBAAgB,EAChB,iBAAiB,EACjB,aAAa,EACb,WAAW,GACZ,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACpF,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,YAAY,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAEnD;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CACpC,QAAQ,GAAE,MAAM,CAAC,QAA2B,EAC5C,OAAO,CAAC,EAAE,MAAM,GACf,gBAAgB,CAIlB;AAED;;;;GAIG;AACH,wBAAgB,gCAAgC,CAC9C,OAAO,EAAE,MAAM,EACf,QAAQ,GAAE,MAAM,CAAC,QAA2B,GAC3C,gBAAgB,CAElB;AAED;;;;GAIG;AACH,wBAAsB,8BAA8B,CAClD,OAAO,EAAE,MAAM,EACf,QAAQ,GAAE,MAAM,CAAC,QAA2B,GAC3C,OAAO,CAAC,MAAM,CAAC,CAejB;AAID,kEAAkE;AAClE,wBAAgB,mBAAmB,IAAI,gBAAgB,CAGtD;AAED,mEAAmE;AACnE,wBAAgB,iBAAiB,CAAC,QAAQ,GAAE,MAAM,CAAC,QAA2B,GAAG,MAAM,CAEtF"}
@@ -0,0 +1,63 @@
1
+ import { WindowsScheduler } from "./windows.js";
2
+ import { LinuxScheduler } from "./linux.js";
3
+ import { MacScheduler } from "./mac.js";
4
+ export { WindowsScheduler, SchtasksError, WINDOWS_TASK_PREFIX } from "./windows.js";
5
+ export { LinuxScheduler } from "./linux.js";
6
+ export { MacScheduler } from "./mac.js";
7
+ export { TaskRegistry } from "./registry.js";
8
+ /**
9
+ * Фабрика бэкендов планировщика по платформе.
10
+ *
11
+ * - win32 → WindowsScheduler (schtasks);
12
+ * - darwin → MacScheduler (launchd);
13
+ * - linux (и прочие POSIX) → LinuxScheduler (crontab).
14
+ */
15
+ export function createSchedulerBackend(platform = process.platform, profile) {
16
+ if (platform === "win32")
17
+ return new WindowsScheduler(profile);
18
+ if (platform === "darwin")
19
+ return new MacScheduler(profile);
20
+ return new LinuxScheduler(profile);
21
+ }
22
+ /**
23
+ * Бэкенд планировщика в пространстве имён конкретного профиля — в том числе
24
+ * неактивного. Нужен, чтобы удаление профиля снимало ЕГО задачи, а не задачи
25
+ * активного профиля (T-05).
26
+ */
27
+ export function createSchedulerBackendForProfile(profile, platform = process.platform) {
28
+ return createSchedulerBackend(platform, profile);
29
+ }
30
+ /**
31
+ * Снимает все задачи профиля из планировщика ОС перед удалением его файлов.
32
+ * Ошибки по отдельным задачам игнорируются; бросает только если сам список
33
+ * задач получить не удалось.
34
+ */
35
+ export async function removeScheduledTasksForProfile(profile, platform = process.platform) {
36
+ const scheduler = createSchedulerBackendForProfile(profile, platform);
37
+ const tasks = await scheduler.listTasks();
38
+ let removed = 0;
39
+ for (const task of tasks) {
40
+ const name = task.taskName ?? "";
41
+ if (!name)
42
+ continue;
43
+ try {
44
+ await scheduler.deleteTask(name);
45
+ removed++;
46
+ }
47
+ catch {
48
+ // Задача уже удалена или недоступна — продолжаем чистить остальные.
49
+ }
50
+ }
51
+ return removed;
52
+ }
53
+ let cached = null;
54
+ /** Возвращает общий (закэшированный) бэкенд текущей платформы. */
55
+ export function getSchedulerBackend() {
56
+ if (!cached)
57
+ cached = createSchedulerBackend();
58
+ return cached;
59
+ }
60
+ /** Название планировщика для текущей платформы (для GUI/логов). */
61
+ export function getSchedulerTitle(platform = process.platform) {
62
+ return createSchedulerBackend(platform).title;
63
+ }
@@ -0,0 +1,46 @@
1
+ import { PosixSchedulerBase } from "./posix.js";
2
+ import type { RegistryEntry } from "./registry.js";
3
+ /**
4
+ * Бэкенд планировщика Linux на основе пользовательского crontab.
5
+ *
6
+ * Все задачи плагина живут в одном управляемом блоке:
7
+ * # >>> opencode-scheduler >>>
8
+ * # task: <имя>
9
+ * <cron> /bin/bash '<обёртка>' >> '<лог>' 2>&1
10
+ * # <<< opencode-scheduler <<<
11
+ * При паузе строка задачи комментируется ("# PAUSED: ..."), при удалении —
12
+ * блок перегенерируется из реестра.
13
+ */
14
+ export declare class LinuxScheduler extends PosixSchedulerBase {
15
+ readonly platform: NodeJS.Platform;
16
+ readonly title = "agent-steward by DeadSno";
17
+ private readonly blockBegin;
18
+ private readonly blockEnd;
19
+ private readonly legacyBlockBegin;
20
+ private readonly legacyBlockEnd;
21
+ private readonly ownsLegacyBlock;
22
+ constructor(profile?: string);
23
+ private cronLine;
24
+ private renderBlock;
25
+ /** Читает текущий crontab (пустая строка, если crontab ещё не создан). */
26
+ private readCrontab;
27
+ /** Убирает управляемый блок плагина из текста crontab. */
28
+ private stripBlock;
29
+ /** Записывает crontab через stdin: `crontab -`. */
30
+ private writeCrontab;
31
+ /** Перегенерирует блок плагина из реестра. */
32
+ private rebuildCrontab;
33
+ /** Строка команды one-shot для stdin `at`. */
34
+ private atCommand;
35
+ /**
36
+ * Ставит one-shot в `at` и возвращает id задания.
37
+ * `at -t` принимает локальное время системы в формате YYYYMMDDHHMM.
38
+ */
39
+ private scheduleAt;
40
+ /** Отменяет задание at, если оно ещё существует. */
41
+ private cancelAt;
42
+ protected installEntry(entry: RegistryEntry): Promise<void>;
43
+ protected uninstallEntry(entry: RegistryEntry): Promise<void>;
44
+ protected applyPause(entry: RegistryEntry, paused: boolean): Promise<void>;
45
+ }
46
+ //# sourceMappingURL=linux.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"linux.d.ts","sourceRoot":"","sources":["../../../src/core/scheduler/linux.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,kBAAkB,EAAc,MAAM,YAAY,CAAC;AAC5D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAInD;;;;;;;;;;GAUG;AACH,qBAAa,cAAe,SAAQ,kBAAkB;IACpD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAW;IAC7C,QAAQ,CAAC,KAAK,8BAA8B;IAE5C,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAS;IAC1C,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAS;IACxC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAU;gBAE9B,OAAO,GAAE,MAAyB;IAY9C,OAAO,CAAC,QAAQ;IAkBhB,OAAO,CAAC,WAAW;IAYnB,0EAA0E;YAC5D,WAAW;IAkBzB,0DAA0D;IAC1D,OAAO,CAAC,UAAU;IA+BlB,mDAAmD;YACrC,YAAY;IAgB1B,8CAA8C;YAChC,cAAc;IA4B5B,8CAA8C;IAC9C,OAAO,CAAC,SAAS;IAKjB;;;OAGG;YACW,UAAU;IAuExB,oDAAoD;YACtC,QAAQ;cAgBN,YAAY,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;cAUjD,cAAc,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;cAQnD,UAAU,CAAC,KAAK,EAAE,aAAa,EAAE,MAAM,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;CAYjF"}
@@ -0,0 +1,261 @@
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 { cancelAtFallback, isAtMissingError, isPidJobId, scheduleAtFallback, } from "./at-fallback.js";
6
+ import { needsPollMode } from "../schedule-v2.js";
7
+ import { LockManager, withLockWait } from "../lock.js";
8
+ import { getBasePluginDir, getProfileName } from "../../profiles.js";
9
+ import { taskFolderNameForProfile, legacyTaskFolderNameForProfile } from "../../types.js";
10
+ import { PosixSchedulerBase, shellQuote } from "./posix.js";
11
+ const execFileAsync = promisify(execFile);
12
+ /**
13
+ * Бэкенд планировщика Linux на основе пользовательского crontab.
14
+ *
15
+ * Все задачи плагина живут в одном управляемом блоке:
16
+ * # >>> opencode-scheduler >>>
17
+ * # task: <имя>
18
+ * <cron> /bin/bash '<обёртка>' >> '<лог>' 2>&1
19
+ * # <<< opencode-scheduler <<<
20
+ * При паузе строка задачи комментируется ("# PAUSED: ..."), при удалении —
21
+ * блок перегенерируется из реестра.
22
+ */
23
+ export class LinuxScheduler extends PosixSchedulerBase {
24
+ constructor(profile = getProfileName()) {
25
+ super("linux", profile);
26
+ this.platform = "linux";
27
+ this.title = "agent-steward by DeadSno";
28
+ const folderName = taskFolderNameForProfile(profile);
29
+ const legacyFolderName = legacyTaskFolderNameForProfile(profile);
30
+ this.blockBegin = `# >>> opencode-scheduler:${folderName} >>>`;
31
+ this.blockEnd = `# <<< opencode-scheduler:${folderName} <<<`;
32
+ this.legacyBlockBegin = `# >>> opencode-scheduler:${legacyFolderName} >>>`;
33
+ this.legacyBlockEnd = `# <<< opencode-scheduler:${legacyFolderName} <<<`;
34
+ // Древний бессуффиксный блок принадлежит только профилю default.
35
+ this.ownsLegacyBlock = profile === "default";
36
+ }
37
+ cronLine(entry) {
38
+ if (entry.triggerType !== "cron") {
39
+ // Файловый/MCP-триггер не имеет расписания — держим задачу только в реестре.
40
+ return "";
41
+ }
42
+ const log = entry.logFile ? ` >> ${shellQuote(entry.logFile)} 2>&1` : "";
43
+ const cmd = `/bin/bash ${shellQuote(entry.command)}${log}`;
44
+ // crontab понимает только 5-полевой cron. Расширенные выражения (L, #,
45
+ // списки, @daily и т.п.) нельзя писать в crontab как есть — опрашиваем
46
+ // каждую минуту, а решение о запуске принимает gate во враппере.
47
+ // Задачи с чужой IANA-таймзоной (не системной) тоже уходят в poll-режим,
48
+ // иначе crontab сработает по системному времени, а не по таймзоне задачи.
49
+ const schedule = needsPollMode(entry.schedule, entry.timezone)
50
+ ? "* * * * *"
51
+ : entry.schedule;
52
+ return `${schedule} ${cmd}`;
53
+ }
54
+ renderBlock(entries) {
55
+ const lines = [this.blockBegin];
56
+ for (const entry of entries) {
57
+ const line = this.cronLine(entry);
58
+ if (!line)
59
+ 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
+ /** Читает текущий crontab (пустая строка, если crontab ещё не создан). */
67
+ async readCrontab() {
68
+ try {
69
+ const { stdout } = await execFileAsync("crontab", ["-l"], {
70
+ maxBuffer: 10 * 1024 * 1024,
71
+ });
72
+ return stdout;
73
+ }
74
+ catch (err) {
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
+ /** Убирает управляемый блок плагина из текста crontab. */
86
+ stripBlock(content) {
87
+ // Совместимость: до появления профилей блок назывался без суффикса.
88
+ // Он принадлежит профилю default; другие профили его не трогают.
89
+ const legacyBegin = "# >>> opencode-scheduler >>>";
90
+ const legacyEnd = "# <<< opencode-scheduler <<<";
91
+ const ownsLegacy = this.ownsLegacyBlock;
92
+ const isBegin = (line) => line === this.blockBegin ||
93
+ line === this.legacyBlockBegin ||
94
+ (ownsLegacy && line === legacyBegin);
95
+ const isEnd = (line) => line === this.blockEnd ||
96
+ line === this.legacyBlockEnd ||
97
+ (ownsLegacy && line === legacyEnd);
98
+ const lines = content.split(/\r?\n/);
99
+ const result = [];
100
+ let inside = false;
101
+ for (const line of lines) {
102
+ if (isBegin(line.trim())) {
103
+ inside = true;
104
+ continue;
105
+ }
106
+ if (isEnd(line.trim())) {
107
+ inside = false;
108
+ continue;
109
+ }
110
+ if (!inside)
111
+ result.push(line);
112
+ }
113
+ return result.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd();
114
+ }
115
+ /** Записывает crontab через stdin: `crontab -`. */
116
+ async writeCrontab(content) {
117
+ await new Promise((resolve, reject) => {
118
+ const child = spawn("crontab", ["-"], { stdio: ["pipe", "ignore", "pipe"] });
119
+ let stderr = "";
120
+ child.stderr.on("data", (chunk) => {
121
+ stderr += String(chunk);
122
+ });
123
+ child.on("error", reject);
124
+ child.on("close", (code) => {
125
+ if (code === 0)
126
+ resolve();
127
+ else
128
+ reject(new Error(`crontab - завершился с кодом ${code}: ${stderr.trim()}`));
129
+ });
130
+ child.stdin.end(content.endsWith("\n") ? content : `${content}\n`);
131
+ });
132
+ }
133
+ /** Перегенерирует блок плагина из реестра. */
134
+ async rebuildCrontab() {
135
+ // T-17: crontab общий для всех профилей пользователя, а read-modify-write
136
+ // не атомарен — параллельные операции разных профилей могли затирать блоки
137
+ // друг друга. Кросс-процессный замок живёт в базовой директории плагина
138
+ // (общей для всех профилей) и ждёт освобождения вместо пропуска.
139
+ const crontabLock = new LockManager(path.join(getBasePluginDir(), "locks"));
140
+ await withLockWait(crontabLock, "crontab", async () => {
141
+ const entries = await this.registry.load();
142
+ const current = await this.readCrontab();
143
+ const base = this.stripBlock(current);
144
+ const block = this.renderBlock(entries);
145
+ // Пустой блок (нет задач) не пишем, чтобы не оставлять мусор в crontab.
146
+ const hasTasks = block
147
+ .split("\n")
148
+ .some((line) => line.trim().startsWith("# task:"));
149
+ const next = [base, hasTasks ? block : ""].filter(Boolean).join("\n");
150
+ await this.writeCrontab(next);
151
+ }, { timeoutMs: 15000, staleMs: 60000 });
152
+ }
153
+ /** Строка команды one-shot для stdin `at`. */
154
+ atCommand(entry) {
155
+ const log = entry.logFile ? ` >> ${shellQuote(entry.logFile)} 2>&1` : "";
156
+ return `/bin/bash ${shellQuote(entry.command)}${log}`;
157
+ }
158
+ /**
159
+ * Ставит one-shot в `at` и возвращает id задания.
160
+ * `at -t` принимает локальное время системы в формате YYYYMMDDHHMM.
161
+ */
162
+ async scheduleAt(entry) {
163
+ if (!entry.runAt) {
164
+ throw new Error(`Задача "${entry.name}": не задано runAt для one-shot.`);
165
+ }
166
+ const timestamp = buildAtTimestamp(entry.runAt);
167
+ return new Promise((resolve, reject) => {
168
+ const child = spawn("at", ["-t", timestamp], {
169
+ stdio: ["pipe", "pipe", "pipe"],
170
+ });
171
+ let stdout = "";
172
+ let stderr = "";
173
+ child.stdout.on("data", (chunk) => {
174
+ stdout += String(chunk);
175
+ });
176
+ child.stderr.on("data", (chunk) => {
177
+ stderr += String(chunk);
178
+ });
179
+ child.on("error", (err) => {
180
+ // P1-7.T1.2: `at` может отсутствовать (минимальные образы, Alpine и
181
+ // т.п.). Не роняем задачу — планируем отвязанный bash-процесс.
182
+ if (isAtMissingError(err)) {
183
+ void scheduleAtFallback(entry, this.atCommand(entry))
184
+ .then((jobId) => {
185
+ console.warn(`[agent-steward] at не найден — задача "${entry.name}" запланирована через fallback (${jobId}). ` +
186
+ "Fallback не переживает перезагрузку; установите пакет at.");
187
+ resolve(jobId);
188
+ })
189
+ .catch((fallbackErr) => {
190
+ reject(new Error(`Не удалось вызвать at и fallback-планировщик: ${fallbackErr instanceof Error
191
+ ? fallbackErr.message
192
+ : String(fallbackErr)}`));
193
+ });
194
+ return;
195
+ }
196
+ reject(new Error(`Не удалось вызвать at (установите пакет at): ${err instanceof Error ? err.message : String(err)}`));
197
+ });
198
+ child.on("close", (code) => {
199
+ if (code !== 0) {
200
+ reject(new Error(`at завершился с кодом ${code}: ${stderr.trim() || stdout.trim()}`));
201
+ return;
202
+ }
203
+ // GNU at пишет «job N at …» в stderr, а не в stdout — ищем в обоих потоках.
204
+ const match = /job\s+(\d+)/i.exec(stdout + "\n" + stderr);
205
+ if (!match) {
206
+ reject(new Error(`at не вернул id задания: ${stdout.trim()}`));
207
+ return;
208
+ }
209
+ resolve(match[1]);
210
+ });
211
+ child.stdin.end(`${this.atCommand(entry)}\n`);
212
+ });
213
+ }
214
+ /** Отменяет задание at, если оно ещё существует. */
215
+ async cancelAt(entry) {
216
+ if (!entry.atJobId)
217
+ return;
218
+ if (isPidJobId(entry.atJobId)) {
219
+ // P1-7.T1.2: снимаем fallback-процесс, а не at-задание.
220
+ cancelAtFallback(entry.atJobId);
221
+ delete entry.atJobId;
222
+ return;
223
+ }
224
+ try {
225
+ await execFileAsync("atrm", [entry.atJobId]);
226
+ }
227
+ catch {
228
+ // Задание уже выполнилось или было удалено — это не ошибка.
229
+ }
230
+ delete entry.atJobId;
231
+ }
232
+ async installEntry(entry) {
233
+ if (entry.triggerType === "once") {
234
+ if (!entry.paused) {
235
+ entry.atJobId = await this.scheduleAt(entry);
236
+ }
237
+ return;
238
+ }
239
+ await this.rebuildCrontab();
240
+ }
241
+ async uninstallEntry(entry) {
242
+ if (entry.triggerType === "once") {
243
+ await this.cancelAt(entry);
244
+ return;
245
+ }
246
+ await this.rebuildCrontab();
247
+ }
248
+ async applyPause(entry, paused) {
249
+ if (entry.triggerType === "once") {
250
+ if (paused) {
251
+ await this.cancelAt(entry);
252
+ }
253
+ else if (entry.runAt && Date.parse(entry.runAt) > Date.now()) {
254
+ entry.atJobId = await this.scheduleAt(entry);
255
+ }
256
+ await this.registry.upsert(entry);
257
+ return;
258
+ }
259
+ await this.rebuildCrontab();
260
+ }
261
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Читает файл лога задачи и возвращает последние 50 строк.
3
+ *
4
+ * Лог пишут обёртки (PowerShell на Windows, bash на POSIX) в
5
+ * ${LOG_DIR}/<sanitizedName>.log — тот же путь, что передаётся при создании.
6
+ */
7
+ export declare function getTaskLogs(name: string, limit?: number): Promise<{
8
+ logs: string;
9
+ error?: string;
10
+ }>;
11
+ //# sourceMappingURL=logs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logs.d.ts","sourceRoot":"","sources":["../../../src/core/scheduler/logs.ts"],"names":[],"mappings":"AAIA;;;;;GAKG;AACH,wBAAsB,WAAW,CAC/B,IAAI,EAAE,MAAM,EACZ,KAAK,SAAK,GACT,OAAO,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CAuB3C"}
@@ -0,0 +1,34 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { LOG_DIR, sanitizeName } from "../../types.js";
4
+ /**
5
+ * Читает файл лога задачи и возвращает последние 50 строк.
6
+ *
7
+ * Лог пишут обёртки (PowerShell на Windows, bash на POSIX) в
8
+ * ${LOG_DIR}/<sanitizedName>.log — тот же путь, что передаётся при создании.
9
+ */
10
+ export async function getTaskLogs(name, limit = 50) {
11
+ const logPath = path.join(LOG_DIR, `${sanitizeName(name)}.log`);
12
+ try {
13
+ // PowerShell 5.1 пишет UTF-8 с BOM — убираем его, чтобы GUI не показывал мусор.
14
+ const content = (await fs.readFile(logPath, "utf8")).replace(/^\uFEFF/, "");
15
+ const lines = content.split(/\r?\n/).filter((line) => line.trim());
16
+ if (lines.length === 0) {
17
+ return {
18
+ logs: "",
19
+ error: `Лог задачи "${name}" пуст. Задача ещё не писала вывод — запустите её и повторите.`,
20
+ };
21
+ }
22
+ const last = lines.slice(-Math.max(1, Math.min(limit, 1000)));
23
+ return { logs: last.join("\n") };
24
+ }
25
+ catch (err) {
26
+ if (err.code === "ENOENT") {
27
+ return {
28
+ logs: "",
29
+ error: `Лог задачи "${name}" не найден по пути ${logPath} (задача ещё не запускалась).`,
30
+ };
31
+ }
32
+ return { logs: "", error: err instanceof Error ? err.message : String(err) };
33
+ }
34
+ }
@@ -0,0 +1,46 @@
1
+ import { PosixSchedulerBase } from "./posix.js";
2
+ import type { RegistryEntry } from "./registry.js";
3
+ /** Один элемент StartCalendarInterval. */
4
+ interface LaunchdCalendar {
5
+ Minute?: number;
6
+ Hour?: number;
7
+ Weekday?: number;
8
+ Month?: number;
9
+ Day?: number;
10
+ }
11
+ /** Расписание launchd, полученное из cron-выражения. */
12
+ interface LaunchdSchedule {
13
+ /** StartInterval в секундах (для poll-режима «каждую минуту»). */
14
+ interval?: number;
15
+ /** Одиночный StartCalendarInterval (фиксированное время). */
16
+ calendar?: LaunchdCalendar;
17
+ /** Массив StartCalendarInterval (например, минуты 0,15,30,45). */
18
+ calendars?: LaunchdCalendar[];
19
+ }
20
+ /**
21
+ * Преобразует поддерживаемое 5-полевое cron-выражение в расписание launchd.
22
+ * Поддерживается то же подмножество, что и у Windows-бэкенда.
23
+ */
24
+ export declare function cronToLaunchdSchedule(cron: string): LaunchdSchedule;
25
+ /**
26
+ * Бэкенд планировщика macOS на основе launchd.
27
+ *
28
+ * Каждая задача — отдельный LaunchAgent:
29
+ * ~/Library/LaunchAgents/com.opencode.scheduler.<name>.plist
30
+ * Управление — через launchctl load/unload -w.
31
+ */
32
+ export declare class MacScheduler extends PosixSchedulerBase {
33
+ readonly platform: NodeJS.Platform;
34
+ readonly title = "agent-steward by DeadSno";
35
+ constructor(profile?: string);
36
+ private readonly profile;
37
+ private label;
38
+ private plistPath;
39
+ /** Выполняет launchctl, не считая ошибку фатальной (unload несуществующего). */
40
+ private launchctl;
41
+ protected installEntry(entry: RegistryEntry): Promise<void>;
42
+ protected uninstallEntry(entry: RegistryEntry): Promise<void>;
43
+ protected applyPause(entry: RegistryEntry, paused: boolean): Promise<void>;
44
+ }
45
+ export {};
46
+ //# sourceMappingURL=mac.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mac.d.ts","sourceRoot":"","sources":["../../../src/core/scheduler/mac.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAgBnD,0CAA0C;AAC1C,UAAU,eAAe;IACvB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED,wDAAwD;AACxD,UAAU,eAAe;IACvB,kEAAkE;IAClE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,6DAA6D;IAC7D,QAAQ,CAAC,EAAE,eAAe,CAAC;IAC3B,kEAAkE;IAClE,SAAS,CAAC,EAAE,eAAe,EAAE,CAAC;CAC/B;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,GAAG,eAAe,CA6DnE;AAuID;;;;;;GAMG;AACH,qBAAa,YAAa,SAAQ,kBAAkB;IAClD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAY;IAC9C,QAAQ,CAAC,KAAK,8BAA8B;gBAEhC,OAAO,GAAE,MAAyB;IAK9C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IAEjC,OAAO,CAAC,KAAK;IAmBb,OAAO,CAAC,SAAS;IAIjB,gFAAgF;YAClE,SAAS;cAQP,YAAY,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;cAQjD,cAAc,CAAC,KAAK,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;cAMnD,UAAU,CAAC,KAAK,EAAE,aAAa,EAAE,MAAM,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;CAQjF"}