@tidegap/core 0.18.0 → 0.20.0

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 (171) hide show
  1. package/README.md +3 -1
  2. package/dist/agent-snippet.d.ts +30 -0
  3. package/dist/agent-snippet.js +120 -0
  4. package/dist/budget.d.ts +0 -12
  5. package/dist/budget.js +2 -24
  6. package/dist/channels/commands.d.ts +137 -0
  7. package/dist/channels/commands.js +377 -0
  8. package/dist/channels/delivery-codes.d.ts +9 -0
  9. package/dist/channels/delivery-codes.js +53 -0
  10. package/dist/channels/digest.d.ts +102 -0
  11. package/dist/channels/digest.js +146 -0
  12. package/dist/channels/format.d.ts +127 -0
  13. package/dist/channels/format.js +407 -0
  14. package/dist/channels/index.d.ts +15 -0
  15. package/dist/channels/index.js +15 -0
  16. package/dist/channels/kinds/command.d.ts +13 -0
  17. package/dist/channels/kinds/command.js +65 -0
  18. package/dist/channels/kinds/discord.d.ts +16 -0
  19. package/dist/channels/kinds/discord.js +67 -0
  20. package/dist/channels/kinds/email.d.ts +20 -0
  21. package/dist/channels/kinds/email.js +162 -0
  22. package/dist/channels/kinds/index.d.ts +8 -0
  23. package/dist/channels/kinds/index.js +17 -0
  24. package/dist/channels/kinds/ntfy.d.ts +25 -0
  25. package/dist/channels/kinds/ntfy.js +163 -0
  26. package/dist/channels/kinds/pushover.d.ts +11 -0
  27. package/dist/channels/kinds/pushover.js +77 -0
  28. package/dist/channels/kinds/shared.d.ts +25 -0
  29. package/dist/channels/kinds/shared.js +39 -0
  30. package/dist/channels/kinds/shortcuts.d.ts +9 -0
  31. package/dist/channels/kinds/shortcuts.js +45 -0
  32. package/dist/channels/kinds/slack.d.ts +8 -0
  33. package/dist/channels/kinds/slack.js +57 -0
  34. package/dist/channels/kinds/telegram.d.ts +4 -0
  35. package/dist/channels/kinds/telegram.js +26 -0
  36. package/dist/channels/kinds/webhook.d.ts +30 -0
  37. package/dist/channels/kinds/webhook.js +177 -0
  38. package/dist/channels/payload.d.ts +36 -0
  39. package/dist/channels/payload.js +61 -0
  40. package/dist/channels/plan.d.ts +24 -0
  41. package/dist/channels/plan.js +66 -0
  42. package/dist/channels/registry.d.ts +191 -0
  43. package/dist/channels/registry.js +125 -0
  44. package/dist/channels/telegram.d.ts +110 -0
  45. package/dist/channels/telegram.js +168 -0
  46. package/dist/channels/types.d.ts +107 -0
  47. package/dist/channels/types.js +26 -0
  48. package/dist/claude-tools.d.ts +29 -0
  49. package/dist/claude-tools.js +49 -0
  50. package/dist/data/tables.generated.d.ts +6 -0
  51. package/dist/data/tables.generated.js +37 -0
  52. package/dist/energy.d.ts +77 -0
  53. package/dist/energy.js +131 -0
  54. package/dist/grid.d.ts +19 -2
  55. package/dist/grid.js +84 -28
  56. package/dist/handoff.d.ts +152 -0
  57. package/dist/handoff.js +430 -0
  58. package/dist/history.d.ts +2 -0
  59. package/dist/history.js +3 -1
  60. package/dist/index.d.ts +46 -16
  61. package/dist/index.js +34 -8
  62. package/dist/job-cadence.d.ts +76 -0
  63. package/dist/job-cadence.js +240 -0
  64. package/dist/jobs.d.ts +173 -0
  65. package/dist/jobs.js +794 -0
  66. package/dist/notify.d.ts +2 -0
  67. package/dist/notify.js +2 -1
  68. package/dist/paths.d.ts +13 -46
  69. package/dist/paths.js +51 -219
  70. package/dist/postpone.d.ts +113 -0
  71. package/dist/postpone.js +185 -0
  72. package/dist/providers/anthropic.js +7 -3
  73. package/dist/providers/base.d.ts +113 -1
  74. package/dist/providers/base.js +15 -0
  75. package/dist/providers/budget.d.ts +25 -0
  76. package/dist/providers/budget.js +57 -0
  77. package/dist/providers/defaults.js +4 -0
  78. package/dist/providers/defer.d.ts +16 -0
  79. package/dist/providers/defer.js +31 -0
  80. package/dist/providers/gemini.d.ts +1 -0
  81. package/dist/providers/gemini.js +27 -20
  82. package/dist/providers/index.d.ts +2 -2
  83. package/dist/providers/index.js +1 -1
  84. package/dist/providers/ollama.d.ts +1 -0
  85. package/dist/providers/ollama.js +26 -22
  86. package/dist/providers/openai.js +5 -5
  87. package/dist/providers/timeout.d.ts +18 -0
  88. package/dist/providers/timeout.js +33 -0
  89. package/dist/quota.d.ts +7 -2
  90. package/dist/quota.js +13 -29
  91. package/dist/readiness.d.ts +169 -0
  92. package/dist/readiness.js +254 -0
  93. package/dist/redact.d.ts +42 -0
  94. package/dist/redact.js +110 -0
  95. package/dist/region-host.d.ts +30 -0
  96. package/dist/region-host.js +69 -0
  97. package/dist/region.d.ts +102 -20
  98. package/dist/region.js +175 -23
  99. package/dist/run-session.d.ts +36 -0
  100. package/dist/run-session.js +72 -0
  101. package/dist/schedule-job.d.ts +95 -0
  102. package/dist/schedule-job.js +195 -0
  103. package/dist/scheduler.d.ts +245 -14
  104. package/dist/scheduler.js +925 -110
  105. package/dist/sign.d.ts +8 -1
  106. package/dist/sign.js +49 -3
  107. package/dist/storage/sqlite.d.ts +157 -5
  108. package/dist/storage/sqlite.js +661 -20
  109. package/dist/task-events.d.ts +102 -0
  110. package/dist/task-events.js +308 -0
  111. package/dist/tool-surface.d.ts +31 -2
  112. package/dist/tool-surface.js +359 -65
  113. package/dist/types.d.ts +246 -3
  114. package/dist/types.js +8 -1
  115. package/dist/zone-time.d.ts +22 -0
  116. package/dist/zone-time.js +76 -0
  117. package/package.json +11 -6
  118. package/dist/aggregator.d.ts.map +0 -1
  119. package/dist/aggregator.js.map +0 -1
  120. package/dist/budget.d.ts.map +0 -1
  121. package/dist/budget.js.map +0 -1
  122. package/dist/data/tables.generated.d.ts.map +0 -1
  123. package/dist/data/tables.generated.js.map +0 -1
  124. package/dist/energy.d.ts.map +0 -1
  125. package/dist/energy.js.map +0 -1
  126. package/dist/grid.d.ts.map +0 -1
  127. package/dist/grid.js.map +0 -1
  128. package/dist/history.d.ts.map +0 -1
  129. package/dist/history.js.map +0 -1
  130. package/dist/index.d.ts.map +0 -1
  131. package/dist/index.js.map +0 -1
  132. package/dist/notify.d.ts.map +0 -1
  133. package/dist/notify.js.map +0 -1
  134. package/dist/paths.d.ts.map +0 -1
  135. package/dist/paths.js.map +0 -1
  136. package/dist/providers/anthropic.d.ts.map +0 -1
  137. package/dist/providers/anthropic.js.map +0 -1
  138. package/dist/providers/base.d.ts.map +0 -1
  139. package/dist/providers/base.js.map +0 -1
  140. package/dist/providers/defaults.d.ts.map +0 -1
  141. package/dist/providers/defaults.js.map +0 -1
  142. package/dist/providers/gemini.d.ts.map +0 -1
  143. package/dist/providers/gemini.js.map +0 -1
  144. package/dist/providers/index.d.ts.map +0 -1
  145. package/dist/providers/index.js.map +0 -1
  146. package/dist/providers/ollama.d.ts.map +0 -1
  147. package/dist/providers/ollama.js.map +0 -1
  148. package/dist/providers/openai.d.ts.map +0 -1
  149. package/dist/providers/openai.js.map +0 -1
  150. package/dist/quota.d.ts.map +0 -1
  151. package/dist/quota.js.map +0 -1
  152. package/dist/recommend.d.ts.map +0 -1
  153. package/dist/recommend.js.map +0 -1
  154. package/dist/redact.d.ts.map +0 -1
  155. package/dist/redact.js.map +0 -1
  156. package/dist/region.d.ts.map +0 -1
  157. package/dist/region.js.map +0 -1
  158. package/dist/routing.d.ts.map +0 -1
  159. package/dist/routing.js.map +0 -1
  160. package/dist/scheduler.d.ts.map +0 -1
  161. package/dist/scheduler.js.map +0 -1
  162. package/dist/select-window.d.ts.map +0 -1
  163. package/dist/select-window.js.map +0 -1
  164. package/dist/sign.d.ts.map +0 -1
  165. package/dist/sign.js.map +0 -1
  166. package/dist/storage/sqlite.d.ts.map +0 -1
  167. package/dist/storage/sqlite.js.map +0 -1
  168. package/dist/tool-surface.d.ts.map +0 -1
  169. package/dist/tool-surface.js.map +0 -1
  170. package/dist/types.d.ts.map +0 -1
  171. package/dist/types.js.map +0 -1
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Cadence, window and anchor math of floating recurring jobs (KTD5).
3
+ *
4
+ * Pure functions, no I/O. A job runs once per period, at the cleanest hour
5
+ * inside `[earliest, deadline]` of its next occurrence:
6
+ *
7
+ * - Run-anchored (`daily` or `every N hours`, no window): the next run is
8
+ * due one period after the last run started, never sooner than half a
9
+ * period after it. With no last run (a new or resumed job) it is due one
10
+ * period from now. A deadline that is not after now falls back to the
11
+ * no-last-run rule, so an overdue job never gets a past deadline.
12
+ * - Calendar-anchored (any window, `weekdays`, `weekly`): slots are local
13
+ * wall-clock windows in the job's IANA zone on allowed days; no window
14
+ * means the whole local day. The next slot is the first one that starts
15
+ * after the last run and ends after now.
16
+ *
17
+ * DST: a local time that does not exist (spring forward) moves forward to
18
+ * the next valid minute; a repeated local time (fall back) uses its first
19
+ * instant. A slot that DST collapses keeps its nominal length.
20
+ *
21
+ * Catch-up (R6) needs no extra rule: a job keeps one live occurrence, an
22
+ * overdue one is simply due on the next tick, and its successor is computed
23
+ * from that run's start.
24
+ */
25
+ import type { JobCadence, JobWindow, Occurrence } from "./types.js";
26
+ /** A schedule input the user gave that breaks a rule; the message names the rule. */
27
+ export declare class JobScheduleError extends Error {
28
+ constructor(message: string);
29
+ }
30
+ /** The part of a job that decides when it runs. */
31
+ export interface JobSchedule {
32
+ cadence: JobCadence;
33
+ window?: JobWindow;
34
+ /** IANA zone. */
35
+ timeZone: string;
36
+ }
37
+ /** Inputs of {@link nextOccurrence}; instants as ISO strings, Dates or epoch ms. */
38
+ export interface NextOccurrenceInput {
39
+ now: Date | string | number;
40
+ /** Start of the job's last run, if it ever ran (ignored on resume). */
41
+ lastRunStart?: Date | string | number;
42
+ /**
43
+ * Deadline of an occurrence the user skipped. The successor is anchored
44
+ * on it: a calendar job takes the first slot starting at or after it, a
45
+ * run-anchored job counts from it.
46
+ */
47
+ skippedDeadline?: Date | string | number;
48
+ }
49
+ export declare const MIN_EVERY_HOURS = 2;
50
+ export declare const MAX_EVERY_HOURS = 168;
51
+ /**
52
+ * Parse a window `HH:MM-HH:MM` in local time. An end at or before the start
53
+ * crosses midnight; an end equal to the start is refused.
54
+ */
55
+ export declare function parseWindow(text: string): JobWindow;
56
+ /**
57
+ * Parse a cadence: `daily`, `weekdays`, `weekly:<days>` (or `weekly <days>`,
58
+ * days comma-separated) or `every <N>h` (also `every <N> hours`).
59
+ */
60
+ export declare function parseCadence(text: string): JobCadence;
61
+ /**
62
+ * Check a schedule against the rules and return it normalized (weekly days
63
+ * deduplicated, Monday first). Throws {@link JobScheduleError} naming the
64
+ * broken rule.
65
+ */
66
+ export declare function validateJobSchedule(schedule: JobSchedule): JobSchedule;
67
+ /** True when the schedule runs in calendar slots rather than from the last run. */
68
+ export declare function isCalendarAnchored(schedule: JobSchedule): boolean;
69
+ /**
70
+ * The next occurrence of a job. Throws {@link JobScheduleError} on a
71
+ * schedule that breaks a rule (see {@link validateJobSchedule}).
72
+ */
73
+ export declare function nextOccurrence(schedule: JobSchedule, input: NextOccurrenceInput): Occurrence;
74
+ /** The guarantee a schedule gives, as one sentence (R4). */
75
+ export declare function guaranteeText(schedule: JobSchedule): string;
76
+ //# sourceMappingURL=job-cadence.d.ts.map
@@ -0,0 +1,240 @@
1
+ /**
2
+ * Cadence, window and anchor math of floating recurring jobs (KTD5).
3
+ *
4
+ * Pure functions, no I/O. A job runs once per period, at the cleanest hour
5
+ * inside `[earliest, deadline]` of its next occurrence:
6
+ *
7
+ * - Run-anchored (`daily` or `every N hours`, no window): the next run is
8
+ * due one period after the last run started, never sooner than half a
9
+ * period after it. With no last run (a new or resumed job) it is due one
10
+ * period from now. A deadline that is not after now falls back to the
11
+ * no-last-run rule, so an overdue job never gets a past deadline.
12
+ * - Calendar-anchored (any window, `weekdays`, `weekly`): slots are local
13
+ * wall-clock windows in the job's IANA zone on allowed days; no window
14
+ * means the whole local day. The next slot is the first one that starts
15
+ * after the last run and ends after now.
16
+ *
17
+ * DST: a local time that does not exist (spring forward) moves forward to
18
+ * the next valid minute; a repeated local time (fall back) uses its first
19
+ * instant. A slot that DST collapses keeps its nominal length.
20
+ *
21
+ * Catch-up (R6) needs no extra rule: a job keeps one live occurrence, an
22
+ * overdue one is simply due on the next tick, and its successor is computed
23
+ * from that run's start.
24
+ */
25
+ import { isValidTimeZone, localTime, localToUtcMs } from "./zone-time.js";
26
+ /** A schedule input the user gave that breaks a rule; the message names the rule. */
27
+ export class JobScheduleError extends Error {
28
+ constructor(message) {
29
+ super(message);
30
+ this.name = "JobScheduleError";
31
+ }
32
+ }
33
+ const MINUTE_MS = 60_000;
34
+ const HOUR_MS = 60 * MINUTE_MS;
35
+ const DAY_MS = 24 * HOUR_MS;
36
+ /** Index = `Date.getUTCDay()`. */
37
+ const WEEKDAY_BY_INDEX = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
38
+ /** Display and storage order. */
39
+ const WEEKDAY_ORDER = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
40
+ const WEEKDAY_NAMES = {
41
+ monday: "mon",
42
+ tuesday: "tue",
43
+ wednesday: "wed",
44
+ thursday: "thu",
45
+ friday: "fri",
46
+ saturday: "sat",
47
+ sunday: "sun",
48
+ };
49
+ const WORK_DAYS = new Set(["mon", "tue", "wed", "thu", "fri"]);
50
+ export const MIN_EVERY_HOURS = 2;
51
+ export const MAX_EVERY_HOURS = 168;
52
+ const HHMM = /^(\d{1,2}):(\d{2})$/;
53
+ /** `HH:MM` to minutes after midnight, or undefined when malformed. */
54
+ function minutesOf(hhmm) {
55
+ const m = HHMM.exec(hhmm.trim());
56
+ if (!m)
57
+ return undefined;
58
+ const h = Number(m[1]);
59
+ const mi = Number(m[2]);
60
+ if (h > 23 || mi > 59)
61
+ return undefined;
62
+ return h * 60 + mi;
63
+ }
64
+ function hhmm(minutes) {
65
+ return `${String(Math.floor(minutes / 60)).padStart(2, "0")}:${String(minutes % 60).padStart(2, "0")}`;
66
+ }
67
+ /** One weekday name (`mon` or `monday`, any case). */
68
+ function parseWeekday(raw) {
69
+ const v = raw.trim().toLowerCase();
70
+ if (WEEKDAY_ORDER.includes(v))
71
+ return v;
72
+ const full = WEEKDAY_NAMES[v];
73
+ if (full)
74
+ return full;
75
+ throw new JobScheduleError(`unknown day "${raw.trim()}"; use mon, tue, wed, thu, fri, sat or sun`);
76
+ }
77
+ /**
78
+ * Parse a window `HH:MM-HH:MM` in local time. An end at or before the start
79
+ * crosses midnight; an end equal to the start is refused.
80
+ */
81
+ export function parseWindow(text) {
82
+ const parts = text.split("-");
83
+ const start = parts.length === 2 ? minutesOf(parts[0]) : undefined;
84
+ const end = parts.length === 2 ? minutesOf(parts[1]) : undefined;
85
+ if (start === undefined || end === undefined) {
86
+ throw new JobScheduleError(`window "${text}" must look like HH:MM-HH:MM, for example 00:00-08:00`);
87
+ }
88
+ if (start === end)
89
+ throw new JobScheduleError("window start and end must differ");
90
+ return { start: hhmm(start), end: hhmm(end) };
91
+ }
92
+ /**
93
+ * Parse a cadence: `daily`, `weekdays`, `weekly:<days>` (or `weekly <days>`,
94
+ * days comma-separated) or `every <N>h` (also `every <N> hours`).
95
+ */
96
+ export function parseCadence(text) {
97
+ const v = text.trim().toLowerCase();
98
+ if (v === "daily")
99
+ return { kind: "daily" };
100
+ if (v === "weekdays")
101
+ return { kind: "weekdays" };
102
+ const weekly = /^weekly(?:[:\s](.*))?$/.exec(v);
103
+ if (weekly) {
104
+ const days = (weekly[1] ?? "").split(",").filter((d) => d.trim() !== "").map(parseWeekday);
105
+ return { kind: "weekly", days };
106
+ }
107
+ const every = /^every[:\s]\s*(\d+)\s*(?:h|hours?)$/.exec(v);
108
+ if (every)
109
+ return { kind: "hours", every: Number(every[1]) };
110
+ throw new JobScheduleError(`unknown cadence "${text.trim()}"; use daily, weekdays, weekly:mon,thu or every 6h`);
111
+ }
112
+ /**
113
+ * Check a schedule against the rules and return it normalized (weekly days
114
+ * deduplicated, Monday first). Throws {@link JobScheduleError} naming the
115
+ * broken rule.
116
+ */
117
+ export function validateJobSchedule(schedule) {
118
+ if (typeof schedule.timeZone !== "string" || !isValidTimeZone(schedule.timeZone)) {
119
+ throw new JobScheduleError(`unknown time zone "${String(schedule.timeZone)}"; use an IANA name such as Europe/Berlin`);
120
+ }
121
+ const c = schedule.cadence;
122
+ let cadence;
123
+ switch (c?.kind) {
124
+ case "daily":
125
+ case "weekdays":
126
+ cadence = { kind: c.kind };
127
+ break;
128
+ case "weekly": {
129
+ const days = new Set((Array.isArray(c.days) ? c.days : []).map((d) => parseWeekday(String(d))));
130
+ if (days.size === 0)
131
+ throw new JobScheduleError("weekly: pick at least one day");
132
+ cadence = { kind: "weekly", days: WEEKDAY_ORDER.filter((d) => days.has(d)) };
133
+ break;
134
+ }
135
+ case "hours":
136
+ if (!Number.isInteger(c.every) || c.every < MIN_EVERY_HOURS || c.every > MAX_EVERY_HOURS) {
137
+ throw new JobScheduleError(`every N hours needs a whole N from ${MIN_EVERY_HOURS} to ${MAX_EVERY_HOURS}`);
138
+ }
139
+ cadence = { kind: "hours", every: c.every };
140
+ break;
141
+ default:
142
+ throw new JobScheduleError(`unknown cadence ${JSON.stringify(c?.kind)}`);
143
+ }
144
+ if (!schedule.window)
145
+ return { cadence, timeZone: schedule.timeZone };
146
+ if (cadence.kind === "hours") {
147
+ throw new JobScheduleError("a window works only with daily, weekdays or weekly; every N hours counts from the last run");
148
+ }
149
+ return { cadence, window: parseWindow(`${schedule.window.start}-${schedule.window.end}`), timeZone: schedule.timeZone };
150
+ }
151
+ /** True when the schedule runs in calendar slots rather than from the last run. */
152
+ export function isCalendarAnchored(schedule) {
153
+ return schedule.window !== undefined || schedule.cadence.kind === "weekdays" || schedule.cadence.kind === "weekly";
154
+ }
155
+ /** The run-anchored period in ms (`daily` = 24 h). */
156
+ function periodMs(cadence) {
157
+ return cadence.kind === "hours" ? cadence.every * HOUR_MS : DAY_MS;
158
+ }
159
+ function toMs(v) {
160
+ const ms = typeof v === "number" ? v : typeof v === "string" ? Date.parse(v) : v.getTime();
161
+ if (!Number.isFinite(ms))
162
+ throw new JobScheduleError(`invalid instant ${JSON.stringify(v)}`);
163
+ return ms;
164
+ }
165
+ /** The slot that starts on local date y-mo-d, or undefined on a day the cadence skips. */
166
+ function slotOn(y, mo, d, schedule) {
167
+ const weekday = WEEKDAY_BY_INDEX[new Date(Date.UTC(y, mo, d)).getUTCDay()];
168
+ const c = schedule.cadence;
169
+ if (c.kind === "weekdays" && !WORK_DAYS.has(weekday))
170
+ return undefined;
171
+ if (c.kind === "weekly" && !c.days.includes(weekday))
172
+ return undefined;
173
+ const tz = schedule.timeZone;
174
+ if (!schedule.window) {
175
+ return { start: localToUtcMs(y, mo, d, 0, 0, tz), end: localToUtcMs(y, mo, d + 1, 0, 0, tz) };
176
+ }
177
+ const startMin = minutesOf(schedule.window.start);
178
+ const endMin = minutesOf(schedule.window.end);
179
+ const crosses = endMin <= startMin;
180
+ const start = localToUtcMs(y, mo, d, Math.floor(startMin / 60), startMin % 60, tz);
181
+ let end = localToUtcMs(y, mo, d + (crosses ? 1 : 0), Math.floor(endMin / 60), endMin % 60, tz);
182
+ // A DST gap can swallow the slot (02:00-03:00 on a spring-forward day):
183
+ // keep its nominal length from the moved start.
184
+ if (end <= start)
185
+ end = start + ((endMin - startMin + 24 * 60) % (24 * 60)) * MINUTE_MS;
186
+ return { start, end };
187
+ }
188
+ /**
189
+ * The next occurrence of a job. Throws {@link JobScheduleError} on a
190
+ * schedule that breaks a rule (see {@link validateJobSchedule}).
191
+ */
192
+ export function nextOccurrence(schedule, input) {
193
+ const s = validateJobSchedule(schedule);
194
+ const now = toMs(input.now);
195
+ const lastRun = input.lastRunStart !== undefined ? toMs(input.lastRunStart) : undefined;
196
+ const skipped = input.skippedDeadline !== undefined ? toMs(input.skippedDeadline) : undefined;
197
+ const iso = (ms) => new Date(ms).toISOString();
198
+ if (!isCalendarAnchored(s)) {
199
+ const period = periodMs(s.cadence);
200
+ const base = skipped ?? lastRun;
201
+ if (base !== undefined && base + period > now) {
202
+ return { earliest: iso(Math.max(base + period / 2, now)), deadline: iso(base + period), anchor: "run" };
203
+ }
204
+ return { earliest: iso(now), deadline: iso(now + period), anchor: "run" };
205
+ }
206
+ // A slot that ends after now starts at most one local day before now, so
207
+ // the search starts on yesterday's local date.
208
+ const local = new Date(localTime(now, s.timeZone));
209
+ const [y, mo, d] = [local.getUTCFullYear(), local.getUTCMonth(), local.getUTCDate()];
210
+ const after = Math.max(now, skipped ?? now);
211
+ const days = Math.ceil((after - now) / DAY_MS) + 16;
212
+ for (let k = -1; k <= days; k++) {
213
+ const slot = slotOn(y, mo, d + k, s);
214
+ if (!slot || slot.end <= now)
215
+ continue;
216
+ if (lastRun !== undefined && slot.start <= lastRun)
217
+ continue;
218
+ if (skipped !== undefined && slot.start < skipped)
219
+ continue;
220
+ return { earliest: iso(Math.max(slot.start, now)), deadline: iso(slot.end), anchor: "calendar" };
221
+ }
222
+ // Unreachable for a validated schedule: every cadence has a slot each week.
223
+ throw new JobScheduleError("no slot found in the next two weeks");
224
+ }
225
+ function dayList(days) {
226
+ const names = days.map((d) => d[0].toUpperCase() + d.slice(1));
227
+ return names.length === 1 ? names[0] : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
228
+ }
229
+ /** The guarantee a schedule gives, as one sentence (R4). */
230
+ export function guaranteeText(schedule) {
231
+ const s = validateJobSchedule(schedule);
232
+ if (!isCalendarAnchored(s)) {
233
+ const h = periodMs(s.cadence) / HOUR_MS;
234
+ return `runs at least every ${h} h, never sooner than ${h / 2} h after the last run`;
235
+ }
236
+ const c = s.cadence;
237
+ const days = c.kind === "weekly" ? `every ${dayList(c.days)}` : c.kind === "weekdays" ? "every weekday (Mon-Fri)" : "every day";
238
+ return s.window ? `runs ${days} between ${s.window.start} and ${s.window.end}` : `runs once ${days}, any time of day`;
239
+ }
240
+ //# sourceMappingURL=job-cadence.js.map
package/dist/jobs.d.ts ADDED
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Floating recurring jobs: the job store actions and the job sweep.
3
+ *
4
+ * A job ("at least once a day, check my mail") keeps exactly one live
5
+ * occurrence in the ledger: an ordinary provider-call task with `job_id`
6
+ * set, `repeat = none` and no series. The id is derived, `<job_id>~<seq>`
7
+ * (a retry is `<job_id>~<seq>r`), and inserted once (`insertIfAbsent`).
8
+ *
9
+ * {@link sweepJobs} owns every transition the daemon makes (KTD2). It runs
10
+ * inside `prepareTick`, so every ticker gets it. For each job it reads the
11
+ * tracked occurrence and:
12
+ *
13
+ * - live occurrence: nothing (R17), except a `running` one whose dispatch
14
+ * is older than its caps allow, which fails as interrupted (a Batch row
15
+ * with a batch id goes back to `submitted` instead);
16
+ * - finished occurrence: records the outcome (KTD9: ok, a failure with
17
+ * one retry per slot and auto-pause after three failed slots, or a
18
+ * skip), then materializes the next occurrence;
19
+ * - no occurrence on an active job: materializes one.
20
+ *
21
+ * Every job write is a compare-and-set on `revision`. Pause, edit and
22
+ * remove write the job row first, then cancel the tracked occurrence; a
23
+ * sweep whose job write misses leaves its insert to the next pass, which
24
+ * adopts it on an active job and cancels it otherwise (the stop-flag-first
25
+ * rule). The sweep never throws.
26
+ */
27
+ import { type SleepReading } from "./readiness.js";
28
+ import type { Scheduler } from "./scheduler.js";
29
+ import { type JobCadence, type JobCaps, type JobNotify, type JobRecord, type JobTemplate, type JobWindow, type TaskRecord, type TaskStatus } from "./types.js";
30
+ /** Why a job action was refused; `code` maps to an HTTP status in the hosts. */
31
+ export declare class JobActionError extends Error {
32
+ /** `invalid` = bad input (400), `not_found` (404), `conflict` = the state forbids it (409). */
33
+ readonly code: "invalid" | "not_found" | "conflict";
34
+ /**
35
+ * A finer cause for a host that answers it: `stale_revision` = the caller
36
+ * holds an older revision than the stored job ({@link updateJob}).
37
+ */
38
+ readonly reason?: "stale_revision" | undefined;
39
+ constructor(message: string,
40
+ /** `invalid` = bad input (400), `not_found` (404), `conflict` = the state forbids it (409). */
41
+ code?: "invalid" | "not_found" | "conflict",
42
+ /**
43
+ * A finer cause for a host that answers it: `stale_revision` = the caller
44
+ * holds an older revision than the stored job ({@link updateJob}).
45
+ */
46
+ reason?: "stale_revision" | undefined);
47
+ }
48
+ /** What a caller gives to create a job. */
49
+ export interface JobInput {
50
+ title: string;
51
+ cadence: JobCadence;
52
+ window?: JobWindow;
53
+ /** IANA zone; default the system zone. */
54
+ timeZone?: string;
55
+ template: JobTemplate;
56
+ caps?: Partial<JobCaps>;
57
+ /** Default `every_run`. */
58
+ notify?: JobNotify;
59
+ /** `page`, `cli`, `mcp` or `openclaw`. */
60
+ originHost?: string;
61
+ originCwd?: string;
62
+ /**
63
+ * Deadline of the first occurrence (an agent's `schedule_task` deadline,
64
+ * AS9): it may run from now until then. Later ones follow the cadence.
65
+ */
66
+ deadline?: string | Date;
67
+ }
68
+ /** The fields {@link updateJob} can change; `window: null` removes the window. */
69
+ export interface JobPatch {
70
+ title?: string;
71
+ cadence?: JobCadence;
72
+ window?: JobWindow | null;
73
+ timeZone?: string;
74
+ template?: JobTemplate;
75
+ caps?: Partial<JobCaps>;
76
+ notify?: JobNotify;
77
+ }
78
+ /** Per-call options of the job actions. */
79
+ export interface JobActionOptions {
80
+ /** Who the change is recorded as on occurrence events; default `system`. */
81
+ actor?: string;
82
+ }
83
+ /** Options of {@link updateJob}. */
84
+ export interface JobUpdateOptions extends JobActionOptions {
85
+ /**
86
+ * The revision the caller edited. A stored job with another revision
87
+ * refuses the edit with reason `stale_revision`; omitted = last writer wins.
88
+ */
89
+ expectedRevision?: number;
90
+ }
91
+ /** One occurrence in {@link jobHistory}, newest first. */
92
+ export interface JobHistoryEntry {
93
+ taskId: string;
94
+ status: TaskStatus;
95
+ enqueuedAt: string;
96
+ scheduledFor?: string;
97
+ deadline?: string;
98
+ completedAt?: string;
99
+ /** True when the occurrence has a carbon receipt. */
100
+ hasReceipt: boolean;
101
+ /** Actual grams on the receipt, else the schedule-time estimate. */
102
+ carbonG?: number;
103
+ /** First line of the error, for a failed occurrence. */
104
+ error?: string;
105
+ }
106
+ /** What one {@link sweepJobs} pass did. */
107
+ export interface JobSweepResult {
108
+ /** One line per change and per failure, for the tick log. */
109
+ messages: string[];
110
+ /** Occurrence ids inserted this pass (retries included). */
111
+ materialized: string[];
112
+ /** Retry occurrence ids inserted this pass. */
113
+ retried: string[];
114
+ /** Jobs paused after their third failed slot this pass. */
115
+ autoPaused: string[];
116
+ /** Running occurrences failed as interrupted this pass. */
117
+ interrupted: string[];
118
+ }
119
+ /** A job secret name: what the command sees as an environment variable. */
120
+ export declare const JOB_SECRET_NAME: RegExp;
121
+ /** Delay before the one retry of a failed slot. */
122
+ export declare const JOB_RETRY_DELAY_MS: number;
123
+ /** Failed slots in a row that pause a job. */
124
+ export declare const JOB_AUTO_PAUSE_FAILURES = 3;
125
+ /** How `pauseReason` starts when the third failed slot paused the job: `auto: <first error line>`. */
126
+ export declare const JOB_AUTO_PAUSE_PREFIX = "auto: ";
127
+ /** The error line of an auto-pause reason, or undefined when the job was not paused by its failures. */
128
+ export declare function jobAutoPauseReason(pauseReason: string | undefined): string | undefined;
129
+ export declare const JOB_INTERRUPTED_ERROR = "interrupted: the tick stopped during the run";
130
+ /**
131
+ * The error of a row whose Batch submit a forced stop interrupted (batch 25
132
+ * KTD5). The provider may hold a batch for it, so no path runs it again:
133
+ * `retryTask` and the Python `retry_task` refuse it, and the sweep does not
134
+ * retry it. The text is the marker; `test/fixtures/interrupted-batch-submit.json`
135
+ * shares it with the Python core.
136
+ */
137
+ export declare const BATCH_SUBMIT_INTERRUPTED_ERROR = "interrupted: the tick stopped during the Batch submit; the provider may have accepted the batch, so check the provider's batch list before you enqueue the task again";
138
+ /**
139
+ * The job sweep (KTD2): for every job, record the outcome of its finished
140
+ * occurrence and keep one live occurrence per active job. Never throws.
141
+ */
142
+ export declare function sweepJobs(scheduler: Scheduler, now?: Date, opts?: {
143
+ sleepNow?: SleepReading | null;
144
+ }): Promise<JobSweepResult>;
145
+ /** Create a job and its first occurrence. Throws {@link JobActionError} on bad input. */
146
+ export declare function createJob(scheduler: Scheduler, input: JobInput, opts?: JobActionOptions): Promise<JobRecord>;
147
+ /**
148
+ * Change a job; the pending occurrence is replaced by one on the new rule (a
149
+ * running one keeps its template). With `expectedRevision`, a job another
150
+ * writer changed since is refused with reason `stale_revision`.
151
+ */
152
+ export declare function updateJob(scheduler: Scheduler, jobId: string, patch: JobPatch, opts?: JobUpdateOptions): Promise<JobRecord>;
153
+ /** Pause an active job; its pending occurrence is cancelled, a running one finishes with no successor. */
154
+ export declare function pauseJob(scheduler: Scheduler, jobId: string, opts?: JobActionOptions): Promise<JobRecord>;
155
+ /** Resume a paused job: counter reset, one occurrence from now, no backfill (R8). */
156
+ export declare function resumeJob(scheduler: Scheduler, jobId: string, opts?: JobActionOptions): Promise<JobRecord>;
157
+ /**
158
+ * Run a job at the next tick (AS10): its pending occurrence is expedited
159
+ * (no second row). Refused while an occurrence runs or the job is paused.
160
+ * Returns the expedited occurrence.
161
+ */
162
+ export declare function runJobNow(scheduler: Scheduler, jobId: string, opts?: JobActionOptions): Promise<TaskRecord<unknown>>;
163
+ /** Remove a job: it stops and is hidden; its rows and history stay (AS11). */
164
+ export declare function removeJob(scheduler: Scheduler, jobId: string, opts?: JobActionOptions): Promise<JobRecord>;
165
+ /** One job, removed ones included; undefined when the id is unknown. */
166
+ export declare function getJob(scheduler: Scheduler, jobId: string): JobRecord | undefined;
167
+ /** Jobs, oldest first; removed jobs are hidden unless asked for. */
168
+ export declare function listJobs(scheduler: Scheduler, opts?: {
169
+ includeRemoved?: boolean;
170
+ }): JobRecord[];
171
+ /** A job's occurrences, newest first. */
172
+ export declare function jobHistory(scheduler: Scheduler, jobId: string, limit?: number): JobHistoryEntry[];
173
+ //# sourceMappingURL=jobs.d.ts.map