@usepipa/pipa 0.4.2 → 0.5.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.
@@ -0,0 +1,628 @@
1
+ import { constants } from "node:fs";
2
+ import { link, lstat, mkdir, open, readFile, readdir, rm, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ import { isDeepStrictEqual } from "node:util";
6
+ import { DateTime, IANAZone } from "luxon";
7
+ import { pipaPaths, writePrivateJson } from "./state.mjs";
8
+
9
+ const FREQUENCIES = new Set(["minutes", "hours", "daily", "weekly"]);
10
+ const STATUSES = new Set(["active", "inactive", "completed"]);
11
+ const RUN_STATUSES = new Set(["succeeded", "failed", "aborted", "denied"]);
12
+
13
+ export function calculateNextRunAt(schedule, timezone, strictAfter, anchor = strictAfter) {
14
+ validateTimezone(timezone);
15
+ const after = parseTimestamp(strictAfter, "strict-future boundary");
16
+ const start = parseTimestamp(anchor, "schedule anchor");
17
+ assertCanonicalSchedule(schedule, timezone, start);
18
+
19
+ if (schedule?.type === "once") {
20
+ const at = parseTimestamp(schedule.at, "once timestamp");
21
+ return at > after ? canonicalIso(at) : null;
22
+ }
23
+ if (schedule.frequency === "minutes" || schedule.frequency === "hours") {
24
+ const milliseconds = schedule.interval * (schedule.frequency === "minutes" ? 60_000 : 3_600_000);
25
+ const steps = Math.max(1, Math.floor((after.toMillis() - start.toMillis()) / milliseconds) + 1);
26
+ const next = DateTime.fromMillis(start.toMillis() + steps * milliseconds, { zone: "utc" });
27
+ return isWithinUntil(next, schedule.until, timezone) ? canonicalIso(next) : null;
28
+ }
29
+
30
+ const afterLocal = after.setZone(timezone);
31
+ const anchorLocal = start.setZone(timezone);
32
+ if (schedule.frequency === "daily") {
33
+ const anchorDay = anchorLocal.startOf("day");
34
+ const afterDay = afterLocal.startOf("day");
35
+ const elapsed = Math.round(afterDay.diff(anchorDay, "days").days);
36
+ const offset = modulo(-elapsed, schedule.interval);
37
+ for (const day of [afterDay.plus({ days: offset }), afterDay.plus({ days: offset + schedule.interval })]) {
38
+ const next = firstTimeAfter(day, schedule.times, after);
39
+ if (next && isWithinUntil(next, schedule.until, timezone)) return canonicalIso(next);
40
+ }
41
+ return null;
42
+ }
43
+
44
+ const anchorWeek = anchorLocal.startOf("day").minus({ days: anchorLocal.weekday - 1 });
45
+ const afterWeek = afterLocal.startOf("day").minus({ days: afterLocal.weekday - 1 });
46
+ const elapsedWeeks = Math.round(afterWeek.diff(anchorWeek, "weeks").weeks);
47
+ const weekOffset = modulo(-elapsedWeeks, schedule.interval);
48
+ for (const week of [afterWeek.plus({ weeks: weekOffset }), afterWeek.plus({ weeks: weekOffset + schedule.interval })]) {
49
+ for (const weekday of schedule.weekdays) {
50
+ const next = firstTimeAfter(week.plus({ days: weekday - 1 }), schedule.times, after);
51
+ if (next && isWithinUntil(next, schedule.until, timezone)) return canonicalIso(next);
52
+ }
53
+ }
54
+ return null;
55
+ }
56
+
57
+ export function normalizeRoutine(input, now = DateTime.utc().toISO()) {
58
+ if (!input || typeof input !== "object" || Array.isArray(input)) invalid("must be an object");
59
+ const clock = parseTimestamp(now, "clock");
60
+ const id = requiredString(input.id, "id");
61
+ if (typeof input.prompt !== "string" || !input.prompt.trim()) invalid("prompt is empty");
62
+ validateTimezone(input.timezone);
63
+ const schedule = normalizeSchedule(input.schedule, input.timezone, clock);
64
+ const destination = normalizeDestination(input.destination);
65
+ const status = input.status ?? "active";
66
+ if (!STATUSES.has(status)) invalid("status is unsupported");
67
+ const createdAt = input.createdAt === undefined ? canonicalIso(clock) : canonicalTimestamp(input.createdAt, "createdAt");
68
+ const updatedAt = input.updatedAt === undefined ? canonicalIso(clock) : canonicalTimestamp(input.updatedAt, "updatedAt");
69
+ const runRequestedAt = input.runRequestedAt == null ? null : canonicalTimestamp(input.runRequestedAt, "runRequestedAt");
70
+ const lastRun = input.lastRun == null ? null : normalizeLastRun(input.lastRun);
71
+ const calculated = status === "active" ? calculateNextRunAt(schedule, input.timezone, canonicalIso(clock), createdAt) : null;
72
+ if (status === "active" && calculated === null) invalid("active schedule has no future occurrence");
73
+
74
+ return {
75
+ id,
76
+ prompt: input.prompt,
77
+ schedule,
78
+ timezone: input.timezone,
79
+ destination,
80
+ status,
81
+ nextRunAt: calculated,
82
+ runRequestedAt,
83
+ createdAt,
84
+ updatedAt,
85
+ lastRun,
86
+ };
87
+ }
88
+
89
+ export async function loadRoutineState(file = pipaPaths().routines) {
90
+ let handle;
91
+ try {
92
+ const info = await lstat(file);
93
+ if (!info.isFile()) throw new Error("routine state must be a regular file");
94
+ handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
95
+ const opened = await handle.stat();
96
+ if (!opened.isFile()) throw new Error("routine state must be a regular file");
97
+ const state = JSON.parse(await handle.readFile("utf8"));
98
+ validateRoutineState(state);
99
+ return state;
100
+ } catch (error) {
101
+ if (error?.code === "ENOENT") return { version: 1, routines: [] };
102
+ throw new Error(`Could not read Pipa routines: ${error.message}`);
103
+ } finally {
104
+ await handle?.close();
105
+ }
106
+ }
107
+
108
+ export async function acquireRoutineMutationLock(file = pipaPaths().routinesLock, options = {}) {
109
+ const timeoutMs = options.timeoutMs ?? 2_000;
110
+ const retryMs = options.retryMs ?? 10;
111
+ const token = randomUUID();
112
+ const startedAt = Date.now();
113
+ await mkdir(file, { recursive: true, mode: 0o700 });
114
+ const ticket = path.join(file, `${process.pid}-${token}.json`);
115
+ const temporary = `${ticket}.tmp`;
116
+ const createdAt = new Date().toISOString();
117
+ await writeFile(temporary, JSON.stringify({ token, pid: process.pid, createdAt, choosing: true, number: 0 }), { mode: 0o600 });
118
+ try {
119
+ await link(temporary, ticket);
120
+ } finally {
121
+ await rm(temporary, { force: true });
122
+ }
123
+ let number;
124
+ try {
125
+ const existing = await readLockTickets(file);
126
+ number = Math.max(0, ...existing.map((entry) => entry.owner?.number ?? 0)) + 1;
127
+ await writeFile(ticket, JSON.stringify({ token, pid: process.pid, createdAt, choosing: false, number }));
128
+ while (true) {
129
+ let blocked = false;
130
+ for (const entry of await readLockTickets(file)) {
131
+ if (entry.owner?.token === token) continue;
132
+ if (!entry.owner) {
133
+ if (entry.pid && !isRunning(entry.pid)) await rm(entry.file, { force: true });
134
+ else blocked = true;
135
+ continue;
136
+ }
137
+ if (!isRunning(entry.owner.pid)) {
138
+ await rm(entry.file, { force: true });
139
+ continue;
140
+ }
141
+ if (entry.owner.choosing || entry.owner.number < number || (entry.owner.number === number && entry.owner.token < token)) blocked = true;
142
+ }
143
+ if (!blocked) break;
144
+ if (Date.now() - startedAt >= timeoutMs) throw new Error("Routine mutation lock timed out.");
145
+ await new Promise((resolve) => setTimeout(resolve, retryMs));
146
+ }
147
+ } catch (error) {
148
+ await rm(ticket, { force: true });
149
+ throw error;
150
+ }
151
+
152
+ let released = false;
153
+ return async () => {
154
+ if (released) return;
155
+ released = true;
156
+ const owner = await readLock(ticket);
157
+ if (owner?.token === token) await rm(ticket, { force: true });
158
+ };
159
+ }
160
+
161
+ export async function mutateRoutineState(mutator, paths = pipaPaths(), options = {}) {
162
+ if (typeof mutator !== "function") throw new TypeError("Routine mutator must be a function.");
163
+ const release = await acquireRoutineMutationLock(paths.routinesLock, options);
164
+ try {
165
+ const state = await loadRoutineState(paths.routines);
166
+ const result = mutator(state);
167
+ if (result && typeof result.then === "function") throw new TypeError("Routine mutator must be synchronous.");
168
+ if (result === false) return state;
169
+ validateRoutineState(state);
170
+ await writePrivateJson(paths.routines, state);
171
+ return state;
172
+ } finally {
173
+ await release();
174
+ }
175
+ }
176
+
177
+ export async function requestRoutineRun(id, now = DateTime.utc().toISO(), paths = pipaPaths()) {
178
+ let requested;
179
+ await mutateRoutineState((state) => {
180
+ const routine = state.routines.find((item) => item.id === id);
181
+ if (!routine) throw new Error(`Routine not found: ${id}`);
182
+ const clock = parseTimestamp(now, "clock");
183
+ const previous = routine.runRequestedAt == null ? Number.NEGATIVE_INFINITY : parseTimestamp(routine.runRequestedAt, "runRequestedAt").toMillis();
184
+ routine.runRequestedAt = canonicalIso(DateTime.fromMillis(Math.max(clock.toMillis(), previous + 1), { zone: "utc" }));
185
+ routine.updatedAt = canonicalIso(clock);
186
+ requested = structuredClone(routine);
187
+ }, paths);
188
+ return requested;
189
+ }
190
+
191
+ export function assertRoutineDestinationAllowed(destination, allowedChannelIds = []) {
192
+ const normalized = normalizeDestination(destination);
193
+ if (!/^[CG][A-Z0-9]+$/u.test(normalized.channelId)) invalid("destination channelId must be a concrete Slack channel ID");
194
+ if (normalized.threadTs !== null && !/^\d+\.\d+$/u.test(normalized.threadTs)) invalid("destination threadTs is invalid");
195
+ if (allowedChannelIds.length > 0 && !allowedChannelIds.includes(normalized.channelId)) invalid("destination channel is not allowed");
196
+ return normalized;
197
+ }
198
+
199
+ export async function createRoutine(input, options = {}) {
200
+ const now = options.now ?? DateTime.utc().toISO();
201
+ const paths = options.paths ?? pipaPaths();
202
+ const routine = normalizeRoutine(input, now);
203
+ assertRoutineDestinationAllowed(routine.destination, options.allowedChannelIds);
204
+ if (options.preview) return routine;
205
+ await mutateRoutineState((state) => {
206
+ if (state.routines.some((item) => item.id === routine.id)) throw new Error(`Routine already exists: ${routine.id}`);
207
+ state.routines.push(routine);
208
+ }, paths);
209
+ return routine;
210
+ }
211
+
212
+ export async function editRoutine(id, changes, options = {}) {
213
+ const now = options.now ?? DateTime.utc().toISO();
214
+ const paths = options.paths ?? pipaPaths();
215
+ let edited;
216
+ await mutateRoutineState((state) => {
217
+ const index = state.routines.findIndex((item) => item.id === id);
218
+ if (index === -1) throw new Error(`Routine not found: ${id}`);
219
+ const current = state.routines[index];
220
+ const mutable = new Set(["prompt", "schedule", "timezone", "destination", "status"]);
221
+ if (Object.keys(changes).some((key) => !mutable.has(key))) invalid("edit contains immutable fields");
222
+ const candidate = {
223
+ ...current,
224
+ prompt: changes.prompt ?? current.prompt,
225
+ schedule: changes.schedule ?? current.schedule,
226
+ timezone: changes.timezone ?? current.timezone,
227
+ status: changes.status ?? current.status,
228
+ destination: changes.destination ? { ...current.destination, ...changes.destination } : current.destination,
229
+ updatedAt: now,
230
+ };
231
+ const lifecycleUnchanged = changes.schedule === undefined && changes.timezone === undefined && changes.status === undefined;
232
+ edited = lifecycleUnchanged
233
+ ? { ...normalizeRoutine({ ...candidate, status: "inactive" }, now), status: current.status, nextRunAt: current.nextRunAt }
234
+ : normalizeRoutine(candidate, now);
235
+ assertRoutineDestinationAllowed(edited.destination, options.allowedChannelIds);
236
+ state.routines[index] = edited;
237
+ }, paths);
238
+ return edited;
239
+ }
240
+
241
+ export async function deleteRoutine(id, paths = pipaPaths()) {
242
+ await mutateRoutineState((state) => {
243
+ const index = state.routines.findIndex((item) => item.id === id);
244
+ if (index === -1) throw new Error(`Routine not found: ${id}`);
245
+ state.routines.splice(index, 1);
246
+ }, paths);
247
+ }
248
+
249
+ export function reconcileRoutineState(input, now = DateTime.utc().toISO()) {
250
+ validateRoutineState(input);
251
+ const state = structuredClone(input);
252
+ const clock = parseTimestamp(now, "clock");
253
+ const clockIso = canonicalIso(clock);
254
+ for (const routine of state.routines) {
255
+ if (routine.status !== "active") {
256
+ routine.nextRunAt = null;
257
+ continue;
258
+ }
259
+ if (parseTimestamp(routine.nextRunAt, "nextRunAt") > clock) continue;
260
+ if (routine.schedule.type === "once") {
261
+ routine.status = "inactive";
262
+ routine.nextRunAt = null;
263
+ routine.updatedAt = clockIso;
264
+ continue;
265
+ }
266
+ const next = calculateNextRunAt(routine.schedule, routine.timezone, clockIso, routine.nextRunAt);
267
+ routine.nextRunAt = next;
268
+ routine.updatedAt = clockIso;
269
+ if (next === null) routine.status = "completed";
270
+ }
271
+ validateRoutineState(state);
272
+ return state;
273
+ }
274
+
275
+ export async function reconcileRoutines(now = DateTime.utc().toISO(), paths = pipaPaths()) {
276
+ return mutateRoutineState((state) => {
277
+ state.routines = reconcileRoutineState(state, now).routines;
278
+ }, paths);
279
+ }
280
+
281
+ export async function mergeRoutineRunOutcome(snapshot, outcome, completedAt = DateTime.utc().toISO(), paths = pipaPaths()) {
282
+ validateOutcome(snapshot, outcome);
283
+ const completed = canonicalTimestamp(completedAt, "completedAt");
284
+ let merged = null;
285
+ await mutateRoutineState((state) => {
286
+ const routine = state.routines.find((item) => item.id === snapshot.id);
287
+ if (!routine) return false;
288
+ const denialStillOwned = (snapshot.status === undefined || routine.status === snapshot.status)
289
+ && (snapshot.destination === undefined || JSON.stringify(routine.destination) === JSON.stringify(snapshot.destination));
290
+
291
+ if (snapshot.trigger === "run-now") {
292
+ if (routine.runRequestedAt !== snapshot.runRequestedAt) return false;
293
+ routine.runRequestedAt = null;
294
+ } else {
295
+ const ownsOccurrence = routine.status === "active"
296
+ && routine.nextRunAt === snapshot.occurrenceAt
297
+ && JSON.stringify(routine.schedule) === JSON.stringify(snapshot.schedule);
298
+ if (!ownsOccurrence) return false;
299
+ if (routine.schedule.type === "once") {
300
+ routine.status = "completed";
301
+ routine.nextRunAt = null;
302
+ } else {
303
+ routine.nextRunAt = calculateNextRunAt(routine.schedule, routine.timezone, completed, routine.createdAt);
304
+ if (routine.nextRunAt === null) routine.status = "completed";
305
+ }
306
+ }
307
+ if (outcome.status === "denied" && denialStillOwned) {
308
+ routine.status = "inactive";
309
+ routine.nextRunAt = null;
310
+ }
311
+ routine.lastRun = {
312
+ trigger: snapshot.trigger,
313
+ occurrenceAt: canonicalTimestamp(snapshot.occurrenceAt, "occurrenceAt"),
314
+ completedAt: completed,
315
+ status: outcome.status,
316
+ errorCode: outcome.errorCode ?? null,
317
+ errorSummary: outcome.errorSummary ?? null,
318
+ };
319
+ routine.updatedAt = completed;
320
+ merged = structuredClone(routine);
321
+ }, paths);
322
+ return merged;
323
+ }
324
+
325
+ export function createRoutineScheduler(options) {
326
+ const paths = options.paths ?? pipaPaths();
327
+ const intervalMs = options.intervalMs ?? 30_000;
328
+ const active = new Map();
329
+ const blocked = new Set();
330
+ let timer;
331
+ let ticking = false;
332
+ let currentTick = Promise.resolve();
333
+ let started = false;
334
+ let stopped = false;
335
+ let stopReason;
336
+
337
+ function tick() {
338
+ if (stopped || ticking) return currentTick;
339
+ ticking = true;
340
+ currentTick = runTick().finally(() => { ticking = false; });
341
+ return currentTick;
342
+ }
343
+
344
+ async function runTick() {
345
+ const now = options.now?.() ?? DateTime.utc().toISO();
346
+ const state = await loadRoutineState(paths.routines);
347
+ if (stopped) return;
348
+ for (const [id, entry] of active) {
349
+ const current = state.routines.find((routine) => routine.id === id);
350
+ if (!current || (entry.snapshot.status === "active" && current.status !== "active")) {
351
+ entry.controller.abort(new Error("Routine was deactivated or deleted."));
352
+ if (entry.sessionId) await Promise.resolve(options.abortTurn?.(entry.sessionId, entry.controller.signal.reason)).catch(() => undefined);
353
+ }
354
+ }
355
+ for (const routine of state.routines) {
356
+ if (stopped) break;
357
+ if (active.has(routine.id) || blocked.has(routine.id)) continue;
358
+ const scheduled = routine.status === "active" && routine.nextRunAt !== null && parseTimestamp(routine.nextRunAt, "nextRunAt") <= parseTimestamp(now, "clock");
359
+ if (!scheduled && routine.runRequestedAt === null) continue;
360
+ const trigger = scheduled ? "scheduled" : "run-now";
361
+ const occurrenceAt = scheduled ? routine.nextRunAt : routine.runRequestedAt;
362
+ const snapshot = structuredClone({ ...routine, trigger, occurrenceAt });
363
+ const entry = { snapshot, controller: new AbortController(), sessionId: null };
364
+ active.set(routine.id, entry);
365
+ entry.done = run(entry);
366
+ void entry.done.catch(options.onError ?? (() => undefined));
367
+ }
368
+ }
369
+
370
+ async function run(entry) {
371
+ let outcome;
372
+ try {
373
+ outcome = await options.execute(entry.snapshot, {
374
+ signal: entry.controller.signal,
375
+ onSession(sessionId) { entry.sessionId = sessionId; },
376
+ async abort(reason) {
377
+ entry.controller.abort(reason);
378
+ if (entry.sessionId) await Promise.resolve(options.abortTurn?.(entry.sessionId, reason)).catch(() => undefined);
379
+ },
380
+ });
381
+ outcome ??= { status: "succeeded" };
382
+ } catch {
383
+ outcome = entry.controller.signal.aborted
384
+ ? { status: "aborted", errorCode: "aborted", errorSummary: "Routine execution was aborted." }
385
+ : { status: "failed", errorCode: "executor_failed", errorSummary: "Routine execution failed." };
386
+ }
387
+ try {
388
+ if (!stopped) await (options.mergeOutcome ?? mergeRoutineRunOutcome)(entry.snapshot, outcome, options.now?.() ?? DateTime.utc().toISO(), paths);
389
+ } catch (error) {
390
+ blocked.add(entry.snapshot.id);
391
+ throw error;
392
+ } finally {
393
+ if (active.get(entry.snapshot.id) === entry) active.delete(entry.snapshot.id);
394
+ }
395
+ }
396
+
397
+ return {
398
+ async start() {
399
+ if (started) throw new Error("Routine scheduler already started.");
400
+ started = true;
401
+ if (stopped) throw stopReason;
402
+ await reconcileRoutines(options.now?.() ?? DateTime.utc().toISO(), paths);
403
+ await tick();
404
+ if (stopped) return;
405
+ timer = (options.setInterval ?? setInterval)(() => { void tick().catch(options.onError ?? (() => undefined)); }, intervalMs);
406
+ timer?.unref?.();
407
+ },
408
+ tick,
409
+ stop(reason = new Error("Pipa stopped.")) {
410
+ if (stopped) return;
411
+ stopped = true;
412
+ stopReason = reason;
413
+ (options.clearInterval ?? clearInterval)(timer);
414
+ for (const entry of active.values()) {
415
+ entry.controller.abort(reason);
416
+ if (entry.sessionId) void Promise.resolve(options.abortTurn?.(entry.sessionId, reason)).catch(() => undefined);
417
+ }
418
+ },
419
+ async drain() {
420
+ await currentTick.catch(() => undefined);
421
+ while (active.size) await Promise.allSettled([...active.values()].map((entry) => entry.done));
422
+ },
423
+ };
424
+ }
425
+
426
+ function normalizeSchedule(schedule, timezone, clock, fail = invalid) {
427
+ if (!schedule || typeof schedule !== "object" || Array.isArray(schedule)) fail("schedule must be an object");
428
+ if (schedule.type === "once") return { type: "once", at: canonicalIso(parseTimestamp(schedule.at, "once timestamp", fail)) };
429
+ if (schedule.type !== "recurring" || !FREQUENCIES.has(schedule.frequency)) fail("schedule frequency is unsupported");
430
+ if (!Number.isSafeInteger(schedule.interval) || schedule.interval <= 0) fail("schedule interval must be a positive integer");
431
+ const until = schedule.until == null ? null : normalizeDate(schedule.until, fail);
432
+ const local = clock.setZone(timezone);
433
+ let times = schedule.times ?? [];
434
+ let weekdays = schedule.weekdays ?? [];
435
+ if (!Array.isArray(times) || !Array.isArray(weekdays)) fail("schedule times and weekdays must be lists");
436
+ if (schedule.frequency === "daily" || schedule.frequency === "weekly") {
437
+ if (times.length === 0) times = [local.toFormat("HH:mm")];
438
+ times = [...new Set(times.map((value) => normalizeTime(value, fail)))].sort();
439
+ } else if (times.length !== 0 || weekdays.length !== 0) {
440
+ fail("minute and hour schedules cannot have times or weekdays");
441
+ }
442
+ if (schedule.frequency === "weekly") {
443
+ if (weekdays.length === 0) weekdays = [local.weekday];
444
+ if (!weekdays.every((value) => Number.isInteger(value) && value >= 1 && value <= 7)) fail("weekdays must be integers from 1 to 7");
445
+ weekdays = [...new Set(weekdays)].sort((left, right) => left - right);
446
+ } else if (weekdays.length !== 0) {
447
+ fail("only weekly schedules can have weekdays");
448
+ }
449
+ return { type: "recurring", frequency: schedule.frequency, interval: schedule.interval, times, weekdays, until };
450
+ }
451
+
452
+ function validateRoutineState(state) {
453
+ if (!state || typeof state !== "object" || Array.isArray(state)) invalidState("must be an object");
454
+ requireKeys(state, ["version", "routines"], "state");
455
+ if (state.version !== 1) invalidState("unsupported version");
456
+ if (!Array.isArray(state.routines)) invalidState("routines must be a list");
457
+ const ids = new Set();
458
+ for (const routine of state.routines) {
459
+ validateCanonicalRoutine(routine);
460
+ if (ids.has(routine.id)) invalidState(`duplicate routine id: ${routine.id}`);
461
+ ids.add(routine.id);
462
+ }
463
+ }
464
+
465
+ function validateCanonicalRoutine(routine) {
466
+ if (!routine || typeof routine !== "object" || Array.isArray(routine)) invalidState("routine must be an object");
467
+ requireKeys(routine, ["id", "prompt", "schedule", "timezone", "destination", "status", "nextRunAt", "runRequestedAt", "createdAt", "updatedAt", "lastRun"], "routine");
468
+ requiredString(routine.id, "id", invalidState);
469
+ if (typeof routine.prompt !== "string" || !routine.prompt.trim()) invalidState("prompt is empty");
470
+ validateTimezone(routine.timezone, invalidState);
471
+ const createdAt = canonicalTimestamp(routine.createdAt, "createdAt", invalidState);
472
+ const updatedAt = canonicalTimestamp(routine.updatedAt, "updatedAt", invalidState);
473
+ assertCanonicalSchedule(routine.schedule, routine.timezone, parseTimestamp(createdAt, "createdAt", invalidState));
474
+ requireKeys(routine.destination, ["channelId", "threadTs"], "destination");
475
+ normalizeDestination(routine.destination, invalidState);
476
+ if (!STATUSES.has(routine.status)) invalidState("status is unsupported");
477
+ if (updatedAt < createdAt) invalidState("updatedAt cannot precede createdAt");
478
+ if (routine.runRequestedAt !== null) canonicalTimestamp(routine.runRequestedAt, "runRequestedAt", invalidState);
479
+ if (routine.status === "active") {
480
+ if (routine.nextRunAt === null) invalidState("active routine must have nextRunAt");
481
+ const next = canonicalTimestamp(routine.nextRunAt, "nextRunAt", invalidState);
482
+ const boundary = canonicalIso(parseTimestamp(next, "nextRunAt").minus({ milliseconds: 1 }));
483
+ if (calculateNextRunAt(routine.schedule, routine.timezone, boundary, createdAt) !== next) invalidState("nextRunAt is not a schedule occurrence");
484
+ } else if (routine.nextRunAt !== null) invalidState("inactive and completed routines cannot have nextRunAt");
485
+ if (routine.lastRun !== null) normalizeLastRun(routine.lastRun, invalidState);
486
+ }
487
+
488
+ function assertCanonicalSchedule(schedule, timezone, clock) {
489
+ if (!isDeepStrictEqual(schedule, normalizeSchedule(schedule, timezone, clock, invalidState))) {
490
+ invalidState("schedule is not canonical");
491
+ }
492
+ }
493
+
494
+ function normalizeLastRun(lastRun, fail = invalid) {
495
+ if (!lastRun || typeof lastRun !== "object" || Array.isArray(lastRun)) fail("lastRun must be an object");
496
+ requireKeys(lastRun, ["trigger", "occurrenceAt", "completedAt", "status", "errorCode", "errorSummary"], "lastRun", fail);
497
+ if (lastRun.trigger !== "scheduled" && lastRun.trigger !== "run-now") fail("lastRun trigger is unsupported");
498
+ if (!RUN_STATUSES.has(lastRun.status)) fail("lastRun status is unsupported");
499
+ const errorCode = lastRun.errorCode == null ? null : requiredString(lastRun.errorCode, "lastRun errorCode", fail);
500
+ const errorSummary = lastRun.errorSummary == null ? null : requiredString(lastRun.errorSummary, "lastRun errorSummary", fail);
501
+ if (errorCode?.length > 64 || errorSummary?.length > 500) fail("lastRun error is too long");
502
+ return {
503
+ trigger: lastRun.trigger,
504
+ occurrenceAt: canonicalTimestamp(lastRun.occurrenceAt, "lastRun occurrenceAt", fail),
505
+ completedAt: canonicalTimestamp(lastRun.completedAt, "lastRun completedAt", fail),
506
+ status: lastRun.status,
507
+ errorCode,
508
+ errorSummary,
509
+ };
510
+ }
511
+
512
+ function normalizeDestination(destination, fail = invalid) {
513
+ if (!destination || typeof destination !== "object" || Array.isArray(destination)) fail("destination must be an object");
514
+ const channelId = requiredString(destination.channelId, "destination channelId", fail);
515
+ const threadTs = destination.threadTs == null ? null : requiredString(destination.threadTs, "destination threadTs", fail);
516
+ return { channelId, threadTs };
517
+ }
518
+
519
+ function validateOutcome(snapshot, outcome) {
520
+ if (!snapshot || typeof snapshot !== "object" || Array.isArray(snapshot)) invalid("snapshot is invalid");
521
+ requiredString(snapshot.id, "snapshot id");
522
+ if (snapshot.trigger !== "scheduled" && snapshot.trigger !== "run-now") invalid("snapshot trigger is unsupported");
523
+ if (snapshot.trigger === "run-now" && snapshot.runRequestedAt !== snapshot.occurrenceAt) invalid("run-now marker must own its occurrence");
524
+ if (!outcome || !RUN_STATUSES.has(outcome.status)) invalid("outcome status is unsupported");
525
+ if (outcome.errorCode != null && (typeof outcome.errorCode !== "string" || outcome.errorCode.length > 64)) invalid("outcome error code is invalid");
526
+ if (outcome.errorSummary != null && (typeof outcome.errorSummary !== "string" || outcome.errorSummary.length > 500)) invalid("outcome error summary is invalid");
527
+ }
528
+
529
+ function firstTimeAfter(day, times, after) {
530
+ for (const time of times) {
531
+ const [hour, minute] = time.split(":").map(Number);
532
+ const resolved = DateTime.fromObject({ year: day.year, month: day.month, day: day.day, hour, minute }, { zone: day.zoneName });
533
+ if (!resolved.isValid) continue;
534
+ const candidate = resolved.getPossibleOffsets().sort((left, right) => left.toMillis() - right.toMillis())[0];
535
+ if (candidate > after) return candidate;
536
+ }
537
+ return null;
538
+ }
539
+
540
+ function isWithinUntil(value, until, timezone) {
541
+ return until === null || value.setZone(timezone).toISODate() <= until;
542
+ }
543
+
544
+ function normalizeTime(value, fail = invalidState) {
545
+ if (typeof value !== "string" || !/^(?:[01]\d|2[0-3]):[0-5]\d$/u.test(value)) fail("schedule time is invalid");
546
+ return value;
547
+ }
548
+
549
+ function normalizeDate(value, fail = invalid) {
550
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/u.test(value)) fail("until date is invalid");
551
+ const parsed = DateTime.fromISO(value, { zone: "utc" });
552
+ if (!parsed.isValid || parsed.toISODate() !== value) fail("until date is invalid");
553
+ return value;
554
+ }
555
+
556
+ function validateTimezone(value, fail = invalid) {
557
+ if (typeof value !== "string" || (value !== "UTC" && !value.includes("/")) || !IANAZone.isValidZone(value)) fail("timezone must be an IANA name");
558
+ }
559
+
560
+ function canonicalTimestamp(value, name, fail = invalid) {
561
+ const parsed = parseTimestamp(value, name, fail);
562
+ const canonical = canonicalIso(parsed);
563
+ if (value !== canonical) fail(`${name} must be canonical UTC ISO`);
564
+ return canonical;
565
+ }
566
+
567
+ function parseTimestamp(value, name, fail = invalid) {
568
+ if (typeof value !== "string") fail(`${name} is invalid`);
569
+ const parsed = DateTime.fromISO(value, { setZone: true });
570
+ if (!parsed.isValid) fail(`${name} is invalid`);
571
+ return parsed.toUTC();
572
+ }
573
+
574
+ function canonicalIso(value) {
575
+ return value.toUTC().toISO({ suppressMilliseconds: false, includeOffset: true });
576
+ }
577
+
578
+ function requiredString(value, name, fail = invalid) {
579
+ if (typeof value !== "string" || !value.trim()) fail(`${name} is missing`);
580
+ return value;
581
+ }
582
+
583
+ function requireKeys(value, expected, name, fail = invalidState) {
584
+ const keys = Object.keys(value).sort();
585
+ const canonical = [...expected].sort();
586
+ if (JSON.stringify(keys) !== JSON.stringify(canonical)) fail(`${name} has invalid fields`);
587
+ }
588
+
589
+ async function readLock(file) {
590
+ try {
591
+ const value = JSON.parse(await readFile(file, "utf8"));
592
+ if (typeof value.token !== "string" || !Number.isSafeInteger(value.pid) || typeof value.createdAt !== "string"
593
+ || typeof value.choosing !== "boolean" || !Number.isSafeInteger(value.number) || value.number < 0) return null;
594
+ return value;
595
+ } catch {
596
+ return null;
597
+ }
598
+ }
599
+
600
+ async function readLockTickets(directory) {
601
+ const entries = await readdir(directory, { withFileTypes: true });
602
+ return Promise.all(entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map(async (entry) => {
603
+ const file = path.join(directory, entry.name);
604
+ const pid = Number.parseInt(entry.name.split("-")[0], 10);
605
+ return { file, pid: Number.isSafeInteger(pid) ? pid : null, owner: await readLock(file) };
606
+ }));
607
+ }
608
+
609
+ function isRunning(pid) {
610
+ try {
611
+ process.kill(pid, 0);
612
+ return true;
613
+ } catch (error) {
614
+ return error?.code === "EPERM";
615
+ }
616
+ }
617
+
618
+ function modulo(value, divisor) {
619
+ return ((value % divisor) + divisor) % divisor;
620
+ }
621
+
622
+ function invalid(message) {
623
+ throw new Error(`Invalid routine: ${message}`);
624
+ }
625
+
626
+ function invalidState(message) {
627
+ throw new Error(`Invalid routine state: ${message}`);
628
+ }
package/src/state.mjs CHANGED
@@ -55,6 +55,8 @@ export function pipaPaths(home = process.env.PIPA_HOME || os.homedir()) {
55
55
  config: path.join(directory, "config.json"),
56
56
  manifest: path.join(directory, "slack-manifest.json"),
57
57
  lock: path.join(directory, "pipa.lock"),
58
+ routines: path.join(directory, "routines.json"),
59
+ routinesLock: path.join(directory, "routines.lock"),
58
60
  sessions: path.join(directory, "sessions.json"),
59
61
  };
60
62
  }
@@ -181,7 +183,7 @@ async function readJson(file, missingMessage) {
181
183
  }
182
184
  }
183
185
 
184
- async function writePrivateJson(file, value) {
186
+ export async function writePrivateJson(file, value) {
185
187
  await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
186
188
  const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
187
189
  try {