@aiwayds/dsh-opentui 0.17.3 → 0.18.1

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,294 @@
1
+ // Cross-start failure memory for provision-opentui-profile.mjs.
2
+ //
3
+ // The provisioning script runs on every launch. When a plugin cannot be
4
+ // installed at its pin (the registry is missing the version, or the version
5
+ // that landed is not the pin) the old behaviour retried on every start
6
+ // forever, rewriting node_modules and slowing startup without bound. This
7
+ // module decides, purely, what happened last time and whether another retry
8
+ // is worth it.
9
+ //
10
+ // Nothing here touches the filesystem or spawns a process: the caller passes
11
+ // the state file's text in and writes the serialized result out. That keeps
12
+ // the retry policy testable without a real profile.
13
+ //
14
+ // Timestamps are always stored as ISO strings so the file is timezone-free
15
+ // and diff-friendly.
16
+
17
+ export const STATE_VERSION = 1
18
+ export const MAX_ATTEMPTS = 3
19
+ export const BACKOFF_MS = 600000 // 10 minutes
20
+ // A pin that has been failing for a full day gets a fresh round. Without this
21
+ // the attempt cap would skip a plugin forever: a registry that published the
22
+ // pinned version late, or a network outage, would look identical to a broken
23
+ // pin. The window is measured from firstFailedAt, not lastFailedAt, so a pin
24
+ // that fails once a day still resets on schedule.
25
+ export const RESET_AFTER_MS = 86_400_000 // 24 hours
26
+ export const MAX_ERROR_LENGTH = 200
27
+
28
+ const EPOCH_ISO = new Date(0).toISOString()
29
+
30
+ /** Coerce a Date | ISO string | epoch milliseconds value to milliseconds.
31
+ * Returns null when the value cannot be read as a point in time. */
32
+ function parseTimeMs(value) {
33
+ if (value instanceof Date) {
34
+ const ms = value.getTime()
35
+ return Number.isFinite(ms) ? ms : null
36
+ }
37
+ if (typeof value === 'number') return Number.isFinite(value) ? value : null
38
+ if (typeof value === 'string' && value.trim() !== '') {
39
+ const ms = Date.parse(value)
40
+ return Number.isFinite(ms) ? ms : null
41
+ }
42
+ return null
43
+ }
44
+
45
+ function toIso(value) {
46
+ const ms = parseTimeMs(value)
47
+ return ms === null ? null : new Date(ms).toISOString()
48
+ }
49
+
50
+ /** Failure text is logged on one line and must not grow the state file:
51
+ * newlines become spaces, and the result is capped at MAX_ERROR_LENGTH. */
52
+ function sanitizeError(error) {
53
+ const text = typeof error === 'string'
54
+ ? error
55
+ : error == null
56
+ ? ''
57
+ : String(error)
58
+ return text.replace(/[\r\n]+/g, ' ').slice(0, MAX_ERROR_LENGTH)
59
+ }
60
+
61
+ /** A stored entry is untrusted input (the file may be hand-edited or written
62
+ * by an older build), so re-validate on read. Anything malformed is dropped
63
+ * by the caller; the remaining entries still participate in the policy. */
64
+ function normalizeEntry(raw) {
65
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
66
+ const pin = typeof raw.pin === 'string' ? raw.pin.trim() : ''
67
+ if (pin === '') return null
68
+ const attempts = Math.floor(Number(raw.attempts))
69
+ if (!Number.isFinite(attempts) || attempts < 1) return null
70
+ const firstFailedAt = toIso(raw.firstFailedAt)
71
+ const lastFailedAt = toIso(raw.lastFailedAt)
72
+ if (firstFailedAt === null || lastFailedAt === null) return null
73
+ return {
74
+ pin,
75
+ attempts,
76
+ firstFailedAt,
77
+ lastFailedAt,
78
+ error: sanitizeError(raw.error),
79
+ }
80
+ }
81
+
82
+ /** Fresh, empty state. Always a new object so callers cannot share one. */
83
+ export function emptyState() {
84
+ return { version: STATE_VERSION, failures: {} }
85
+ }
86
+
87
+ /** Parse the state file's text. Returns null when the document is not a
88
+ * usable state at all; individual malformed failure entries are dropped so
89
+ * one bad row cannot disable retry tracking for every plugin. */
90
+ export function parseState(text) {
91
+ if (typeof text !== 'string' || text.trim() === '') return null
92
+ let raw
93
+ try {
94
+ raw = JSON.parse(text)
95
+ } catch {
96
+ return null
97
+ }
98
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
99
+ if (!raw.failures || typeof raw.failures !== 'object' || Array.isArray(raw.failures)) return null
100
+
101
+ const failures = {}
102
+ for (const [name, entry] of Object.entries(raw.failures)) {
103
+ if (typeof name !== 'string' || name === '') continue
104
+ const normalized = normalizeEntry(entry)
105
+ if (normalized) failures[name] = normalized
106
+ }
107
+ return { version: STATE_VERSION, failures }
108
+ }
109
+
110
+ /** Stable JSON for the state file: failure names sorted, fixed field order
111
+ * inside each entry, trailing newline. Two runs over the same state produce
112
+ * byte-identical output, so the file does not churn. */
113
+ export function serializeState(state) {
114
+ const source = state && typeof state === 'object' && state.failures && typeof state.failures === 'object'
115
+ ? state.failures
116
+ : {}
117
+ const failures = {}
118
+ for (const name of Object.keys(source).sort()) {
119
+ const entry = normalizeEntry(source[name])
120
+ if (entry) failures[name] = entry
121
+ }
122
+ return `${JSON.stringify({ version: STATE_VERSION, failures }, null, 2)}\n`
123
+ }
124
+
125
+ /** True when `firstFailedAt` is at least `resetAfterMs` before `now`.
126
+ * Exactly the window boundary counts as due: a failure recorded at T is
127
+ * "24 hours old" at T+24h, and the next attempt is a fresh round.
128
+ * Unreadable timestamps are never due (retry is the safe failure mode). */
129
+ function isResetDue({ now, firstFailedAt, resetAfterMs = RESET_AFTER_MS }) {
130
+ const nowMs = parseTimeMs(now)
131
+ if (nowMs === null) return false
132
+ const firstMs = parseTimeMs(firstFailedAt)
133
+ if (firstMs === null) return false
134
+ const window = Number.isFinite(Number(resetAfterMs)) ? Number(resetAfterMs) : RESET_AFTER_MS
135
+ return nowMs - firstMs >= window
136
+ }
137
+
138
+ /** Record a failed install attempt. Same pin: attempts grow and
139
+ * firstFailedAt is preserved. New pin: the failure history resets, because
140
+ * the previous failures said nothing about this pin. A pin that has been
141
+ * failing for RESET_AFTER_MS also starts a fresh round (attempts back to 1,
142
+ * firstFailedAt moved to now) — the pin deserves another chance after a day.
143
+ * Returns a new state. */
144
+ export function recordFailure({ state, name, pin, now, error } = {}) {
145
+ const base = state && typeof state === 'object' && state.failures && typeof state.failures === 'object'
146
+ ? state
147
+ : emptyState()
148
+ const failures = { ...base.failures }
149
+ const previous = normalizeEntry(failures[name])
150
+ const resolvedPin = pin == null ? '' : String(pin)
151
+ const at = toIso(now) ?? EPOCH_ISO
152
+ const previousMatches = previous !== null && previous.pin === resolvedPin
153
+ const freshRound = previousMatches && isResetDue({ now, firstFailedAt: previous.firstFailedAt })
154
+ const samePin = previousMatches && !freshRound
155
+
156
+ failures[name] = {
157
+ pin: resolvedPin,
158
+ attempts: samePin ? previous.attempts + 1 : 1,
159
+ firstFailedAt: samePin ? previous.firstFailedAt : at,
160
+ lastFailedAt: at,
161
+ error: sanitizeError(error),
162
+ }
163
+ return { version: STATE_VERSION, failures }
164
+ }
165
+
166
+ /** Clear the failure entry for `name`. `pin` is intentionally unused: a
167
+ * successful install means there is nothing left to retry, whatever pin the
168
+ * entry recorded. Returns a new state. */
169
+ export function recordSuccess({ state, name } = {}) {
170
+ const base = state && typeof state === 'object' && state.failures && typeof state.failures === 'object'
171
+ ? state
172
+ : emptyState()
173
+ const failures = { ...base.failures }
174
+ delete failures[name]
175
+ return { version: STATE_VERSION, failures }
176
+ }
177
+
178
+ /**
179
+ * Record ONE launch's install outcomes under a SINGLE timestamp.
180
+ *
181
+ * The timestamp is chosen by the caller at the moment the batch FINISHED
182
+ * (`new Date().toISOString()` after the last `dsh plugin add` returned), never
183
+ * at process start. Provisioning can spend minutes installing, and the backoff
184
+ * window is measured from `lastFailedAt`: stamping a 9-minute failing batch
185
+ * with the launch time leaves 1 minute of the 10-minute window instead of 10.
186
+ * One timestamp for the whole batch (rather than one per package) keeps the
187
+ * entries of a launch identical; the difference between per-package calls
188
+ * would be milliseconds and is not worth the extra clock reads.
189
+ *
190
+ * Pure: `rows` is `[{ name, pin, ok, error }]`. Returns the next state and the
191
+ * names recorded as failures, so the caller can keep its degraded count.
192
+ *
193
+ * @param {{state?: object, rows?: Array<{name: string, pin: string, ok: boolean, error?: string}>, now?: Date|string|number}} input
194
+ * @returns {{state: object, failed: string[]}}
195
+ */
196
+ export function recordInstallOutcomes({ state, rows = [], now } = {}) {
197
+ const base = state && typeof state === 'object' && state.failures && typeof state.failures === 'object'
198
+ ? state
199
+ : emptyState()
200
+ let next = base
201
+ const failed = []
202
+ for (const row of Array.isArray(rows) ? rows : []) {
203
+ if (!row || typeof row.name !== 'string' || row.name === '') continue
204
+ if (row.ok) {
205
+ next = recordSuccess({ state: next, name: row.name })
206
+ continue
207
+ }
208
+ next = recordFailure({ state: next, name: row.name, pin: row.pin, now, error: row.error })
209
+ failed.push(row.name)
210
+ }
211
+ return { state: next, failed }
212
+ }
213
+
214
+ /** Should this pin be skipped on this launch?
215
+ *
216
+ * Order matters:
217
+ * 1. no entry, or an entry for another pin -> try it
218
+ * 2. firstFailedAt is RESET_AFTER_MS old -> try it (fresh round)
219
+ * 3. attempts >= maxAttempts -> skip permanently (until the pin changes or
220
+ * the reset window elapses)
221
+ * 4. still inside the backoff window -> skip for now
222
+ * 5. otherwise -> try
223
+ *
224
+ * The reset check precedes the attempt cap on purpose: without it a plugin
225
+ * that failed three times would never be retried again on this pin.
226
+ *
227
+ * Unreadable timestamps count as "not skipped": retrying is slower than
228
+ * ideal, but a corrupt clock must never wedge provisioning forever. */
229
+ export function shouldSkipRetry({ state, name, pin, now, backoffMs = BACKOFF_MS, maxAttempts = MAX_ATTEMPTS } = {}) {
230
+ const failures = state && typeof state === 'object' && state.failures && typeof state.failures === 'object'
231
+ ? state.failures
232
+ : {}
233
+ const entry = normalizeEntry(failures[name])
234
+ if (!entry || entry.pin !== pin) return { skip: false, reason: null, entry }
235
+
236
+ if (isResetDue({ now, firstFailedAt: entry.firstFailedAt })) {
237
+ return { skip: false, reason: 'reset', entry }
238
+ }
239
+
240
+ const limit = Number.isFinite(Number(maxAttempts)) ? Number(maxAttempts) : MAX_ATTEMPTS
241
+ if (entry.attempts >= limit) return { skip: true, reason: 'max-attempts', entry }
242
+
243
+ const nowMs = parseTimeMs(now)
244
+ const lastMs = parseTimeMs(entry.lastFailedAt)
245
+ if (nowMs === null || lastMs === null) return { skip: false, reason: null, entry }
246
+
247
+ const window = Number.isFinite(Number(backoffMs)) ? Number(backoffMs) : BACKOFF_MS
248
+ if (nowMs - lastMs < window) return { skip: true, reason: 'backoff', entry }
249
+
250
+ return { skip: false, reason: null, entry }
251
+ }
252
+
253
+ /** `pins` may be a name -> pin map, an array of names, or an array of
254
+ * { name, pin } rows. Omitting it summarises every recorded failure using
255
+ * the pin stored in the entry. */
256
+ function pinPairs(pins) {
257
+ if (pins == null) return null
258
+ if (Array.isArray(pins)) {
259
+ return pins.map((item) => {
260
+ if (typeof item === 'string') return [item, null]
261
+ if (item && typeof item === 'object') return [item.name, item.pin ?? null]
262
+ return [null, null]
263
+ })
264
+ }
265
+ if (typeof pins === 'object') return Object.entries(pins)
266
+ return []
267
+ }
268
+
269
+ /** One row per pin this launch would skip, sorted by name, ready to be
270
+ * printed as a single startup warning. */
271
+ export function summarizeSkips({ state, pins, now, backoffMs = BACKOFF_MS, maxAttempts = MAX_ATTEMPTS } = {}) {
272
+ const failures = state && typeof state === 'object' && state.failures && typeof state.failures === 'object'
273
+ ? state.failures
274
+ : {}
275
+ const pairs = pinPairs(pins) ?? Object.keys(failures).map((name) => [name, null])
276
+
277
+ const rows = []
278
+ for (const [name, pin] of pairs) {
279
+ if (typeof name !== 'string' || name === '') continue
280
+ const entry = normalizeEntry(failures[name])
281
+ if (!entry) continue
282
+ const wantedPin = pin == null ? entry.pin : pin
283
+ const verdict = shouldSkipRetry({ state, name, pin: wantedPin, now, backoffMs, maxAttempts })
284
+ if (!verdict.skip) continue
285
+ rows.push({
286
+ name,
287
+ pin: verdict.entry.pin,
288
+ reason: verdict.reason,
289
+ attempts: verdict.entry.attempts,
290
+ lastFailedAt: verdict.entry.lastFailedAt,
291
+ })
292
+ }
293
+ return rows.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
294
+ }