dsh-qq-affinity 1.0.3 → 1.5.6

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.
package/lib/care.js CHANGED
@@ -16,7 +16,8 @@
16
16
 
17
17
  import { plainText, send as sendThroughBridge } from './onebot.js'
18
18
  import { inQuietHours, isAiAuthored, uid } from './util.js'
19
- import { writeAutoReply } from './analyze.js'
19
+ import { writeAutoReply, writeCapExcuse, cannedExcuse } from './analyze.js'
20
+ import { resolvePersona } from './personas.js'
20
21
 
21
22
  const HOUR = 60 * 60 * 1000
22
23
 
@@ -40,6 +41,10 @@ export function createCareEngine({ ctx, store, deliver: deliverOverride, tasks =
40
41
  const chains = new Map()
41
42
  /** uin -> timestamps of replies actually sent, for the hourly cap. */
42
43
  const sent = new Map()
44
+ /** uin -> when the cap brush-off was last sent, so it happens at most once an hour. */
45
+ const excused = new Map()
46
+ /** uin -> { events, timer }: messages waiting for the debounce window to close. */
47
+ const pending = new Map()
43
48
 
44
49
  const sendOut = deliverOverride ?? ((settings, target, text) => sendThroughBridge(settings, target, text))
45
50
 
@@ -51,12 +56,51 @@ export function createCareEngine({ ctx, store, deliver: deliverOverride, tasks =
51
56
  return next
52
57
  }
53
58
 
54
- /** Recorded timestamps for one person inside the last hour. */
59
+ /** ISO timestamp of one outbox row, in milliseconds. */
60
+ function stampOf(row) {
61
+ const at = Date.parse(row.sentAt ?? row.createdAt ?? '')
62
+ return Number.isFinite(at) ? at : 0
63
+ }
64
+
65
+ /**
66
+ * The start of the current quota window for one person.
67
+ *
68
+ * Usually "an hour ago", but a manual reset moves it forward: the user's
69
+ * decision to zero the count beats the sliding window.
70
+ */
71
+ function windowStart(uin) {
72
+ return Math.max(Date.now() - HOUR, store.careResetAt(uin))
73
+ }
74
+
75
+ /**
76
+ * Reply *events* sent to one person inside the last hour.
77
+ *
78
+ * One event = one automatic reply, no matter how many of their messages that
79
+ * reply covered (the debounce can fold five messages into one answer — that is
80
+ * still 一次). Counted from the outbox rather than only from memory: the quota
81
+ * has to survive a plugin reload.
82
+ */
55
83
  function recentCount(uin) {
56
- const cutoff = Date.now() - HOUR
84
+ const cutoff = windowStart(uin)
57
85
  const kept = (sent.get(uin) ?? []).filter(at => at >= cutoff)
58
86
  sent.set(uin, kept)
59
- return kept.length
87
+ const recorded = store.outbox().filter(row => row.uin === uin
88
+ && (row.kind ?? 'reply') === 'reply'
89
+ // 'sending' is in flight; counting it stops a burst from slipping through.
90
+ && (row.status === 'sent' || row.status === 'sending')
91
+ && stampOf(row) >= cutoff).length
92
+ return Math.max(kept.length, recorded)
93
+ }
94
+
95
+ /** How many of their messages those reply events covered, for the panel. */
96
+ function coveredMessages(uin) {
97
+ const cutoff = windowStart(uin)
98
+ return store.outbox()
99
+ .filter(row => row.uin === uin
100
+ && (row.kind ?? 'reply') === 'reply'
101
+ && (row.status === 'sent' || row.status === 'sending')
102
+ && stampOf(row) >= cutoff)
103
+ .reduce((total, row) => total + (Number(row.inboundCount) > 0 ? Number(row.inboundCount) : 1), 0)
60
104
  }
61
105
 
62
106
  /** Record one reply attempt and return its outbox row. */
@@ -64,11 +108,30 @@ export function createCareEngine({ ctx, store, deliver: deliverOverride, tasks =
64
108
  return store.recordOutbox({ id: uid('o'), ...fields })
65
109
  }
66
110
 
111
+ /**
112
+ * Whether this person has already been brushed off in the current hour.
113
+ *
114
+ * The outbox is the source of truth, not the in-memory map: a reload in the
115
+ * middle of the hour must not produce a second excuse, and the outbox is what
116
+ * survives a reload.
117
+ */
118
+ function excusedRecently(uin) {
119
+ const cutoff = windowStart(uin)
120
+ const fromOutbox = store.outbox().some(row => row.uin === uin
121
+ && row.kind === 'excuse'
122
+ // A draft or in-flight excuse counts too: it is still this hour's one brush-off.
123
+ && (row.status === 'sent' || row.status === 'sending' || row.status === 'draft')
124
+ && stampOf(row) >= cutoff)
125
+ if (fromOutbox) return true
126
+ return (excused.get(uin) ?? 0) >= cutoff
127
+ }
128
+
67
129
  /**
68
130
  * Actually send one reply and fold it into the conversation.
69
131
  * @returns {Promise<object>} the updated outbox row.
70
132
  */
71
- async function dispatch(row, conversation, targetUin) {
133
+ async function dispatch(row, conversation, targetUin, options = {}) {
134
+ const track = options.track !== false
72
135
  const settings = store.state.settings
73
136
  const bridge = settings.onebot
74
137
  const target = {
@@ -85,7 +148,8 @@ export function createCareEngine({ ctx, store, deliver: deliverOverride, tasks =
85
148
  text: row.text,
86
149
  aiAuto: true,
87
150
  }])
88
- sent.set(targetUin, [...(sent.get(targetUin) ?? []), Date.now()])
151
+ // A cap brush-off is a courtesy, not one of the replies the cap counts.
152
+ if (track) sent.set(targetUin, [...(sent.get(targetUin) ?? []), Date.now()])
89
153
  store.markStale(conversation)
90
154
  return store.updateOutbox(row.id, {
91
155
  status: 'sent',
@@ -156,28 +220,157 @@ export function createCareEngine({ ctx, store, deliver: deliverOverride, tasks =
156
220
  // Answering every line in a group would be noise; only a mention wakes it.
157
221
  return { action: 'ignored', reason: 'not-mentioned' }
158
222
  }
159
- if (UNANSWERABLE.test(plainText(event.text))) {
223
+ // Everything else is decided when the wait is over, not now: a burst of
224
+ // messages should produce one reply to the whole burst.
225
+ return schedule(event, conversation, care)
226
+ }
227
+
228
+ /**
229
+ * Buffer one eligible message and (re)start the wait.
230
+ *
231
+ * Each new message restarts the timer, so the reply lands once the other side
232
+ * stops typing — the way a person answers a run of messages in one go.
233
+ */
234
+ function schedule(event, conversation, care) {
235
+ const uin = event.peerUin
236
+ const delayMs = Math.max(0, Math.round(Number(care.replyDelaySeconds ?? 5) * 1000))
237
+ const entry = pending.get(uin) ?? { events: [], timer: null, conversation }
238
+ entry.events.push(event)
239
+ entry.conversation = conversation
240
+ if (entry.timer !== null) {
241
+ clearTimeout(entry.timer)
242
+ entry.timer = null
243
+ }
244
+ pending.set(uin, entry)
245
+ if (delayMs === 0) return flush(uin)
246
+ entry.timer = setTimeout(() => {
247
+ entry.timer = null
248
+ // The timer fires outside the per-person chain, so join it here.
249
+ void serialize(uin, () => flush(uin))
250
+ }, delayMs)
251
+ return {
252
+ action: 'queued',
253
+ reason: `等 ${Math.max(1, Math.round(delayMs / 1000))} 秒看还有没有新消息,到时一起回`,
254
+ }
255
+ }
256
+
257
+ /**
258
+ * Answer everything buffered for one person, in a single turn.
259
+ *
260
+ * Deliberately not serialized here: the immediate path already runs inside the
261
+ * per-person chain, and re-entering it would make the chain await itself. The
262
+ * timer path wraps this in `serialize` instead.
263
+ * @param {string} uin
264
+ */
265
+ function flush(uin) {
266
+ const entry = pending.get(uin)
267
+ if (entry === undefined) return Promise.resolve({ action: 'ignored', reason: 'nothing-queued' })
268
+ if (entry.timer !== null) clearTimeout(entry.timer)
269
+ pending.delete(uin)
270
+ return replyTurn(entry.events, entry.conversation)
271
+ }
272
+
273
+ /**
274
+ * The reply pipeline for one coalesced burst.
275
+ * @param {Array<object>} events - every buffered message, oldest first.
276
+ * @param {object} conversation
277
+ */
278
+ async function replyTurn(events, conversation) {
279
+ // A picture or a bare sticker on its own is not something to answer; if the
280
+ // burst contains anything with words, those are what get answered.
281
+ const usable = events.filter(entry => !UNANSWERABLE.test(plainText(entry.text)))
282
+ const uin = (usable[usable.length - 1] ?? events[events.length - 1]).peerUin
283
+ const care = store.careFor(uin)
284
+ const skip = (reason, extra = {}) => {
285
+ const newest = events[events.length - 1]
286
+ const row = note({
287
+ conversationId: conversation.id,
288
+ uin,
289
+ inboundText: newest.text,
290
+ inboundTs: newest.ts,
291
+ inboundCount: events.length,
292
+ status: 'skipped',
293
+ reason,
294
+ ...extra,
295
+ })
296
+ return { action: 'skipped', reason, outboxId: row.id }
297
+ }
298
+
299
+ if (care === undefined || care.enabled !== true) return { action: 'recorded', reason: 'person-off' }
300
+ if (usable.length === 0) {
160
301
  return skip('对方只发了图片或表情,没有可以接的话。')
161
302
  }
303
+ const event = usable[usable.length - 1]
304
+ // The voice in force right now, recorded on every row it produces.
305
+ const persona = resolvePersona(store.state.replyPersonas, care.persona)
162
306
  if (inQuietHours(nowMinutes(), care.quietFrom, care.quietTo)) {
163
307
  return skip(`落在免打扰时段(${care.quietFrom}–${care.quietTo})。`)
164
308
  }
165
- // No minimum gap: the hourly cap is the only rate limit.
166
- if (recentCount(event.peerUin) >= care.hourlyCap) {
167
- return skip(`这一小时已经自动回复 ${care.hourlyCap} 次,先停下。`)
309
+ // No minimum gap: the hourly cap is the only rate limit. Reaching it is not
310
+ // silence: one polite brush-off goes out, and only then does it stop.
311
+ if (recentCount(uin) >= care.hourlyCap) {
312
+ // One brush-off per hour, for the (N+1)-th message only. Everything after
313
+ // it stays silent, however many messages arrive.
314
+ if (excusedRecently(uin)) {
315
+ return skip(`这一小时已经回复 ${care.hourlyCap} 次并推辞过一次,不再打扰。`)
316
+ }
317
+ const excuseTask = tasks === null ? '' : tasks.begin({
318
+ kind: 'care',
319
+ label: '找借口推辞',
320
+ detail: store.person(uin)?.names?.slice(-1)[0] ?? uin,
321
+ })
322
+ let excuse
323
+ try {
324
+ excuse = await writeCapExcuse(ctx, store, {
325
+ conversationId: conversation.id,
326
+ uin,
327
+ maxChars: Math.min(30, care.maxReplyChars),
328
+ })
329
+ if (excuseTask !== '') tasks.finish(excuseTask)
330
+ } catch (error) {
331
+ // A phrasing failure must never turn into silence: fall back to a canned line.
332
+ excuse = cannedExcuse(event.ts)
333
+ if (excuseTask !== '') tasks.finish(excuseTask, '模型没写出推辞,用了备用话术')
334
+ }
335
+ excused.set(uin, Date.now())
336
+ const excuseRow = note({
337
+ conversationId: conversation.id,
338
+ uin,
339
+ inboundText: event.text,
340
+ inboundTs: event.ts,
341
+ inboundCount: events.length,
342
+ text: excuse,
343
+ kind: 'excuse',
344
+ personaId: persona.id,
345
+ personaName: persona.name,
346
+ status: care.mode === 'auto' ? 'sending' : 'draft',
347
+ })
348
+ if (care.mode !== 'auto') {
349
+ return { action: 'declined', reason: '已达回复上限,已备好一句推辞等你确认。', outboxId: excuseRow.id }
350
+ }
351
+ // The brush-off itself does not consume the hourly quota.
352
+ const sentExcuse = await dispatch(excuseRow, conversation, uin, { track: false })
353
+ return {
354
+ action: 'declined',
355
+ reason: '已达回复上限,已礼貌推辞这次聊天。',
356
+ outboxId: excuseRow.id,
357
+ error: sentExcuse.status === 'sent' ? '' : sentExcuse.reason,
358
+ }
168
359
  }
169
360
 
170
361
  let text
362
+ const stats = {}
171
363
  const replyTask = tasks === null ? '' : tasks.begin({
172
364
  kind: 'care',
173
365
  label: care.mode === 'auto' ? '自动回复' : '生成托管草稿',
174
- detail: store.person(event.peerUin)?.names?.slice(-1)[0] ?? event.peerUin,
366
+ detail: store.person(uin)?.names?.slice(-1)[0] ?? uin,
175
367
  })
176
368
  try {
177
369
  text = await writeAutoReply(ctx, store, {
178
370
  conversationId: conversation.id,
179
- uin: event.peerUin,
371
+ uin,
180
372
  maxChars: care.maxReplyChars,
373
+ stats,
181
374
  })
182
375
  if (replyTask !== '') tasks.finish(replyTask)
183
376
  } catch (error) {
@@ -187,15 +380,21 @@ export function createCareEngine({ ctx, store, deliver: deliverOverride, tasks =
187
380
 
188
381
  const row = note({
189
382
  conversationId: conversation.id,
190
- uin: event.peerUin,
383
+ uin,
191
384
  inboundText: event.text,
192
385
  inboundTs: event.ts,
386
+ inboundCount: events.length,
193
387
  text,
388
+ // Which voice wrote this line — the record should say so, not just the panel.
389
+ personaId: persona.id,
390
+ personaName: persona.name,
391
+ // How big the request was, so an unusual jump is visible in the record.
392
+ promptChars: Number(stats.promptChars ?? 0),
194
393
  status: care.mode === 'auto' ? 'sending' : 'draft',
195
394
  })
196
395
 
197
396
  if (care.mode !== 'auto') return { action: 'drafted', outboxId: row.id }
198
- const updated = await dispatch(row, conversation, event.peerUin)
397
+ const updated = await dispatch(row, conversation, uin)
199
398
  return { action: updated.status === 'sent' ? 'sent' : 'failed', outboxId: row.id, reason: updated.reason }
200
399
  }
201
400
 
@@ -206,6 +405,11 @@ export function createCareEngine({ ctx, store, deliver: deliverOverride, tasks =
206
405
  return serialize(key, () => handleEvent(event))
207
406
  }
208
407
 
408
+ /** How many people currently have messages waiting for their debounce window. */
409
+ function pendingCount() {
410
+ return pending.size
411
+ }
412
+
209
413
  /** Send a draft the user approved. Cooldowns do not apply to an explicit action. */
210
414
  async function approve(id) {
211
415
  const row = store.outbox().find(entry => entry.id === id)
@@ -228,17 +432,34 @@ export function createCareEngine({ ctx, store, deliver: deliverOverride, tasks =
228
432
  return store.updateOutbox(id, { status: 'cancelled', decidedAt: new Date().toISOString() })
229
433
  }
230
434
 
231
- /** How many automatic replies went out in the last hour, per person. */
435
+ /**
436
+ * Per-person usage for the panel: reply events this hour, the messages they
437
+ * covered, and the configured cap.
438
+ */
232
439
  function usage() {
233
440
  const result = {}
234
- for (const [uin, times] of sent.entries()) {
235
- const kept = times.filter(at => at >= Date.now() - HOUR)
236
- if (kept.length > 0) result[uin] = { lastHour: kept.length, lastAt: Math.max(...kept) }
441
+ const rows = store.outbox()
442
+ const uins = new Set(rows.filter(row => (row.kind ?? 'reply') === 'reply').map(row => row.uin))
443
+ for (const uin of uins) {
444
+ const times = recentCount(uin)
445
+ if (times <= 0) continue
446
+ const care = store.careFor(uin)
447
+ const lastAt = rows
448
+ .filter(row => row.uin === uin
449
+ && (row.kind ?? 'reply') === 'reply'
450
+ && (row.status === 'sent' || row.status === 'sending'))
451
+ .reduce((latest, row) => Math.max(latest, stampOf(row)), 0)
452
+ result[uin] = {
453
+ lastHour: times,
454
+ coveredMessages: coveredMessages(uin),
455
+ lastAt: lastAt === 0 ? null : lastAt,
456
+ cap: care === undefined ? undefined : care.hourlyCap,
457
+ }
237
458
  }
238
459
  return result
239
460
  }
240
461
 
241
- return { handleEvent, enqueue, approve, cancel, usage }
462
+ return { handleEvent, enqueue, flush, pendingCount, approve, cancel, usage }
242
463
  }
243
464
 
244
465
  /** Count the AI-authored rows of one conversation, for the UI badge. */
package/lib/features.js CHANGED
@@ -234,3 +234,108 @@ export function lastInbound(rows, targetUin) {
234
234
  }
235
235
  return undefined
236
236
  }
237
+
238
+ /**
239
+ * What a group looks like as a room, rather than as a set of individuals.
240
+ *
241
+ * A group has no "the other person", so the usual measure() split does not apply:
242
+ * here the interesting facts are who speaks, when, how fast the room moves, and
243
+ * how much of it is addressed at me.
244
+ * @param {Array<object>} rows - every row of one group conversation.
245
+ * @param {string} [selfUin]
246
+ */
247
+ export function groupFeatures(rows, selfUin = '') {
248
+ const ordered = [...rows].sort((left, right) => left.ts - right.ts)
249
+ const speakers = new Map()
250
+ for (const row of ordered) {
251
+ const uin = row.senderUin === '' ? 'unknown' : row.senderUin
252
+ const entry = speakers.get(uin) ?? { uin, names: new Map(), count: 0, chars: 0, questions: 0, decor: 0 }
253
+ entry.count += 1
254
+ entry.chars += String(row.text ?? '').length
255
+ if (isQuestion(row.text)) entry.questions += 1
256
+ entry.decor += decorationCount(row.text)
257
+ const name = String(row.senderName ?? '').trim()
258
+ if (name !== '') entry.names.set(name, (entry.names.get(name) ?? 0) + 1)
259
+ speakers.set(uin, entry)
260
+ }
261
+ const total = ordered.length
262
+ const ranked = [...speakers.values()]
263
+ .sort((left, right) => right.count - left.count)
264
+ .map(entry => ({
265
+ uin: entry.uin,
266
+ // The most frequent display name is the one the room actually uses.
267
+ name: [...entry.names.entries()].sort((left, right) => right[1] - left[1]).map(([name]) => name)[0] ?? '',
268
+ messages: entry.count,
269
+ share: total === 0 ? 0 : Math.round((entry.count / total) * 100) / 100,
270
+ avgChars: Math.round(entry.chars / Math.max(1, entry.count)),
271
+ questionRatio: Math.round((entry.questions / Math.max(1, entry.count)) * 100) / 100,
272
+ decorationPerMessage: Math.round((entry.decor / Math.max(1, entry.count)) * 100) / 100,
273
+ }))
274
+
275
+ // How crowded the room is: many speakers each saying a little, or a few loud ones.
276
+ const activeSpeakers = ranked.filter(entry => entry.messages >= 2).length
277
+ const topThreeShare = Math.round(ranked.slice(0, 3).reduce((sum, entry) => sum + entry.share, 0) * 100) / 100
278
+
279
+ const hours = Array.from({ length: 24 }, () => 0)
280
+ for (const row of ordered) hours[hourOf(row.ts)] += 1
281
+ const peakHours = hours
282
+ .map((count, hour) => ({ hour, count }))
283
+ .sort((left, right) => right.count - left.count)
284
+ .slice(0, 3)
285
+ .filter(entry => entry.count > 0)
286
+ .map(entry => entry.hour)
287
+
288
+ const activeDays = new Set(ordered.map(row => new Date(row.ts).toDateString())).size
289
+ const spanDays = ordered.length === 0
290
+ ? 0
291
+ : Math.max(1, Math.round((ordered[ordered.length - 1].ts - ordered[0].ts) / (24 * 60 * 60 * 1000)))
292
+
293
+ // Bursts: consecutive messages less than two minutes apart are one conversation.
294
+ let bursts = 0
295
+ let inBurst = false
296
+ let fastestGap = Number.POSITIVE_INFINITY
297
+ for (let index = 0; index < ordered.length; index += 1) {
298
+ const previous = ordered[index - 1]
299
+ if (previous === undefined) {
300
+ inBurst = false
301
+ continue
302
+ }
303
+ const gap = ordered[index].ts - previous.ts
304
+ if (gap > 2000 && gap < fastestGap) fastestGap = gap
305
+ if (gap <= 120000) {
306
+ if (!inBurst) {
307
+ bursts += 1
308
+ inBurst = true
309
+ }
310
+ } else {
311
+ inBurst = false
312
+ }
313
+ }
314
+
315
+ const textRows = ordered.filter(row => String(row.text ?? '').trim() !== '')
316
+ const links = textRows.filter(row => /https?:\/\//.test(row.text)).length
317
+ const atMe = selfUin === '' ? 0 : ordered.filter(row => String(row.text ?? '').includes(`@${selfUin}`)).length
318
+ const mineRows = selfUin === '' ? [] : ordered.filter(row => row.senderUin === selfUin)
319
+
320
+ return {
321
+ totalMessages: total,
322
+ activeSpeakers,
323
+ topThreeShare,
324
+ speakers: ranked.slice(0, 12),
325
+ myMessages: mineRows.length,
326
+ myShare: total === 0 ? 0 : Math.round((mineRows.length / total) * 100) / 100,
327
+ atMeMessages: atMe,
328
+ avgChars: mean(textRows.map(row => row.text.length)),
329
+ questionRatio: textRows.length === 0 ? 0 : Math.round((textRows.filter(row => isQuestion(row.text)).length / textRows.length) * 100) / 100,
330
+ decorationPerMessage: textRows.length === 0 ? 0 : Math.round((textRows.reduce((sum, row) => sum + decorationCount(row.text), 0) / textRows.length) * 100) / 100,
331
+ linkShare: textRows.length === 0 ? 0 : Math.round((links / textRows.length) * 100) / 100,
332
+ hourHistogram: hours,
333
+ peakHours,
334
+ activeDays,
335
+ spanDays,
336
+ messagesPerActiveDay: activeDays === 0 ? 0 : Math.round(total / activeDays),
337
+ bursts,
338
+ fastestReplySeconds: Number.isFinite(fastestGap) ? Math.round(fastestGap / 1000) : 0,
339
+ lastContactDays: ordered.length === 0 ? null : Math.round((Date.now() - ordered[ordered.length - 1].ts) / (24 * 60 * 60 * 1000)),
340
+ }
341
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Reply personas: the voice an automatic reply is written in.
3
+ *
4
+ * Only the default ships with the plugin: it imitates the user from their own
5
+ * transcripts. Every other voice is added by the user through the persona
6
+ * interface, so nothing in here needs to guess at a character they did not ask for.
7
+ */
8
+
9
+ /** Built-in presets. `prompt` is empty for the default: it uses the transcript. */
10
+ export const REPLY_PERSONAS = [
11
+ {
12
+ id: 'default',
13
+ name: '默认(像我本人)',
14
+ summary: '从你的聊天记录里学语气,回得像你自己。',
15
+ prompt: '',
16
+ },
17
+ ]
18
+
19
+ /** The preset with this id, or undefined. */
20
+ export function presetPersona(id) {
21
+ return REPLY_PERSONAS.find(entry => entry.id === id)
22
+ }
23
+
24
+ /**
25
+ * Normalize one custom persona from storage.
26
+ * @returns {{ id: string, name: string, prompt: string, custom: true } | undefined}
27
+ */
28
+ export function normalizeCustomPersona(raw) {
29
+ if (raw === null || typeof raw !== 'object') return undefined
30
+ const id = String(raw.id ?? '').trim()
31
+ const name = String(raw.name ?? '').trim().slice(0, 40)
32
+ const prompt = String(raw.prompt ?? '').trim().slice(0, 2000)
33
+ if (id === '' || name === '' || prompt === '') return undefined
34
+ return { id, name, prompt, custom: true, createdAt: typeof raw.createdAt === 'string' ? raw.createdAt : '' }
35
+ }
36
+
37
+ /** Every persona the picker should show: built-in presets first, then custom. */
38
+ export function listPersonas(custom = []) {
39
+ const presets = REPLY_PERSONAS.map(entry => ({ ...entry, custom: false }))
40
+ const extras = (Array.isArray(custom) ? custom : []).map(normalizeCustomPersona).filter(entry => entry !== undefined)
41
+ return [...presets, ...extras]
42
+ }
43
+
44
+ /**
45
+ * Resolve the persona to use for a reply.
46
+ *
47
+ * An unknown id (a deleted custom persona, or a hand-edited file) falls back to
48
+ * the default rather than failing: a reply in the user's own voice is always a
49
+ * sane answer.
50
+ */
51
+ export function resolvePersona(custom, id) {
52
+ const wanted = String(id ?? 'default')
53
+ return listPersonas(custom).find(entry => entry.id === wanted) ?? REPLY_PERSONAS[0]
54
+ }