agent-steward 0.0.2 → 0.0.3

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