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.
@@ -0,0 +1,161 @@
1
+ // Reply personas: the built-in presets, the open "add your own" interface, and
2
+ // the fact that a persona actually changes the prompt the model sees.
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+ import { fileURLToPath, pathToFileURL } from 'node:url'
7
+
8
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
9
+ const href = (rel) => pathToFileURL(path.join(root, rel)).href
10
+ const { Store } = await import(href('lib/store.js'))
11
+ const { REPLY_PERSONAS, listPersonas, resolvePersona, presetPersona } = await import(href('lib/personas.js'))
12
+ const { writeAutoReply } = await import(href('lib/analyze.js'))
13
+ const { createRoutes } = await import(href('lib/api.js'))
14
+
15
+ let failures = 0
16
+ const check = (label, ok, extra = '') => {
17
+ console.log(` ${ok ? 'ok ' : 'FAIL'} ${label}${extra === '' ? '' : ` :: ${extra}`}`)
18
+ if (!ok) failures += 1
19
+ }
20
+
21
+ const prompts = []
22
+ function makeCtx() {
23
+ return {
24
+ get(name) {
25
+ if (name === 'agentDefaultModel') return { currentSelection: () => ({ provider: 'stub', model: 'stub-flash' }) }
26
+ if (name === 'llm') {
27
+ return {
28
+ stream(options) {
29
+ prompts.push(options.messages?.[0]?.content?.[0]?.text ?? '')
30
+ const text = '好的前辈 我马上确认一下参数'
31
+ return (async function* () {
32
+ yield { type: 'text-delta', index: 0, text }
33
+ yield { type: 'usage', usage: { inputTokens: 900, outputTokens: 40 } }
34
+ yield { type: 'finish', reason: { kind: 'stop' } }
35
+ })()
36
+ },
37
+ listProviders: () => [{ id: 'stub' }],
38
+ listModels: async () => [{ id: 'stub-flash' }],
39
+ resolveModelInfo: async () => ({ inputModalities: ['text'] }),
40
+ }
41
+ }
42
+ return undefined
43
+ },
44
+ }
45
+ }
46
+
47
+ console.log('\n== the built-ins ==')
48
+ check('only the default ships', REPLY_PERSONAS.length === 1, `${REPLY_PERSONAS.length}`)
49
+ check('the default imitates me', presetPersona('default').prompt === '', `"${presetPersona('default').prompt}"`)
50
+ check('小莫宁 is not built in any more', presetPersona('moning') === undefined)
51
+ check('弗洛洛 is not built in any more', presetPersona('fuluoluo') === undefined)
52
+ check('presets are listed before custom ones', listPersonas([{ id: 'custom-1', name: '我的', prompt: '直白' }]).length === 2, 'ok')
53
+ check('a custom persona can use a character name', listPersonas([{ id: 'custom-2', name: '小莫宁', prompt: '一口一个前辈' }])[1].name === '小莫宁')
54
+
55
+ console.log('\n== resolving a persona ==')
56
+ check('the default resolves', resolvePersona([], 'default').id === 'default')
57
+ check('a removed preset falls back to default', resolvePersona([], 'moning').id === 'default', resolvePersona([], 'moning').id)
58
+ check('an unknown id falls back to default', resolvePersona([], 'nope').id === 'default', resolvePersona([], 'nope').id)
59
+ check('a custom persona resolves', resolvePersona([{ id: 'custom-7', name: '老王', prompt: '直白' }], 'custom-7').name === '老王')
60
+ check('an empty stored list is fine', resolvePersona(undefined, undefined).id === 'default')
61
+
62
+ // ------------------------------------------------------------------- archive
63
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'qq-affinity-persona-'))
64
+ process.env.DSH_QQ_AFFINITY_HOME = dir
65
+ const store = new Store(dir)
66
+ store.state.settings.selfUin = '20002'
67
+ store.state.settings.selfName = '我'
68
+ const chat = store.ensureConversation({ kind: 'c2c', title: '小明', peerUin: '10001' }).conversation
69
+ store.setEnabled(chat.id, true)
70
+ store.appendMessages(chat.id, [
71
+ { ts: 1700000000000, senderUin: '10001', senderName: '小明', text: '在吗' },
72
+ { ts: 1700000060000, senderUin: '20002', senderName: '我', text: '在' },
73
+ { ts: 1700000120000, senderUin: '10001', senderName: '小明', text: '那个参数你看了吗' },
74
+ ])
75
+
76
+ console.log('\n== a persona changes the prompt ==')
77
+ const ctx = makeCtx()
78
+ // Only the default ships now, so a character voice has to be added first.
79
+ const voice = store.addReplyPersona({
80
+ name: '小莫宁',
81
+ prompt: '称呼对方为「前辈」,语气礼貌认真,先给结论再补依据,偶尔卡一下用省略号。',
82
+ })
83
+ store.setCare('10001', { persona: voice.id })
84
+ check('setCare keeps the persona', store.state.care['10001'].persona === voice.id, store.state.care['10001'].persona)
85
+ const inCharacter = await writeAutoReply(ctx, store, { conversationId: chat.id, uin: '10001', maxChars: 60 })
86
+ check('the reply still comes back as text', typeof inCharacter === 'string' && inCharacter !== '', inCharacter)
87
+ check('the prompt carries the persona block', prompts[prompts.length - 1].includes('【说话人设】'), prompts[prompts.length - 1].slice(0, 80))
88
+ check('the prompt names the character', prompts[prompts.length - 1].includes('小莫宁'), 'ok')
89
+ check('the transcript is marked as reference only', prompts[prompts.length - 1].includes('不要模仿我的语气'), 'ok')
90
+
91
+ store.setCare('10001', { persona: 'default' })
92
+ await writeAutoReply(ctx, store, { conversationId: chat.id, uin: '10001', maxChars: 60 })
93
+ check('the default persona has no persona block', !prompts[prompts.length - 1].includes('【说话人设】'), 'ok')
94
+ check('the default keeps my own voice', prompts[prompts.length - 1].includes('以我的身份'), 'ok')
95
+
96
+ console.log('\n== adding a custom persona through the store ==')
97
+ const beforeAdd = store.customPersonas().length
98
+ const added = store.addReplyPersona({ name: '隔壁老王', prompt: '说话直白,爱用短句,习惯反问。' })
99
+ check('it gets a custom id', added !== undefined && added.id.startsWith('custom-'), JSON.stringify(added?.id))
100
+ check('an empty draft is refused', store.addReplyPersona({ name: '', prompt: 'x' }) === undefined)
101
+ const second = store.addReplyPersona({ name: '二号', prompt: '温和一点' })
102
+ check('ids do not collide', second.id !== added.id, `${added.id} / ${second.id}`)
103
+ check('both are listed', store.customPersonas().length === beforeAdd + 2, `${store.customPersonas().length}`)
104
+ check('the picker lists one preset plus the customs', listPersonas(store.customPersonas()).length === beforeAdd + 3, `${listPersonas(store.customPersonas()).length}`)
105
+ check('removing one works', store.removeReplyPersona(added.id) === true && store.customPersonas().length === beforeAdd + 1)
106
+ check('removing an unknown id is refused', store.removeReplyPersona('custom-999') === false)
107
+
108
+ console.log('\n== the API interface ==')
109
+ const routes = createRoutes(ctx, store, undefined, undefined, {})
110
+ const byPath = new Map()
111
+ for (const route of routes) {
112
+ const entry = byPath.get(route.path) ?? {}
113
+ entry[route.method] = route
114
+ byPath.set(route.path, entry)
115
+ }
116
+ const call = async (routePath, { method = 'GET', body } = {}) => {
117
+ const route = byPath.get(routePath)?.[method]
118
+ if (route === undefined) throw new Error(`missing route ${routePath} [${method}]`)
119
+ const init = { method, headers: {} }
120
+ if (body !== undefined) {
121
+ init.headers['content-type'] = 'application/json'
122
+ init.body = JSON.stringify(body)
123
+ }
124
+ const response = await route.fetch(new Request(`http://localhost${routePath}`, init))
125
+ return { status: response.status, value: await response.json() }
126
+ }
127
+
128
+ let result = await call('/api/qq-affinity/state')
129
+ check('state lists the picker options', (result.value.replyPersonas ?? []).length === 3, `${(result.value.replyPersonas ?? []).length}`)
130
+ check('state marks which are custom', result.value.replyPersonas.some(entry => entry.custom === true))
131
+ check('no removed preset survives in the picker', !result.value.replyPersonas.some(entry => entry.id === 'moning' || entry.id === 'fuluoluo'))
132
+
133
+ result = await call('/api/qq-affinity/personas', { method: 'POST', body: { action: 'add', name: '测试人设', prompt: '只回短句' } })
134
+ check('add works', result.value.ok === true && result.value.persona.name === '测试人设', JSON.stringify(result.value.persona))
135
+ check('the response returns the whole list', result.value.personas.length === 4, `${result.value.personas.length}`)
136
+ const newId = result.value.persona.id
137
+
138
+ result = await call('/api/qq-affinity/personas', { method: 'POST', body: { action: 'add', name: '', prompt: 'x' } })
139
+ check('an empty name is refused', result.status === 400, `${result.status}`)
140
+
141
+ // Point someone at the new persona, then delete it: they must fall back.
142
+ await call('/api/qq-affinity/care', { method: 'POST', body: { uin: '10001', patch: { persona: newId } } })
143
+ check('care accepts the custom persona', store.state.care['10001'].persona === newId, store.state.care['10001'].persona)
144
+ result = await call('/api/qq-affinity/personas', { method: 'POST', body: { action: 'delete', id: newId } })
145
+ check('delete works', result.value.ok === true && result.value.personas.length === 3, JSON.stringify(result.value.resetTo))
146
+ check('whoever used it fell back to default', store.state.care['10001'].persona === 'default', store.state.care['10001'].persona)
147
+
148
+ result = await call('/api/qq-affinity/personas', { method: 'POST', body: { action: 'delete', id: 'default' } })
149
+ check('a built-in cannot be deleted', result.status === 409, `${result.status}`)
150
+
151
+ result = await call('/api/qq-affinity/personas', { method: 'POST', body: { action: 'delete', id: 'custom-404' } })
152
+ check('an unknown custom id is 404', result.status === 404, `${result.status}`)
153
+
154
+ console.log('\n== a persona survives a reload ==')
155
+ const reloaded = new Store(dir)
156
+ check('the stored persona is read back', reloaded.state.care['10001'].persona === 'default', reloaded.state.care['10001'].persona)
157
+ check('the custom persona list is read back', reloaded.customPersonas().length === 2, `${reloaded.customPersonas().length}`)
158
+
159
+ console.log(failures === 0 ? '\nALL PASS' : `\n${failures} FAILURE(S)`)
160
+ fs.rmSync(dir, { recursive: true, force: true })
161
+ process.exit(failures === 0 ? 0 : 1)