dsh-session-superagent 0.10.12 → 2.0.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,338 @@
1
+ /**
2
+ * 持久化 Outbox 房。
3
+ *
4
+ * 所有变更都先构造完整 next,再 await commit(next, expected);commit 必须返回
5
+ * true / { ok:true },false / { ok:false } 表示 expected 已过期。房间不直接写宿主,
6
+ * 也不调用外部 Channel。调用方在 claim 成功后发送,并带 returned attempts 结算,
7
+ * 以防迟到回执覆盖下一次尝试。
8
+ */
9
+ import { createHash } from 'node:crypto'
10
+
11
+ export const OUTBOX_VERSION = 1
12
+ const STATUSES = ['pending', 'sending', 'sent', 'failed', 'gone']
13
+ const STATUS_SET = new Set(STATUSES)
14
+ const TERMINAL = new Set(['sent', 'gone'])
15
+
16
+ export class OutboxCasConflictError extends Error {
17
+ constructor(expected, next) {
18
+ super(`outbox CAS conflict at revision ${expected.revision}`)
19
+ this.name = 'OutboxCasConflictError'
20
+ this.code = 'OUTBOX_CAS_CONFLICT'
21
+ this.expectedRevision = expected.revision
22
+ this.nextRevision = next.revision
23
+ }
24
+ }
25
+
26
+ function isObject(value) {
27
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
28
+ }
29
+
30
+ function clone(value) {
31
+ if (Array.isArray(value)) return value.map(clone)
32
+ if (!isObject(value)) return value
33
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, clone(child)]))
34
+ }
35
+
36
+ function deepFreeze(value) {
37
+ if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value
38
+ for (const child of Object.values(value)) deepFreeze(child)
39
+ return Object.freeze(value)
40
+ }
41
+
42
+ function requiredText(value, name) {
43
+ if (typeof value !== 'string' || !value) throw new TypeError(`${name} must be a non-empty string`)
44
+ return value
45
+ }
46
+
47
+ function eventAt(at) {
48
+ return at === undefined ? new Date().toISOString() : requiredText(at, 'at')
49
+ }
50
+
51
+ function timeValue(value, name = 'at') {
52
+ const parsed = Date.parse(requiredText(value, name))
53
+ if (!Number.isFinite(parsed)) throw new TypeError(`${name} must be an ISO timestamp`)
54
+ return parsed
55
+ }
56
+
57
+ function revision(value) {
58
+ const number = value === undefined ? 0 : value
59
+ if (!Number.isSafeInteger(number) || number < 0) throw new TypeError('outbox revision must be a non-negative safe integer')
60
+ return number
61
+ }
62
+
63
+ function canonical(value) {
64
+ if (Array.isArray(value)) return value.map(canonical)
65
+ if (!isObject(value)) return value
66
+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])]))
67
+ }
68
+
69
+ function messageParts(message) {
70
+ if (!isObject(message)) throw new TypeError('message must be an object')
71
+ const ticketId = requiredText(message.ticketId, 'message.ticketId')
72
+ if (!isObject(message.channel)) throw new TypeError('message.channel must be an object')
73
+ if (typeof message.body !== 'string') throw new TypeError('message.body must be a string')
74
+ return { ticketId, channel: clone(message.channel), body: message.body }
75
+ }
76
+
77
+ /** 内容寻址;channel 的键顺序不影响 ID。领域也可在 enqueue 时显式提供稳定 id。 */
78
+ export function outboxMessageId(message) {
79
+ const { ticketId, channel, body } = messageParts(message)
80
+ const digest = createHash('sha256').update(JSON.stringify(canonical([ticketId, channel, body]))).digest('hex')
81
+ return `outbox:${digest.slice(0, 32)}`
82
+ }
83
+
84
+ function normalizeMessage(message) {
85
+ const parts = messageParts(message)
86
+ const normalized = {
87
+ id: requiredText(message.id, 'message.id'),
88
+ ...parts,
89
+ status: requiredText(message.status, 'message.status'),
90
+ attempts: message.attempts,
91
+ nextAt: requiredText(message.nextAt, 'message.nextAt'),
92
+ createdAt: requiredText(message.createdAt, 'message.createdAt'),
93
+ updatedAt: requiredText(message.updatedAt, 'message.updatedAt'),
94
+ ...(message.leaseUntil !== undefined ? { leaseUntil: message.leaseUntil } : {}),
95
+ ...(message.ownerId !== undefined ? { ownerId: message.ownerId } : {}),
96
+ ...(message.lastError !== undefined ? { lastError: message.lastError } : {}),
97
+ }
98
+ if (!STATUS_SET.has(normalized.status)) throw new TypeError(`unknown outbox status: ${normalized.status}`)
99
+ if (!Number.isSafeInteger(normalized.attempts) || normalized.attempts < 0) {
100
+ throw new TypeError('message.attempts must be a non-negative safe integer')
101
+ }
102
+ timeValue(normalized.nextAt, 'message.nextAt')
103
+ if (normalized.leaseUntil !== undefined && normalized.leaseUntil !== null) timeValue(normalized.leaseUntil, 'message.leaseUntil')
104
+ return normalized
105
+ }
106
+
107
+ /** 恢复 JSON 状态时保留队列顺序;重复持久 ID 属于损坏状态,直接拒绝。 */
108
+ export function createOutboxState(fields = {}) {
109
+ if (!isObject(fields)) throw new TypeError('outbox state must be an object')
110
+ if (fields.outbox !== undefined && !Array.isArray(fields.outbox)) throw new TypeError('outbox must be an array')
111
+ const source = fields.outbox || []
112
+ const outbox = source.map(normalizeMessage)
113
+ const ids = new Set()
114
+ for (const message of outbox) {
115
+ if (ids.has(message.id)) throw new TypeError(`duplicate outbox id: ${message.id}`)
116
+ ids.add(message.id)
117
+ }
118
+ return {
119
+ ...fields,
120
+ outboxVersion: OUTBOX_VERSION,
121
+ revision: revision(fields.revision),
122
+ outbox,
123
+ }
124
+ }
125
+
126
+ function asState(input) {
127
+ if (input === undefined || input === null) return createOutboxState()
128
+ if (!isObject(input)) throw new TypeError('outbox state must be an object')
129
+ if (input.outboxVersion !== undefined && input.outboxVersion !== OUTBOX_VERSION) {
130
+ throw new Error(`outboxVersion ${input.outboxVersion} is newer than supported ${OUTBOX_VERSION}`)
131
+ }
132
+ if (input.outboxVersion === OUTBOX_VERSION && Array.isArray(input.outbox)) return input
133
+ return createOutboxState(input)
134
+ }
135
+
136
+ async function persist(next, expected, commit) {
137
+ if (typeof commit !== 'function') throw new TypeError('outbox mutation requires commit(next, expected)')
138
+ const receipt = await commit(next, expected)
139
+ if (receipt === false || (isObject(receipt) && receipt.ok === false)) throw new OutboxCasConflictError(expected, next)
140
+ if (receipt !== true && !(isObject(receipt) && receipt.ok === true)) {
141
+ throw new TypeError('commit must acknowledge true/{ok:true} or reject false/{ok:false}')
142
+ }
143
+ return next
144
+ }
145
+
146
+ function replace(state, id, changes) {
147
+ return {
148
+ ...state,
149
+ outboxVersion: OUTBOX_VERSION,
150
+ revision: revision(state.revision) + 1,
151
+ outbox: state.outbox.map((message) => message.id === id ? { ...message, ...changes } : message),
152
+ }
153
+ }
154
+
155
+ function findMessage(state, id) {
156
+ const key = requiredText(id, 'id')
157
+ const message = state.outbox.find((candidate) => candidate.id === key)
158
+ if (!message) throw new RangeError(`unknown outbox id: ${key}`)
159
+ return message
160
+ }
161
+
162
+ function stale(source, message) {
163
+ return source.attempts !== undefined && source.attempts !== message.attempts
164
+ }
165
+
166
+ /** 首次入队才 commit;同 ID 永远保留第一条,sent/gone 也不会复活。 */
167
+ export async function enqueue({ state: input, message, commit, at } = {}) {
168
+ const state = asState(input)
169
+ const parts = messageParts(message)
170
+ const id = message.id === undefined ? outboxMessageId(message) : requiredText(message.id, 'message.id')
171
+ const existing = state.outbox.find((candidate) => candidate.id === id)
172
+ if (existing) return { status: 'duplicate', state, message: existing, reused: true }
173
+ const timestamp = eventAt(at)
174
+ const record = {
175
+ id,
176
+ ...parts,
177
+ status: 'pending',
178
+ attempts: 0,
179
+ nextAt: message.nextAt === undefined ? timestamp : requiredText(message.nextAt, 'message.nextAt'),
180
+ createdAt: timestamp,
181
+ updatedAt: timestamp,
182
+ }
183
+ timeValue(record.nextAt, 'message.nextAt')
184
+ const next = { ...state, outboxVersion: OUTBOX_VERSION, revision: revision(state.revision) + 1, outbox: [...state.outbox, record] }
185
+ await persist(next, state, commit)
186
+ return { status: 'enqueued', state: next, message: record, reused: false }
187
+ }
188
+
189
+ function firstActiveByTicket(state, ticketId) {
190
+ const heads = new Map()
191
+ for (const message of state.outbox) {
192
+ if (TERMINAL.has(message.status)) continue
193
+ if (ticketId !== undefined && message.ticketId !== ticketId) continue
194
+ if (!heads.has(message.ticketId)) heads.set(message.ticketId, message)
195
+ }
196
+ return heads
197
+ }
198
+
199
+ /**
200
+ * 单条认领。每个 Ticket 只有队首可发;其 sending / 退避会挡住同 Ticket 后续,
201
+ * 但不挡住其他 Ticket。成功认领后 attempts 已持久化加一,然后才允许外发。
202
+ */
203
+ export async function claim({ state: input, commit, ticketId, at, leaseMs = 60_000, ownerId } = {}) {
204
+ const state = asState(input)
205
+ if (ticketId !== undefined) requiredText(ticketId, 'ticketId')
206
+ const timestamp = eventAt(at)
207
+ const now = timeValue(timestamp)
208
+ const heads = firstActiveByTicket(state, ticketId)
209
+ const candidate = state.outbox.find((message) => heads.get(message.ticketId) === message
210
+ && (message.status === 'pending' || message.status === 'failed')
211
+ && timeValue(message.nextAt, 'message.nextAt') <= now)
212
+ if (!candidate) {
213
+ const active = [...heads.values()]
214
+ const scheduled = active.filter((message) => message.status === 'pending' || message.status === 'failed')
215
+ .map((message) => timeValue(message.nextAt, 'message.nextAt'))
216
+ return {
217
+ status: active.length ? 'waiting' : 'empty',
218
+ state,
219
+ message: null,
220
+ nextAt: scheduled.length ? new Date(Math.min(...scheduled)).toISOString() : null,
221
+ }
222
+ }
223
+ const lease = Number(leaseMs)
224
+ if (!Number.isFinite(lease) || lease <= 0) throw new TypeError('leaseMs must be a positive finite number')
225
+ const next = replace(state, candidate.id, {
226
+ status: 'sending',
227
+ attempts: candidate.attempts + 1,
228
+ nextAt: timestamp,
229
+ updatedAt: timestamp,
230
+ leaseUntil: new Date(now + lease).toISOString(),
231
+ ownerId: ownerId === undefined ? null : String(ownerId),
232
+ })
233
+ await persist(next, state, commit)
234
+ const message = next.outbox.find((record) => record.id === candidate.id)
235
+ return { status: 'claimed', state: next, message, nextAt: null }
236
+ }
237
+
238
+ /** result=sent 只接受 sending;result=gone 也可直接撤销 pending/failed。终态重复结算不 commit。 */
239
+ export async function settle({ state: input, id, result = 'sent', commit, at, attempts } = {}) {
240
+ const state = asState(input)
241
+ if (result !== 'sent' && result !== 'gone') throw new TypeError('settle result must be sent or gone')
242
+ const current = findMessage(state, id)
243
+ if (TERMINAL.has(current.status)) {
244
+ if (current.status !== result) throw new Error(`outbox message is already ${current.status}`)
245
+ return { status: 'duplicate', state, message: current }
246
+ }
247
+ if (attempts !== undefined && attempts !== current.attempts) return { status: 'stale', state, message: current }
248
+ if (result === 'sent' && current.status !== 'sending') throw new Error('sent settlement requires a sending message')
249
+ const timestamp = eventAt(at)
250
+ const next = replace(state, current.id, { status: result, updatedAt: timestamp, leaseUntil: null, ownerId: null, lastError: null })
251
+ await persist(next, state, commit)
252
+ return { status: result, state: next, message: next.outbox.find((message) => message.id === current.id) }
253
+ }
254
+
255
+ /** 外发失败:sending → failed,默认 5 秒起步、指数增长、5 分钟封顶。 */
256
+ export async function retry({
257
+ state: input,
258
+ id,
259
+ commit,
260
+ at,
261
+ attempts,
262
+ error,
263
+ baseDelayMs = 5000,
264
+ maxDelayMs = 300000,
265
+ } = {}) {
266
+ const state = asState(input)
267
+ const current = findMessage(state, id)
268
+ if (TERMINAL.has(current.status)) throw new Error(`cannot retry a ${current.status} message`)
269
+ if (attempts !== undefined && attempts !== current.attempts) return { status: 'stale', state, message: current }
270
+ if (current.status === 'failed') return { status: 'duplicate', state, message: current }
271
+ if (current.status !== 'sending') throw new Error('retry requires a sending message')
272
+ const base = Number(baseDelayMs)
273
+ const cap = Number(maxDelayMs)
274
+ if (!Number.isFinite(base) || base < 0 || !Number.isFinite(cap) || cap < 0) {
275
+ throw new TypeError('retry delays must be non-negative finite numbers')
276
+ }
277
+ const timestamp = eventAt(at)
278
+ const delay = Math.min(cap, base * (2 ** Math.max(0, current.attempts - 1)))
279
+ const nextAt = new Date(timeValue(timestamp) + delay).toISOString()
280
+ const next = replace(state, current.id, { status: 'failed', nextAt, updatedAt: timestamp, leaseUntil: null, ownerId: null, lastError: String(error || 'send failed').slice(0, 1000) })
281
+ await persist(next, state, commit)
282
+ return { status: 'failed', state: next, message: next.outbox.find((message) => message.id === current.id) }
283
+ }
284
+
285
+ /** 启动时恢复崩溃留下的 sending;attempts 不加,sent/gone 与失败退避原样保留。 */
286
+ export async function recover({ state: input, commit, at } = {}) {
287
+ const state = asState(input)
288
+ const timestamp = eventAt(at)
289
+ const now = timeValue(timestamp)
290
+ const recoveredIds = state.outbox.filter((message) => message.status === 'sending'
291
+ && (!message.leaseUntil || timeValue(message.leaseUntil, 'message.leaseUntil') <= now)).map((message) => message.id)
292
+ if (!recoveredIds.length) return { status: 'unchanged', state, recoveredIds }
293
+ const ids = new Set(recoveredIds)
294
+ const next = {
295
+ ...state,
296
+ outboxVersion: OUTBOX_VERSION,
297
+ revision: revision(state.revision) + 1,
298
+ outbox: state.outbox.map((message) => ids.has(message.id)
299
+ ? { ...message, status: 'pending', nextAt: timestamp, updatedAt: timestamp, leaseUntil: null, ownerId: null }
300
+ : message),
301
+ }
302
+ await persist(next, state, commit)
303
+ return { status: 'recovered', state: next, recoveredIds }
304
+ }
305
+
306
+ function projectedRecord(message) {
307
+ return {
308
+ id: typeof message.id === 'string' && message.id ? message.id : null,
309
+ ticketId: typeof message.ticketId === 'string' && message.ticketId ? message.ticketId : null,
310
+ channel: message.channel === undefined ? null : clone(message.channel),
311
+ body: typeof message.body === 'string' ? message.body : null,
312
+ status: STATUS_SET.has(message.status) ? message.status : null,
313
+ attempts: Number.isSafeInteger(message.attempts) && message.attempts >= 0 ? message.attempts : null,
314
+ nextAt: typeof message.nextAt === 'string' && message.nextAt ? message.nextAt : null,
315
+ createdAt: typeof message.createdAt === 'string' && message.createdAt ? message.createdAt : null,
316
+ updatedAt: typeof message.updatedAt === 'string' && message.updatedAt ? message.updatedAt : null,
317
+ ...(message.lastError !== undefined && message.lastError !== null ? { lastError: String(message.lastError) } : {}),
318
+ }
319
+ }
320
+
321
+ /** 与 records 投影同形;缺集合是 null,显式空集合才是 0,且返回值完全冻结。 */
322
+ export function projectOutbox(input) {
323
+ let known = false
324
+ let items = []
325
+ if (Array.isArray(input)) { known = true; items = input }
326
+ else if (isObject(input) && Array.isArray(input.outbox)) { known = true; items = input.outbox }
327
+ else if (isObject(input) && isObject(input.outbox)) { known = true; items = Object.values(input.outbox) }
328
+ if (!known) {
329
+ return deepFreeze({ records: null, total: null, counts: Object.fromEntries(STATUSES.map((status) => [status, null])) })
330
+ }
331
+ const counts = Object.fromEntries(STATUSES.map((status) => [status, 0]))
332
+ const records = items.map((message) => {
333
+ const record = projectedRecord(isObject(message) ? message : {})
334
+ if (record.status) counts[record.status] += 1
335
+ return record
336
+ })
337
+ return deepFreeze({ records, total: records.length, counts })
338
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * 水位 v2 · 投影房。
3
+ *
4
+ * 面板、工具与诊断共用只读视图。输入不被修改,输出冻结;内部 obs 表不暴露,
5
+ * 因此 UI 不能绕过状态房回写水位。
6
+ */
7
+ import { decideWatermark } from './watermark-decision.js'
8
+
9
+ function isObject(value) {
10
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
11
+ }
12
+
13
+ function timeValue(value) {
14
+ if (typeof value === 'number' && Number.isFinite(value)) return value
15
+ const parsed = Date.parse(String(value || ''))
16
+ return Number.isFinite(parsed) ? parsed : 0
17
+ }
18
+
19
+ function latest(rows, field) {
20
+ let latestAt = null
21
+ let latestValue = 0
22
+ for (const row of rows) {
23
+ const event = row && row[field]
24
+ if (!event) continue
25
+ const value = timeValue(event.at)
26
+ if (value >= latestValue) { latestValue = value; latestAt = event.at || null }
27
+ }
28
+ return latestAt
29
+ }
30
+
31
+ function deepFreeze(value) {
32
+ if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value
33
+ for (const child of Object.values(value)) deepFreeze(child)
34
+ return Object.freeze(value)
35
+ }
36
+
37
+ export function projectWatcher(entry, options = {}) {
38
+ const source = isObject(entry) ? entry : {}
39
+ const now = Number.isFinite(Number(options.now)) ? Number(options.now) : Date.now()
40
+ const enabled = source.enabled !== false
41
+ const nextAt = source.nextAt || null
42
+ const status = !enabled ? 'paused'
43
+ : source.lastError ? 'error'
44
+ : (nextAt && timeValue(nextAt) > now) ? 'deferred'
45
+ : 'running'
46
+ const version = Number(source.watermarkVersion) || 1
47
+ const obs = isObject(source.obs) ? source.obs : {}
48
+ const rows = Object.values(obs).filter(isObject)
49
+ const legacyPending = isObject(source.pending) ? Object.keys(source.pending) : []
50
+
51
+ const hasCurrentItems = Array.isArray(options.items)
52
+ let decision = null
53
+ if (version === 2) {
54
+ decision = decideWatermark({
55
+ items: Array.isArray(options.items) ? options.items : [],
56
+ obs,
57
+ sameCursor: options.sameCursor,
58
+ now,
59
+ cooldownMs: options.cooldownMs,
60
+ maxRetries: options.maxRetries,
61
+ batchLimit: options.batchLimit,
62
+ wakeTimes: source.wakeTimes,
63
+ maxWakesPerHour: source.maxWakesPerHour,
64
+ })
65
+ }
66
+
67
+ const knownState = Object.keys(source).length > 0
68
+ const freshCount = knownState && hasCurrentItems && decision ? decision.fresh.length : (knownState && version === 1 ? 0 : null)
69
+ const retryCount = knownState && hasCurrentItems && decision ? decision.retry.length : (knownState && version === 1 ? legacyPending.length : null)
70
+ const handledCount = knownState && hasCurrentItems && decision ? decision.handled.length : (knownState && version === 1 ? (isObject(source.acked) ? Object.keys(source.acked).length : 0) : null)
71
+ const candidateCount = knownState && hasCurrentItems && decision ? decision.candidates.length : (knownState && version === 1 ? legacyPending.length : null)
72
+ const legacyCount = version === 1 ? legacyPending.length : rows.filter((row) => row.legacy).length
73
+
74
+ return deepFreeze({
75
+ id: source.id || null,
76
+ repo: source.repo || null,
77
+ sessionId: source.sessionId || null,
78
+ kind: source.kind || 'issue',
79
+ enabled,
80
+ status,
81
+ watermarkVersion: version,
82
+ round: Number(source.round) || 0,
83
+ freshCount,
84
+ retryCount,
85
+ handledCount,
86
+ candidateCount,
87
+ legacyCount,
88
+ lastDeliveryAt: latest(rows, 'delivered'),
89
+ lastHandledAt: latest(rows, 'handled'),
90
+ lastError: source.lastError || null,
91
+ nextAt,
92
+ deferReason: source.deferReason || null,
93
+ capabilities: Array.isArray(options.capabilities) ? [...options.capabilities] : [],
94
+ budget: decision ? decision.budget : { used: 0, remaining: 0 },
95
+ })
96
+ }
97
+
98
+ export function projectWatchers(state, options = {}) {
99
+ const watchers = isObject(state && state.watchers) ? state.watchers : {}
100
+ const itemsById = isObject(options.itemsById) ? options.itemsById : {}
101
+ return deepFreeze(Object.entries(watchers).map(([id, entry]) => projectWatcher(
102
+ { id, ...(isObject(entry) ? entry : {}) },
103
+ { ...options, items: itemsById[id] || options.items || [] },
104
+ )))
105
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * 提示词配置房:只拥有单会话所需的少量模板。
3
+ *
4
+ * 配置形状与 i18n 房一致:{ zh: { key: template }, en: { key: template } }。
5
+ * 所有创建与覆盖都返回深冻结的新对象;默认模板与调用方传入的对象绝不被改写。
6
+ */
7
+
8
+ export const PROMPT_KEYS = Object.freeze(['wake', 'ack', 'outbox', 'resume'])
9
+ export const PROMPT_LANGUAGES = Object.freeze(['zh', 'en'])
10
+
11
+ const DEFAULTS = {
12
+ zh: {
13
+ wake: '【主理鱼】{repo} 有待处理更新:\n{items}\n本条目主理目标:{goal}',
14
+ ack: '{repo} 已处理:{numbers}\n处理记录:{note}',
15
+ outbox: '待回写 {ticketId}:\n{body}',
16
+ resume: '人工恢复 {ticketId}。\n原因:{reason}\n请先读取当前状态,再继续未完成的工作。',
17
+ },
18
+ en: {
19
+ wake: '[Superagent] Updates need attention in {repo}:\n{items}\nGoal: {goal}',
20
+ ack: 'Handled in {repo}: {numbers}\nNote: {note}',
21
+ outbox: 'Pending outbox delivery for {ticketId}:\n{body}',
22
+ resume: 'Human resume requested for {ticketId}.\nReason: {reason}\nRead the current state before continuing unfinished work.',
23
+ },
24
+ }
25
+
26
+ function freezeCatalog(catalogs) {
27
+ for (const language of PROMPT_LANGUAGES) Object.freeze(catalogs[language])
28
+ return Object.freeze(catalogs)
29
+ }
30
+
31
+ export const DEFAULT_PROMPTS = freezeCatalog({
32
+ zh: { ...DEFAULTS.zh },
33
+ en: { ...DEFAULTS.en },
34
+ })
35
+
36
+ function isRecord(value) {
37
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
38
+ }
39
+
40
+ function assertLanguage(language) {
41
+ if (!PROMPT_LANGUAGES.includes(language)) {
42
+ throw new RangeError(`prompt language must be zh or en; received ${String(language)}`)
43
+ }
44
+ return language
45
+ }
46
+
47
+ function assertKey(key) {
48
+ if (!PROMPT_KEYS.includes(key)) {
49
+ throw new RangeError(`unknown prompt template: ${String(key)}`)
50
+ }
51
+ return key
52
+ }
53
+
54
+ function assertTemplate(template, key, language) {
55
+ if (typeof template !== 'string' || !template.trim()) {
56
+ throw new TypeError(`prompt template ${language}.${key} must be a non-empty string`)
57
+ }
58
+ return template
59
+ }
60
+
61
+ function copyOverrides(overrides) {
62
+ if (!isRecord(overrides)) throw new TypeError('prompt overrides must be an object')
63
+ for (const language of Object.keys(overrides)) assertLanguage(language)
64
+
65
+ const copy = {}
66
+ for (const language of PROMPT_LANGUAGES) {
67
+ const localized = overrides[language] === undefined ? {} : overrides[language]
68
+ if (!isRecord(localized)) throw new TypeError(`prompt overrides.${language} must be an object`)
69
+ for (const key of Object.keys(localized)) assertKey(key)
70
+ copy[language] = Object.fromEntries(PROMPT_KEYS
71
+ .filter((key) => Object.hasOwn(localized, key))
72
+ .map((key) => [key, assertTemplate(localized[key], key, language)]))
73
+ }
74
+ return copy
75
+ }
76
+
77
+ /** 部分覆盖会回退到内置默认;返回完整、独立且冻结的 zh/en 目录。 */
78
+ export function createPromptConfig(overrides = {}) {
79
+ const custom = copyOverrides(overrides)
80
+ return freezeCatalog({
81
+ zh: { ...DEFAULT_PROMPTS.zh, ...custom.zh },
82
+ en: { ...DEFAULT_PROMPTS.en, ...custom.en },
83
+ })
84
+ }
85
+
86
+ /** 覆盖单一语言的一张模板,不改写原配置或默认对象。 */
87
+ export function setPromptOverride(config, key, language, template) {
88
+ assertKey(key)
89
+ assertLanguage(language)
90
+ assertTemplate(template, key, language)
91
+ const current = createPromptConfig(config)
92
+ return createPromptConfig({
93
+ ...current,
94
+ [language]: { ...current[language], [key]: template },
95
+ })
96
+ }
97
+
98
+ /** 清除单一语言的覆盖,让它重新跟随内置默认。 */
99
+ export function clearPromptOverride(config, key, language) {
100
+ assertKey(key)
101
+ assertLanguage(language)
102
+ const current = createPromptConfig(config)
103
+ return createPromptConfig({
104
+ ...current,
105
+ [language]: { ...current[language], [key]: DEFAULT_PROMPTS[language][key] },
106
+ })
107
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * 水位 v2 · 调度房。
3
+ *
4
+ * 只回答「现在是否轮询」:interval、boot、退避、暂停恢复、人工立即与 inFlight。
5
+ * 不读取 obs,也不判断条目是否新鲜。定时器与 poll 都可注入,测试无需真实等待。
6
+ */
7
+ export function createWatchScheduler(options = {}) {
8
+ if (typeof options.poll !== 'function') throw new TypeError('createWatchScheduler requires poll')
9
+ const timers = options.timers || globalThis
10
+ const now = typeof options.now === 'function' ? options.now : Date.now
11
+ const noPoll = typeof options.noPoll === 'function' ? options.noPoll : () => false
12
+ const intervalMs = Math.max(30, Number(options.intervalMs) || 60000)
13
+ const bootDelayMs = Math.max(0, Number(options.bootDelayMs) || 0)
14
+
15
+ let enabled = options.enabled !== false
16
+ let nextAt = null
17
+ let consecutiveFailures = 0
18
+ let deferReason = null
19
+ let inFlight = false
20
+ let current = null
21
+ let intervalTimer = null
22
+ let bootTimer = null
23
+
24
+ const clearIntervalTimer = () => {
25
+ if (intervalTimer) timers.clearInterval(intervalTimer)
26
+ intervalTimer = null
27
+ }
28
+ const clearBootTimer = () => {
29
+ if (bootTimer) timers.clearTimeout(bootTimer)
30
+ bootTimer = null
31
+ }
32
+ const clearBackoff = () => {
33
+ nextAt = null
34
+ consecutiveFailures = 0
35
+ deferReason = null
36
+ }
37
+ const recordFailure = ({ timeout = false } = {}) => {
38
+ if (timeout) {
39
+ nextAt = now() + 30000
40
+ deferReason = 'timeout'
41
+ return
42
+ }
43
+ consecutiveFailures += 1
44
+ const delay = Math.min(30000 * (2 ** Math.max(0, consecutiveFailures - 1)), 30 * 60 * 1000)
45
+ nextAt = now() + delay
46
+ deferReason = 'backoff'
47
+ }
48
+ const run = (manual = false) => {
49
+ if (!enabled) return { status: 'paused' }
50
+ if (inFlight) return { status: 'in-flight' }
51
+ if (noPoll()) return { status: 'offline' }
52
+ if (!manual && nextAt !== null && now() < nextAt) return { status: 'backoff' }
53
+ if (manual) clearBackoff()
54
+
55
+ inFlight = true
56
+ current = Promise.resolve()
57
+ .then(() => options.poll({ manual }))
58
+ .then((result) => {
59
+ if (result && result.timeout) recordFailure({ timeout: true })
60
+ else if (result && result.ok === false) recordFailure()
61
+ else clearBackoff()
62
+ return result
63
+ })
64
+ .catch((error) => {
65
+ recordFailure({ timeout: Boolean(error && error.timeout) })
66
+ return { ok: false, error }
67
+ })
68
+ .finally(() => { inFlight = false })
69
+ return { status: 'started' }
70
+ }
71
+ const start = () => {
72
+ if (!enabled) return { status: 'paused' }
73
+ if (noPoll()) return { status: 'offline' }
74
+ if (intervalTimer) return { status: 'already-started' }
75
+ intervalTimer = timers.setInterval(() => { run(false) }, intervalMs)
76
+ if (typeof intervalTimer.unref === 'function') intervalTimer.unref()
77
+ if (bootDelayMs > 0) {
78
+ bootTimer = timers.setTimeout(() => { bootTimer = null; run(false) }, bootDelayMs)
79
+ if (typeof bootTimer.unref === 'function') bootTimer.unref()
80
+ } else {
81
+ run(false)
82
+ }
83
+ return { status: 'started' }
84
+ }
85
+ const pause = () => {
86
+ enabled = false
87
+ clearIntervalTimer()
88
+ clearBootTimer()
89
+ return { status: 'paused' }
90
+ }
91
+ const resume = () => {
92
+ enabled = true
93
+ start()
94
+ const result = run(true)
95
+ if (result.status === 'started') clearBootTimer()
96
+ return result
97
+ }
98
+
99
+ return {
100
+ start,
101
+ pause,
102
+ resume,
103
+ stop: pause,
104
+ run,
105
+ pollNow: () => run(true),
106
+ whenIdle: () => current || Promise.resolve(),
107
+ clearBackoff,
108
+ recordFailure,
109
+ status: () => ({
110
+ enabled,
111
+ nextAt,
112
+ consecutiveFailures,
113
+ deferReason,
114
+ inFlight,
115
+ timerPending: Boolean(intervalTimer),
116
+ bootTimerPending: Boolean(bootTimer),
117
+ }),
118
+ }
119
+ }