tryharness 0.7.31 → 0.7.33

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.
@@ -0,0 +1,361 @@
1
+ import { randomUUID } from "node:crypto";
2
+
3
+ // Check-ins: a thread's agents woken again later on their own, for work that runs longer than one turn (a render, a
4
+ // deploy, a market that settles tomorrow) or that should be looked at again and again. The person
5
+ // sets one on any thread; the thread's lead (its coordinator) sets one when a round finds the work has to wait, from a
6
+ // fixed set of times (LEAD_TIMES), so the lead never writes a time of its own and keeps one check-in per thread. The
7
+ // relay keeps them: each run posts in the thread and wakes the agents it names, or the lead when it names none.
8
+ // A run missed while the relay was off or the Mac slept happens once when it is back, saying how late it is, never once
9
+ // for each slot it missed. A paused thread skips its runs and picks up at the next one after it resumes; a one-time
10
+ // check-in waits for the resume, since it has no next one. A thread that ends ends its check-ins.
11
+
12
+ // Node's timers stop counting while the Mac sleeps, so a long timer would fire hours late; the wall clock is read on a
13
+ // short poll instead.
14
+ const POLL_MS = 30_000;
15
+ // Within two polls of its time a run is on time; later, its post says it ran late and when it was due.
16
+ const LATE_AFTER_MS = 2 * POLL_MS;
17
+ // The shortest repeat, the same as automations on Harness's server (src/server/schedules/cadence.ts).
18
+ export const MIN_EVERY_MINUTES = 5;
19
+ const WHAT_CHARS = 2_000;
20
+ // A repeating check-in the lead set ends after this many runs; the person can remove it sooner or set their own.
21
+ export const LEAD_MAX_RUNS = 24;
22
+ const DAY_NAMES = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
23
+
24
+ /** The times the lead picks from (src/server/swarm/coordinator.ts COME_BACK), each as the check-in it sets. */
25
+ export const LEAD_TIMES = {
26
+ in_15_minutes: { kind: "in", minutes: 15 },
27
+ in_1_hour: { kind: "in", minutes: 60 },
28
+ in_4_hours: { kind: "in", minutes: 240 },
29
+ tomorrow: { kind: "in", minutes: 24 * 60 },
30
+ every_hour: { kind: "every", minutes: 60 },
31
+ every_4_hours: { kind: "every", minutes: 240 },
32
+ every_day: { kind: "every", minutes: 24 * 60 },
33
+ };
34
+
35
+ const clock = (date) =>
36
+ `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
37
+ const shortDate = (date) =>
38
+ date.toLocaleDateString("en-US", { month: "short", day: "numeric" });
39
+ const plural = (count, unit) => `${count} ${unit}${count === 1 ? "" : "s"}`;
40
+ const minutesIn = (minutes) =>
41
+ minutes % 1440 === 0
42
+ ? plural(minutes / 1440, "day")
43
+ : minutes % 60 === 0
44
+ ? plural(minutes / 60, "hour")
45
+ : plural(minutes, "minute");
46
+
47
+ /**
48
+ * A cadence as the person or the lead gives it, checked and made exact, or { error }. Shapes: once { at } (a time),
49
+ * in { minutes } (once, that long from now), every { minutes }, daily { time: "HH:MM", days: [0-6] } on this Mac's clock.
50
+ */
51
+ export function cadenceOf(given, now = Date.now()) {
52
+ const kind = given?.kind;
53
+ if (kind === "in" || kind === "once") {
54
+ const at =
55
+ kind === "in"
56
+ ? now + Math.round(Number(given.minutes) * 60_000)
57
+ : Date.parse(given.at);
58
+ if (!Number.isFinite(at)) return { error: "give a time it should run" };
59
+ if (at <= now) return { error: "that time has already passed" };
60
+ return { kind: "once", at: new Date(at).toISOString() };
61
+ }
62
+ if (kind === "every") {
63
+ const minutes = Number(given.minutes);
64
+ return Number.isInteger(minutes) && minutes >= MIN_EVERY_MINUTES
65
+ ? { kind: "every", minutes }
66
+ : {
67
+ error: `a check-in repeats at most every ${MIN_EVERY_MINUTES} minutes`,
68
+ };
69
+ }
70
+ if (kind === "daily") {
71
+ const time = String(given.time || "");
72
+ const [hours, minutes] = time.split(":").map(Number);
73
+ if (
74
+ !/^\d{1,2}:\d{2}$/.test(time) ||
75
+ !(hours >= 0 && hours < 24 && minutes >= 0 && minutes < 60)
76
+ )
77
+ return { error: "give the time of day as HH:MM" };
78
+ const days = [
79
+ ...new Set(
80
+ (Array.isArray(given.days) && given.days.length
81
+ ? given.days
82
+ : [0, 1, 2, 3, 4, 5, 6]
83
+ ).map(Number)
84
+ ),
85
+ ].sort();
86
+ if (days.some((day) => !Number.isInteger(day) || day < 0 || day > 6))
87
+ return { error: "days are 0 (Sunday) to 6 (Saturday)" };
88
+ return {
89
+ kind: "daily",
90
+ time: `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}`,
91
+ days,
92
+ };
93
+ }
94
+ return {
95
+ error:
96
+ "say when: once at a time, in some minutes, every some minutes, or daily at a time",
97
+ };
98
+ }
99
+
100
+ /** The first run strictly after `after` (ms), or null when there is none. A repeat counts from `after`. */
101
+ export function nextRunAfter(cadence, after) {
102
+ if (cadence.kind === "once") {
103
+ const at = Date.parse(cadence.at);
104
+ return at > after ? at : null;
105
+ }
106
+ if (cadence.kind === "every") return after + cadence.minutes * 60_000;
107
+ const [hours, minutes] = cadence.time.split(":").map(Number);
108
+ const day = new Date(after);
109
+ for (let offset = 0; offset <= 7; offset++) {
110
+ const candidate = new Date(
111
+ day.getFullYear(),
112
+ day.getMonth(),
113
+ day.getDate() + offset,
114
+ hours,
115
+ minutes
116
+ );
117
+ if (
118
+ candidate.getTime() > after &&
119
+ cadence.days.includes(candidate.getDay())
120
+ )
121
+ return candidate.getTime();
122
+ }
123
+ return null;
124
+ }
125
+
126
+ /** A cadence in a few words: "once at 14:30 on Oct 17", "every 30 minutes", "weekdays at 09:00". */
127
+ export function describeCadence(cadence) {
128
+ if (cadence.kind === "once") {
129
+ const at = new Date(cadence.at);
130
+ return `once at ${clock(at)} on ${shortDate(at)}`;
131
+ }
132
+ if (cadence.kind === "every")
133
+ return `every ${minutesIn(cadence.minutes).replace(/^1 /, "")}`;
134
+ const days =
135
+ cadence.days.length === 7
136
+ ? "every day"
137
+ : cadence.days.join() === "1,2,3,4,5"
138
+ ? "weekdays"
139
+ : cadence.days.map((day) => DAY_NAMES[day]).join(", ");
140
+ return `${days} at ${cadence.time}`;
141
+ }
142
+
143
+ /**
144
+ * The relay's check-ins, kept in the store. `fire(schedule, { late })` is one run; `late` says when it was due, in
145
+ * words, when it runs later than that.
146
+ */
147
+ export function createSchedules({
148
+ store,
149
+ fire,
150
+ log = () => {},
151
+ now = () => Date.now(),
152
+ }) {
153
+ const list = () => {
154
+ try {
155
+ return JSON.parse(store.meta("schedules") || "[]");
156
+ } catch {
157
+ return [];
158
+ }
159
+ };
160
+ const save = (schedules) =>
161
+ store.meta("schedules", JSON.stringify(schedules));
162
+ const update = (id, change) =>
163
+ save(
164
+ list().map((schedule) =>
165
+ schedule.id === id ? { ...schedule, ...change } : schedule
166
+ )
167
+ );
168
+ const ended = (why) => ({ state: "ended", endedWhy: why, nextAt: null });
169
+ const shown = (schedule) => ({
170
+ ...schedule,
171
+ when: describeCadence(schedule.cadence),
172
+ });
173
+ let timer = null,
174
+ soon = null;
175
+ // The next run sooner than the next poll gets a timer of its own, so it runs on time while the Mac is awake. A run held
176
+ // for a paused thread is left to the polls.
177
+ const armSoonest = () => {
178
+ clearTimeout(soon);
179
+ if (!timer) return;
180
+ const at = now();
181
+ const waits = list()
182
+ .filter((schedule) => schedule.state === "on")
183
+ .map((schedule) => Date.parse(schedule.nextAt) - at)
184
+ .filter((wait) => wait > 0 && wait < POLL_MS);
185
+ if (!waits.length) return;
186
+ soon = setTimeout(tick, Math.min(...waits));
187
+ soon.unref?.();
188
+ };
189
+
190
+ // One pass over every check-in: run what is due, once each however many runs it missed.
191
+ const tick = () => {
192
+ const at = now();
193
+ for (const schedule of list()) {
194
+ if (schedule.state !== "on" || Date.parse(schedule.nextAt) > at) continue;
195
+ const thread = store.getTask(schedule.threadId);
196
+ if (!thread || !["open", "paused"].includes(thread.status)) {
197
+ update(schedule.id, ended("the thread ended"));
198
+ continue;
199
+ }
200
+ if (thread.status === "paused") {
201
+ if (schedule.cadence.kind !== "once")
202
+ update(schedule.id, {
203
+ nextAt: new Date(nextRunAfter(schedule.cadence, at)).toISOString(),
204
+ skipped: (schedule.skipped ?? 0) + 1,
205
+ });
206
+ continue;
207
+ }
208
+ const dueAt = Date.parse(schedule.nextAt);
209
+ const runs = schedule.runs + 1;
210
+ const next = nextRunAfter(schedule.cadence, at);
211
+ const done =
212
+ next === null
213
+ ? "it ran"
214
+ : schedule.maxRuns && runs >= schedule.maxRuns
215
+ ? `it ran ${plural(runs, "time")}`
216
+ : schedule.endsAt && next > Date.parse(schedule.endsAt)
217
+ ? "its end date passed"
218
+ : null;
219
+ // Saved before the run, so a run that throws is not run again on the next poll.
220
+ update(schedule.id, {
221
+ runs,
222
+ lastRanAt: new Date(at).toISOString(),
223
+ ...(done ? ended(done) : { nextAt: new Date(next).toISOString() }),
224
+ });
225
+ try {
226
+ fire(shown({ ...schedule, runs }), {
227
+ late:
228
+ at - dueAt > LATE_AFTER_MS
229
+ ? `${clock(new Date(dueAt))} on ${shortDate(new Date(dueAt))}`
230
+ : null,
231
+ });
232
+ } catch (error) {
233
+ log(`check-in ${schedule.id}: ${error.message}`);
234
+ }
235
+ }
236
+ armSoonest();
237
+ };
238
+
239
+ /** Every check-in on a thread (or every thread's), with when it runs in words; ended ones only when asked. */
240
+ const listed = ({ threadId = null, all = false } = {}) =>
241
+ list()
242
+ .filter(
243
+ (schedule) =>
244
+ (!threadId || schedule.threadId === threadId) &&
245
+ (all || schedule.state === "on")
246
+ )
247
+ .map(shown);
248
+
249
+ /**
250
+ * A new check-in, from the person (`by` "user") or the thread's lead ("lead"). `agents`: who it wakes; none wakes the
251
+ * lead. `maxRuns` and `endsAt` end a repeating one.
252
+ */
253
+ const add = ({
254
+ threadId,
255
+ what,
256
+ agents = [],
257
+ cadence: given,
258
+ by = "user",
259
+ maxRuns = null,
260
+ endsAt = null,
261
+ }) => {
262
+ const thread = store.getTask(threadId);
263
+ if (!thread || thread.kind !== "goal")
264
+ return { ok: false, error: "no such thread" };
265
+ if (!["open", "paused"].includes(thread.status))
266
+ return { ok: false, error: `the thread is ${thread.status}` };
267
+ const words = String(what || "").trim();
268
+ if (!words) return { ok: false, error: "say what the check-in is for" };
269
+ const cadence = cadenceOf(given, now());
270
+ if (cadence.error) return { ok: false, error: cadence.error };
271
+ const runs = Number(maxRuns);
272
+ if (maxRuns !== null && !(Number.isInteger(runs) && runs > 0))
273
+ return {
274
+ ok: false,
275
+ error: "the number of runs is a whole number above 0",
276
+ };
277
+ const until = endsAt === null ? null : Date.parse(endsAt);
278
+ if (until !== null && !(until > now()))
279
+ return { ok: false, error: "the end date has already passed" };
280
+ const first = nextRunAfter(cadence, now());
281
+ if (first === null || (until !== null && first > until))
282
+ return { ok: false, error: "it would never run" };
283
+ const schedule = {
284
+ id: randomUUID(),
285
+ threadId,
286
+ what: words.slice(0, WHAT_CHARS),
287
+ agents: [...new Set(agents.map(String))],
288
+ cadence,
289
+ by: by === "user" ? "user" : "lead",
290
+ maxRuns: maxRuns === null ? null : runs,
291
+ endsAt: until === null ? null : new Date(until).toISOString(),
292
+ state: "on",
293
+ runs: 0,
294
+ nextAt: new Date(first).toISOString(),
295
+ lastRanAt: null,
296
+ createdAt: new Date(now()).toISOString(),
297
+ };
298
+ save([...list(), schedule]);
299
+ armSoonest();
300
+ return { ok: true, schedule: shown(schedule) };
301
+ };
302
+
303
+ return {
304
+ list: listed,
305
+ add,
306
+ /** The lead's check-in, at one of LEAD_TIMES; it keeps one per thread, so a second waits for the first to end. */
307
+ addForLead(threadId, time, what) {
308
+ const given = LEAD_TIMES[time];
309
+ if (!given) return { ok: false, error: `no such time: ${time}` };
310
+ if (
311
+ list().some(
312
+ (schedule) =>
313
+ schedule.threadId === threadId &&
314
+ schedule.by === "lead" &&
315
+ schedule.state === "on"
316
+ )
317
+ )
318
+ return { ok: false, error: "the lead already has a check-in here" };
319
+ return add({
320
+ threadId,
321
+ what,
322
+ cadence: given,
323
+ by: "lead",
324
+ maxRuns: given.kind === "every" ? LEAD_MAX_RUNS : null,
325
+ });
326
+ },
327
+ /** Ends a check-in, the person's or the lead's; only the person ends one. */
328
+ remove(id) {
329
+ const schedule = list().find((entry) => entry.id === id);
330
+ if (!schedule || schedule.state !== "on")
331
+ return { ok: false, error: "no such check-in" };
332
+ update(id, ended("you removed it"));
333
+ return {
334
+ ok: true,
335
+ schedule: shown(list().find((entry) => entry.id === id)),
336
+ };
337
+ },
338
+ /** What the lead's round reads: the thread's check-ins in words, and who set each. */
339
+ view(threadId) {
340
+ return listed({ threadId }).map((schedule) => ({
341
+ what: schedule.what.slice(0, 500),
342
+ when: schedule.when,
343
+ by: schedule.by === "user" ? "person" : "lead",
344
+ next: schedule.nextAt,
345
+ }));
346
+ },
347
+ tick,
348
+ /** Starts the poll, running at once whatever came due while the relay was off. */
349
+ start() {
350
+ if (timer) return;
351
+ tick();
352
+ timer = setInterval(tick, POLL_MS);
353
+ timer.unref?.();
354
+ },
355
+ stop() {
356
+ clearInterval(timer);
357
+ clearTimeout(soon);
358
+ timer = null;
359
+ },
360
+ };
361
+ }