pi-odd-worktree 3.13.0 → 3.15.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,242 @@
1
+ 'use strict';
2
+ // The peak-schedule engine: when a provider is peak-priced, and when that answer changes.
3
+ //
4
+ // A provider comes from `lib/peak-providers.js` and carries the schedule: `windows` are half-open
5
+ // `[startHour, endHour)` pairs of hours in `zone`, `weekdaysOnly` drops Saturday and Sunday, and
6
+ // `zone` is the zone the provider publishes those hours in. DeepSeek publishes UTC hours, Anthropic
7
+ // publishes Pacific ones, and the difference is not cosmetic: 05:00-11:00 Pacific is 12:00-18:00 UTC
8
+ // under PDT and 13:00-19:00 UTC under PST, so the hours are read in the provider's own zone and the
9
+ // weekdays are the provider's own weekdays.
10
+ //
11
+ // Nothing here knows about DeepSeek or Claude by name; a provider added to the registry is answered
12
+ // with no change to this file. Nothing here reads a clock either: every function takes the instant
13
+ // it must reason about, so the panel and the row never disagree and the schedule is testable
14
+ // without freezing time.
15
+ //
16
+ // Converting a local wall hour to an instant needs the zone's offset AT THAT INSTANT, which is
17
+ // exactly what is unknown before the conversion: the two-pass correction below applies the offset
18
+ // in force at the candidate itself, which is why the answer survives a DST switch instead of
19
+ // landing an hour off.
20
+
21
+ const MS_PER_DAY = 86_400_000;
22
+ const MINUTE_MS = 60_000;
23
+
24
+ // How far ahead to look for the next transition, in local days. A Friday evening puts the next
25
+ // window three days out; the extra margin keeps the search correct without ever approximating the
26
+ // answer.
27
+ const CANDIDATE_DAYS = 10;
28
+
29
+ // One formatter per zone, built once: `Intl.DateTimeFormat` is the only zone database Node has,
30
+ // and building one per call would dominate a schedule that is recomputed on every boundary.
31
+ const PARTS_FORMATTERS = new Map();
32
+
33
+ /** The parts formatter for a zone, or `undefined` when the zone does not resolve. */
34
+ function partsFormatterFor(timeZone) {
35
+ const cached = PARTS_FORMATTERS.get(timeZone);
36
+ if (cached !== undefined) return cached;
37
+ let formatter;
38
+ try {
39
+ formatter = new Intl.DateTimeFormat('en-US', {
40
+ timeZone,
41
+ hourCycle: 'h23',
42
+ year: 'numeric',
43
+ month: '2-digit',
44
+ day: '2-digit',
45
+ hour: '2-digit',
46
+ minute: '2-digit',
47
+ second: '2-digit',
48
+ });
49
+ } catch {
50
+ formatter = null;
51
+ }
52
+ PARTS_FORMATTERS.set(timeZone, formatter);
53
+ return formatter;
54
+ }
55
+
56
+ /**
57
+ * The local calendar fields one instant reads in one zone. `hourCycle: 'h23'` matters: without it
58
+ * midnight can format as `24`, which would land a candidate a day out.
59
+ */
60
+ function localParts(ts, timeZone) {
61
+ const formatter = partsFormatterFor(timeZone);
62
+ if (!formatter) return undefined;
63
+ const fields = {};
64
+ for (const part of formatter.formatToParts(Math.floor(ts / 1000) * 1000)) {
65
+ if (part.type !== 'literal') fields[part.type] = Number(part.value);
66
+ }
67
+ return {
68
+ year: fields.year,
69
+ month: fields.month,
70
+ day: fields.day,
71
+ hour: fields.hour,
72
+ minute: fields.minute,
73
+ second: fields.second,
74
+ };
75
+ }
76
+
77
+ /** A provider this engine can schedule, or `undefined`: a malformed one is never reasoned about. */
78
+ function scheduledProvider(provider) {
79
+ if (provider === null || typeof provider !== 'object') return undefined;
80
+ if (typeof provider.zone !== 'string' || provider.zone.length === 0) return undefined;
81
+ if (!Array.isArray(provider.windows)) return undefined;
82
+ if (!partsFormatterFor(provider.zone)) return undefined;
83
+ return provider;
84
+ }
85
+
86
+ /** The offset of a zone at one instant, as `local wall clock - UTC`, in milliseconds. */
87
+ function zoneOffsetAt(ts, timeZone) {
88
+ const parts = localParts(ts, timeZone);
89
+ const wall = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);
90
+ return wall - Math.floor(ts / 1000) * 1000;
91
+ }
92
+
93
+ /**
94
+ * The instant at which one local wall hour starts in one zone: the two-pass offset correction. The
95
+ * first pass treats the wall clock as UTC, the second applies the offset in force at the instant
96
+ * the first pass landed on, so a wall hour on either side of a DST switch converts exactly.
97
+ */
98
+ function localHourInstant(timeZone, year, month, day, hour) {
99
+ const wall = Date.UTC(year, month - 1, day, hour, 0, 0);
100
+ const firstPass = wall - zoneOffsetAt(wall, timeZone);
101
+ return wall - zoneOffsetAt(firstPass, timeZone);
102
+ }
103
+
104
+ /** The provider's own weekday for a local calendar date. */
105
+ function isLocalWeekday({ year, month, day }) {
106
+ const weekday = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
107
+ return weekday !== 0 && weekday !== 6;
108
+ }
109
+
110
+ function inAnyWindow(windows, minute) {
111
+ return windows.some(([startHour, endHour]) => minute >= startHour * 60 && minute < endHour * 60);
112
+ }
113
+
114
+ /** The schedule predicate itself, evaluated at one instant in the provider's own zone. */
115
+ function isPeakInstant(provider, ts) {
116
+ if (provider.weekdaysOnly === true && !isLocalWeekday(localParts(ts, provider.zone))) return false;
117
+ const parts = localParts(ts, provider.zone);
118
+ return inAnyWindow(provider.windows, parts.hour * 60 + parts.minute);
119
+ }
120
+
121
+ /**
122
+ * Every instant that could be a transition: both edges of every window across the next ten LOCAL
123
+ * days of the provider's zone. Weekends produce candidates too; they are dropped by the transition
124
+ * test in `nextTransitionFor`, which is what keeps a Saturday 05:00 Pacific from being reported as
125
+ * a change.
126
+ */
127
+ function candidateInstants(provider, now) {
128
+ const today = localParts(now, provider.zone);
129
+ const instants = [];
130
+ for (let offset = 0; offset < CANDIDATE_DAYS; offset++) {
131
+ // Normalising through `Date.UTC` is what rolls the local date over a month or a year boundary.
132
+ const date = new Date(Date.UTC(today.year, today.month - 1, today.day + offset));
133
+ const year = date.getUTCFullYear();
134
+ const month = date.getUTCMonth() + 1;
135
+ const day = date.getUTCDate();
136
+ for (const [startHour, endHour] of provider.windows) {
137
+ instants.push(localHourInstant(provider.zone, year, month, day, startHour));
138
+ instants.push(localHourInstant(provider.zone, year, month, day, endHour));
139
+ }
140
+ }
141
+ return instants;
142
+ }
143
+
144
+ /**
145
+ * The next instant at which the schedule actually flips. A candidate counts only when the predicate
146
+ * disagrees across it by one millisecond, so the answer is the end of the current state whether that
147
+ * state is a peak window or an off-peak gap that spans a weekend.
148
+ */
149
+ function nextTransitionFor(provider, now) {
150
+ const scheduled = scheduledProvider(provider);
151
+ if (!scheduled || !Number.isFinite(now)) return 0;
152
+ let next = now + CANDIDATE_DAYS * MS_PER_DAY;
153
+ for (const instant of candidateInstants(scheduled, now)) {
154
+ if (instant <= now || instant >= next) continue;
155
+ if (isPeakInstant(scheduled, instant - 1) !== isPeakInstant(scheduled, instant)) next = instant;
156
+ }
157
+ return next;
158
+ }
159
+
160
+ /**
161
+ * Whether `now` falls in a provider's peak window, and when that answer changes. An instant or a
162
+ * provider that cannot be read is off-peak with no boundary (`until: 0`), never a throw: a schedule
163
+ * is drawn above a live editor and must not be able to break it.
164
+ */
165
+ function peakStateFor(provider, now) {
166
+ const scheduled = scheduledProvider(provider);
167
+ if (!scheduled || !Number.isFinite(now)) return { kind: 'off-peak', until: 0 };
168
+ const kind = isPeakInstant(scheduled, now) ? 'peak' : 'off-peak';
169
+ return { kind, until: nextTransitionFor(scheduled, now) };
170
+ }
171
+
172
+ /**
173
+ * The nearest boundary among several providers' states: the smallest `until` of the states that are
174
+ * peak. `Infinity` when nothing is peaking, so one timer can wait for the first window that closes
175
+ * instead of one timer per provider — which is what lets two rows appear and disappear together
176
+ * without polling between boundaries.
177
+ */
178
+ function earliestUntil(states) {
179
+ let earliest = Number.POSITIVE_INFINITY;
180
+ if (!Array.isArray(states)) return earliest;
181
+ for (const state of states) {
182
+ if (state === null || typeof state !== 'object' || state.kind !== 'peak') continue;
183
+ const until = state.until;
184
+ if (typeof until === 'number' && until < earliest) earliest = until;
185
+ }
186
+ return earliest;
187
+ }
188
+
189
+ /**
190
+ * A compact remaining time, in the same shape the shell uses for quota resets. Rounds up, so a live
191
+ * window never reads as already over.
192
+ */
193
+ function formatCountdown(milliseconds) {
194
+ if (!Number.isFinite(milliseconds) || milliseconds <= 0) return 'now';
195
+ const minutes = Math.ceil(milliseconds / MINUTE_MS);
196
+ if (minutes < 60) return `${minutes}m`;
197
+ const hours = Math.floor(minutes / 60);
198
+ const restMinutes = minutes % 60;
199
+ if (hours < 24) return restMinutes === 0 ? `${hours}hr` : `${hours}hr ${restMinutes}m`;
200
+ const days = Math.floor(hours / 24);
201
+ const restHours = hours % 24;
202
+ return restHours === 0 ? `${days}d` : `${days}d ${restHours}hr`;
203
+ }
204
+
205
+ /**
206
+ * The next transition as a local clock: `04:00` on the same local date, or `Mon 01:00` when the
207
+ * boundary falls on another one. The instant the schedule actually ends is printed, never a
208
+ * countdown. `timeZone` is optional so a test can pin the locale without freezing the machine's
209
+ * clock.
210
+ */
211
+ function formatBoundaryClock(until, now, timeZone) {
212
+ if (!Number.isFinite(until) || !Number.isFinite(now)) return 'now';
213
+ const boundary = new Date(until);
214
+ const clock = new Intl.DateTimeFormat('en-US', {
215
+ hour: '2-digit',
216
+ minute: '2-digit',
217
+ hour12: false,
218
+ timeZone,
219
+ }).format(boundary);
220
+ const localDate = (instant) =>
221
+ new Intl.DateTimeFormat('en-US', { year: 'numeric', month: '2-digit', day: '2-digit', timeZone }).format(instant);
222
+ if (localDate(boundary) === localDate(new Date(now))) return clock;
223
+ const weekday = new Intl.DateTimeFormat('en-US', { weekday: 'short', timeZone }).format(boundary);
224
+ return `${weekday} ${clock}`;
225
+ }
226
+
227
+ /**
228
+ * `peak 20m` or `off-peak 3hr 20m`: the state, then the time left in it, with no word between and no
229
+ * colour.
230
+ */
231
+ function formatPeakState(state, now) {
232
+ return `${state.kind} ${formatCountdown(state.until - now)}`;
233
+ }
234
+
235
+ module.exports = {
236
+ peakStateFor,
237
+ nextTransitionFor,
238
+ earliestUntil,
239
+ formatCountdown,
240
+ formatBoundaryClock,
241
+ formatPeakState,
242
+ };