dsh-qq-affinity 0.0.0-stage → 0.14.2
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/README.md +55 -2
- package/client.js +3550 -0
- package/cordis.patch.yml +6 -0
- package/docs/DETAIL.md +332 -0
- package/icon.svg +12 -0
- package/index.js +128 -0
- package/lib/analyze.js +777 -0
- package/lib/api.js +984 -0
- package/lib/backfill.js +146 -0
- package/lib/bridge-server.js +78 -0
- package/lib/care.js +240 -0
- package/lib/features.js +200 -0
- package/lib/home.js +168 -0
- package/lib/inbound.js +120 -0
- package/lib/llm.js +137 -0
- package/lib/media.js +161 -0
- package/lib/onebot.js +207 -0
- package/lib/parse.js +184 -0
- package/lib/recover.js +46 -0
- package/lib/store.js +705 -0
- package/lib/util.js +186 -0
- package/lib/vision.js +108 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +38 -4
- package/scripts/api-e2e.mjs +538 -0
- package/scripts/backfill-e2e.mjs +142 -0
- package/scripts/backfill-live.mjs +60 -0
- package/scripts/bridge-e2e.mjs +137 -0
- package/scripts/care-e2e.mjs +217 -0
- package/scripts/check-hook-order.mjs +83 -0
- package/scripts/make-napcat-config.mjs +87 -0
- package/scripts/media-e2e.mjs +103 -0
- package/scripts/recover-e2e.mjs +75 -0
- package/scripts/selftest.mjs +159 -0
- package/scripts/strip-bom.mjs +27 -0
package/lib/home.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the archive lives.
|
|
3
|
+
*
|
|
4
|
+
* The data directory used to be fixed by an environment variable. It is now a
|
|
5
|
+
* user setting, which creates one bootstrap problem: the setting cannot live in
|
|
6
|
+
* the data it points at. So a one-line pointer file stays at the default
|
|
7
|
+
* location and names the real directory.
|
|
8
|
+
*
|
|
9
|
+
* Resolution order, highest first:
|
|
10
|
+
* 1. `DSH_QQ_AFFINITY_HOME` — a deployment override; it wins and locks the UI.
|
|
11
|
+
* 2. `<default>/location.json` `directory` — what the panel set.
|
|
12
|
+
* 3. `<default>` — the shipped default.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import fs from 'node:fs'
|
|
16
|
+
import os from 'node:os'
|
|
17
|
+
import path from 'node:path'
|
|
18
|
+
import { readJson, writeJson } from './util.js'
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The fixed bootstrap directory, which also holds the pointer file.
|
|
22
|
+
* `DSH_QQ_AFFINITY_ROOT` moves the bootstrap directory itself; it exists so a
|
|
23
|
+
* test run never touches the real archive, and never rewrites its pointer.
|
|
24
|
+
*/
|
|
25
|
+
export function defaultRoot() {
|
|
26
|
+
const override = process.env.DSH_QQ_AFFINITY_ROOT
|
|
27
|
+
if (typeof override === 'string' && override.trim() !== '') return path.resolve(override.trim())
|
|
28
|
+
return path.join(os.homedir(), '.dsh', 'qq-affinity')
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const POINTER = 'location.json'
|
|
32
|
+
|
|
33
|
+
/** Entries that make up an archive. */
|
|
34
|
+
const ARCHIVE_ENTRIES = ['meta.json', 'messages', 'suggestions', 'outbox.ndjson']
|
|
35
|
+
|
|
36
|
+
/** The deployment override, when one is set. */
|
|
37
|
+
export function environmentOverride() {
|
|
38
|
+
const value = process.env.DSH_QQ_AFFINITY_HOME
|
|
39
|
+
return typeof value === 'string' && value.trim() !== '' ? path.resolve(value.trim()) : undefined
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Expand a leading `~` and resolve to an absolute path. */
|
|
43
|
+
export function expandPath(input) {
|
|
44
|
+
const text = String(input ?? '').trim()
|
|
45
|
+
if (text === '') throw new Error('路径不能为空。')
|
|
46
|
+
const expanded = text === '~' || text.startsWith('~/') || text.startsWith('~\\')
|
|
47
|
+
? path.join(os.homedir(), text.slice(1))
|
|
48
|
+
: text
|
|
49
|
+
if (!path.isAbsolute(expanded)) throw new Error('请填绝对路径,例如 D:\\QQ档案 或 ~/qq-affinity。')
|
|
50
|
+
return path.normalize(expanded)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Read the pointer file, tolerating a missing or corrupt one. */
|
|
54
|
+
function readPointer() {
|
|
55
|
+
const record = readJson(path.join(defaultRoot(), POINTER), null)
|
|
56
|
+
if (record === null || typeof record !== 'object') return undefined
|
|
57
|
+
if (typeof record.directory !== 'string' || record.directory.trim() === '') return undefined
|
|
58
|
+
try {
|
|
59
|
+
return path.normalize(record.directory)
|
|
60
|
+
} catch {
|
|
61
|
+
return undefined
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The directory a fresh Store should open. */
|
|
66
|
+
export function resolveDataDirectory() {
|
|
67
|
+
const override = environmentOverride()
|
|
68
|
+
if (override !== undefined) return override
|
|
69
|
+
return readPointer() ?? defaultRoot()
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Whether the panel may change the location at all. */
|
|
73
|
+
export function locationLocked() {
|
|
74
|
+
return environmentOverride() !== undefined
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The current location facts the panel shows. */
|
|
78
|
+
export function describeLocation(directory) {
|
|
79
|
+
const override = environmentOverride()
|
|
80
|
+
return {
|
|
81
|
+
directory,
|
|
82
|
+
defaultDirectory: defaultRoot(),
|
|
83
|
+
custom: directory !== defaultRoot(),
|
|
84
|
+
// An environment override wins over the pointer file, so in-app switching
|
|
85
|
+
// would silently do nothing; say so instead.
|
|
86
|
+
envLocked: override !== undefined,
|
|
87
|
+
envValue: override ?? '',
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Persist a new pointer, or drop it when the target is the default. */
|
|
92
|
+
function writePointer(directory) {
|
|
93
|
+
const file = path.join(defaultRoot(), POINTER)
|
|
94
|
+
if (directory === defaultRoot()) {
|
|
95
|
+
fs.rmSync(file, { force: true })
|
|
96
|
+
return
|
|
97
|
+
}
|
|
98
|
+
writeJson(file, { version: 1, directory, updatedAt: new Date().toISOString() })
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Whether a directory already holds an archive. */
|
|
102
|
+
export function hasArchive(directory) {
|
|
103
|
+
return fs.existsSync(path.join(directory, 'meta.json'))
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Copy the archive entries that exist from one directory to another. */
|
|
107
|
+
function copyArchive(from, to) {
|
|
108
|
+
fs.mkdirSync(to, { recursive: true })
|
|
109
|
+
let copied = 0
|
|
110
|
+
for (const entry of ARCHIVE_ENTRIES) {
|
|
111
|
+
const source = path.join(from, entry)
|
|
112
|
+
if (!fs.existsSync(source)) continue
|
|
113
|
+
fs.cpSync(source, path.join(to, entry), { recursive: true, force: true })
|
|
114
|
+
copied += 1
|
|
115
|
+
}
|
|
116
|
+
return copied
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Move the archive to another directory.
|
|
121
|
+
* @param {object} options
|
|
122
|
+
* @param {string} options.from - the directory in use now.
|
|
123
|
+
* @param {string} options.target - the requested directory, already expanded.
|
|
124
|
+
* @param {'migrate' | 'switch'} options.mode - copy the archive there, or just point at it.
|
|
125
|
+
* @param {boolean} [options.cleanup] - delete the old copies after a successful copy.
|
|
126
|
+
* @returns {{ directory: string, mode: string, copied: number, cleanup: boolean, previous: string }}
|
|
127
|
+
*/
|
|
128
|
+
export function relocate({ from, target, mode, cleanup = false }) {
|
|
129
|
+
if (locationLocked()) {
|
|
130
|
+
throw new Error('数据位置被环境变量 DSH_QQ_AFFINITY_HOME 固定住了,面板无法更改。想改就把那个变量去掉。')
|
|
131
|
+
}
|
|
132
|
+
if (target === from) throw new Error('这个位置就是当前使用的目录。')
|
|
133
|
+
if (target === path.parse(target).root) throw new Error('不能把档案放在磁盘根目录。')
|
|
134
|
+
|
|
135
|
+
fs.mkdirSync(target, { recursive: true })
|
|
136
|
+
if (!fs.statSync(target).isDirectory()) throw new Error('这个路径不是文件夹。')
|
|
137
|
+
|
|
138
|
+
if (mode === 'migrate') {
|
|
139
|
+
if (hasArchive(target)) {
|
|
140
|
+
throw new Error('目标位置已经有一份档案。想用那边的数据,请选「切换」;想覆盖,先把那边的 meta.json 移走。')
|
|
141
|
+
}
|
|
142
|
+
const copied = copyArchive(from, target)
|
|
143
|
+
if (!hasArchive(target)) throw new Error('复制没有完成:目标位置还看不到 meta.json,已保持原状。')
|
|
144
|
+
writePointer(target)
|
|
145
|
+
if (cleanup) {
|
|
146
|
+
for (const entry of ARCHIVE_ENTRIES) {
|
|
147
|
+
fs.rmSync(path.join(from, entry), { recursive: true, force: true })
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return { directory: target, mode: 'migrate', copied, cleanup, previous: from }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// Switching never copies: an existing archive there is adopted as-is, and an
|
|
154
|
+
// empty directory becomes a fresh archive.
|
|
155
|
+
const copied = 0
|
|
156
|
+
writePointer(target)
|
|
157
|
+
return { directory: target, mode: 'switch', copied, cleanup: false, previous: from }
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Point back at the shipped default location. */
|
|
161
|
+
export function resetLocation(from) {
|
|
162
|
+
if (locationLocked()) {
|
|
163
|
+
throw new Error('数据位置被环境变量 DSH_QQ_AFFINITY_HOME 固定住了,面板无法更改。')
|
|
164
|
+
}
|
|
165
|
+
writePointer(defaultRoot())
|
|
166
|
+
return { directory: defaultRoot(), mode: 'default', copied: 0, cleanup: false, previous: from }
|
|
167
|
+
}
|
|
168
|
+
|
package/lib/inbound.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The inbound half of the real-time bridge.
|
|
3
|
+
*
|
|
4
|
+
* Two carriers hand reports to the same handler:
|
|
5
|
+
* - a fixed loopback port the plugin listens on itself, so the address a bridge
|
|
6
|
+
* is configured with survives DSH restarts (DSH's own GUI port changes every
|
|
7
|
+
* launch);
|
|
8
|
+
* - the Harness web server's named route, as a fallback when that port is taken.
|
|
9
|
+
*
|
|
10
|
+
* This is the one surface a non-browser process is meant to reach, so it
|
|
11
|
+
* authenticates on its own: a shared token when one is configured, otherwise
|
|
12
|
+
* loopback only. It answers 204 before any model call — the bridge must never
|
|
13
|
+
* wait on the plugin.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { normalizeEvent } from './onebot.js'
|
|
17
|
+
|
|
18
|
+
const MAX_BODY_BYTES = 1 << 20
|
|
19
|
+
|
|
20
|
+
/** Whether a peer address is this machine. */
|
|
21
|
+
export function isLoopback(address) {
|
|
22
|
+
const value = String(address ?? '')
|
|
23
|
+
return value === '127.0.0.1'
|
|
24
|
+
|| value === '::1'
|
|
25
|
+
|| value === '::ffff:127.0.0.1'
|
|
26
|
+
|| value === 'localhost'
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The presented bearer token, from the header or the query string. */
|
|
30
|
+
function presentedToken(headers, url) {
|
|
31
|
+
const header = headers.authorization ?? headers.Authorization ?? ''
|
|
32
|
+
if (typeof header === 'string' && header.toLowerCase().startsWith('bearer ')) return header.slice(7).trim()
|
|
33
|
+
try {
|
|
34
|
+
return new URL(url ?? '/', 'http://dsh.invalid').searchParams.get('access_token') ?? ''
|
|
35
|
+
} catch {
|
|
36
|
+
return ''
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Build the carrier-independent report handler.
|
|
42
|
+
* @param {{ store: import('./store.js').Store, engine: object, ctx: object }} deps
|
|
43
|
+
* @returns {(request: { method: string, headers: Record<string, any>, url: string, remoteAddress?: string, readText: () => Promise<string> }) => Promise<{ status: number, body?: string }>}
|
|
44
|
+
*/
|
|
45
|
+
export function createReportHandler({ store, engine, ctx }) {
|
|
46
|
+
return async function handle(request) {
|
|
47
|
+
if (request.method !== 'POST') return { status: 405, body: 'POST only' }
|
|
48
|
+
if (store.state.settings.onebot.enabled !== true) return { status: 409, body: 'real-time channel is off' }
|
|
49
|
+
|
|
50
|
+
const expected = store.state.settings.onebot.inboundToken
|
|
51
|
+
if (typeof expected === 'string' && expected !== '') {
|
|
52
|
+
if (presentedToken(request.headers, request.url) !== expected) return { status: 401, body: 'bad token' }
|
|
53
|
+
} else if (!isLoopback(request.remoteAddress)) {
|
|
54
|
+
return { status: 403, body: 'loopback only without a token' }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
let payload
|
|
58
|
+
try {
|
|
59
|
+
payload = JSON.parse(await request.readText())
|
|
60
|
+
} catch {
|
|
61
|
+
return { status: 400, body: 'bad json' }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Anything that is not a chat message (heartbeats, notices) is acknowledged
|
|
65
|
+
// and dropped; the plugin records nothing about it.
|
|
66
|
+
if (payload === null || typeof payload !== 'object' || payload.post_type === 'meta_event') return { status: 204 }
|
|
67
|
+
|
|
68
|
+
try {
|
|
69
|
+
const event = normalizeEvent(payload, store.state.settings.selfUin)
|
|
70
|
+
if (event !== undefined) {
|
|
71
|
+
// The panel shows this to prove the bridge is actually reporting in.
|
|
72
|
+
store.state.settings.onebot.lastInboundAt = new Date().toISOString()
|
|
73
|
+
store.save()
|
|
74
|
+
void engine.enqueue(event)
|
|
75
|
+
}
|
|
76
|
+
} catch (error) {
|
|
77
|
+
ctx.logger?.warn?.(`qq-affinity: inbound event failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
78
|
+
}
|
|
79
|
+
return { status: 204 }
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Read a Node request body with a hard size bound. */
|
|
84
|
+
function readBody(req) {
|
|
85
|
+
return new Promise((resolve, reject) => {
|
|
86
|
+
const chunks = []
|
|
87
|
+
let total = 0
|
|
88
|
+
req.on('data', (chunk) => {
|
|
89
|
+
total += chunk.length
|
|
90
|
+
if (total > MAX_BODY_BYTES) {
|
|
91
|
+
reject(new Error('请求体过大。'))
|
|
92
|
+
req.destroy()
|
|
93
|
+
return
|
|
94
|
+
}
|
|
95
|
+
chunks.push(chunk)
|
|
96
|
+
})
|
|
97
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
|
|
98
|
+
req.on('error', reject)
|
|
99
|
+
})
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Adapt the report handler to a raw Node request/response pair, which both
|
|
104
|
+
* carriers provide.
|
|
105
|
+
* @returns {(req: any, res: any) => Promise<void>}
|
|
106
|
+
*/
|
|
107
|
+
export function createNodeHandler({ store, engine, ctx }) {
|
|
108
|
+
const handle = createReportHandler({ store, engine, ctx })
|
|
109
|
+
return async (req, res) => {
|
|
110
|
+
const result = await handle({
|
|
111
|
+
method: req.method ?? 'GET',
|
|
112
|
+
headers: req.headers ?? {},
|
|
113
|
+
url: req.url ?? '/',
|
|
114
|
+
remoteAddress: req.socket?.remoteAddress,
|
|
115
|
+
readText: () => readBody(req),
|
|
116
|
+
})
|
|
117
|
+
res.writeHead(result.status, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' })
|
|
118
|
+
res.end(result.body ?? '')
|
|
119
|
+
}
|
|
120
|
+
}
|
package/lib/llm.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model access for the plugin: resolve the deployment's default route and
|
|
3
|
+
* collect a single text answer, plus a tolerant JSON reader for the answers
|
|
4
|
+
* that must be structured.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** The provider/model route this plugin should call. */
|
|
8
|
+
export function resolveRoute(ctx) {
|
|
9
|
+
const defaultModel = ctx.get('agentDefaultModel')
|
|
10
|
+
if (defaultModel !== undefined) {
|
|
11
|
+
try {
|
|
12
|
+
const selection = defaultModel.currentSelection()
|
|
13
|
+
if (selection !== undefined && typeof selection.provider === 'string' && typeof selection.model === 'string') {
|
|
14
|
+
return { provider: selection.provider, model: selection.model }
|
|
15
|
+
}
|
|
16
|
+
} catch {
|
|
17
|
+
// Fall through to the provider catalogue.
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return undefined
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Fall back to the first registered provider and its first model. */
|
|
24
|
+
async function discoverRoute(ctx) {
|
|
25
|
+
const llm = ctx.get('llm')
|
|
26
|
+
if (llm === undefined) return undefined
|
|
27
|
+
const providers = llm.listProviders()
|
|
28
|
+
for (const provider of providers) {
|
|
29
|
+
try {
|
|
30
|
+
const models = await llm.listModels(provider.id)
|
|
31
|
+
if (models.length > 0) return { provider: provider.id, model: models[0].id }
|
|
32
|
+
} catch {
|
|
33
|
+
// Try the next provider.
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return undefined
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Resolve the route to use, preferring the deployment default.
|
|
41
|
+
* @returns {Promise<{ provider: string, model: string }>}
|
|
42
|
+
*/
|
|
43
|
+
export async function routeFor(ctx) {
|
|
44
|
+
const direct = resolveRoute(ctx)
|
|
45
|
+
if (direct !== undefined) return direct
|
|
46
|
+
const discovered = await discoverRoute(ctx)
|
|
47
|
+
if (discovered !== undefined) return discovered
|
|
48
|
+
throw new Error('没有可用的模型:请先在 DSH 里选择一个默认模型。')
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Run one non-streaming model call and return its text.
|
|
53
|
+
*
|
|
54
|
+
* A reasoning model spends part of `maxTokens` on its reasoning before it writes
|
|
55
|
+
* the answer, so a tight budget can arrive as an empty string. When that happens
|
|
56
|
+
* the call is retried once with a larger budget instead of failing the feature.
|
|
57
|
+
* @param {object} ctx - Cordis context.
|
|
58
|
+
* @param {object} request
|
|
59
|
+
* @param {string} request.system
|
|
60
|
+
* @param {string} request.prompt
|
|
61
|
+
* @param {Array<{ type: 'image', attachment: object }>} [request.images] - image blocks to send with the prompt.
|
|
62
|
+
* @param {number} [request.maxTokens]
|
|
63
|
+
* @param {number} [request.temperature]
|
|
64
|
+
* @param {AbortSignal} [request.signal]
|
|
65
|
+
* @param {string} [request.purpose]
|
|
66
|
+
* @returns {Promise<string>}
|
|
67
|
+
*/
|
|
68
|
+
export async function completeText(ctx, request) {
|
|
69
|
+
const llm = ctx.get('llm')
|
|
70
|
+
if (llm === undefined) throw new Error('模型服务不可用:当前 profile 没有加载 llm 服务。')
|
|
71
|
+
const route = await routeFor(ctx)
|
|
72
|
+
const budget = request.maxTokens ?? 1600
|
|
73
|
+
|
|
74
|
+
const attempt = async (maxTokens) => {
|
|
75
|
+
// Text first, then the images it refers to: adapters serialize in order and
|
|
76
|
+
// models read the instruction before they look.
|
|
77
|
+
const content = [{ type: 'text', text: request.prompt }]
|
|
78
|
+
if (Array.isArray(request.images)) {
|
|
79
|
+
for (const block of request.images) if (block?.type === 'image') content.push(block)
|
|
80
|
+
}
|
|
81
|
+
const stream = llm.stream({
|
|
82
|
+
provider: route.provider,
|
|
83
|
+
model: route.model,
|
|
84
|
+
system: request.system,
|
|
85
|
+
messages: [{ role: 'user', content }],
|
|
86
|
+
temperature: request.temperature ?? 0.4,
|
|
87
|
+
maxTokens,
|
|
88
|
+
signal: request.signal,
|
|
89
|
+
purpose: request.purpose ?? 'qq-affinity',
|
|
90
|
+
})
|
|
91
|
+
let text = ''
|
|
92
|
+
let finish = ''
|
|
93
|
+
for await (const chunk of stream) {
|
|
94
|
+
if (chunk.type === 'text-delta') text += chunk.text
|
|
95
|
+
else if (chunk.type === 'finish') {
|
|
96
|
+
finish = chunk.reason.kind
|
|
97
|
+
if (chunk.reason.kind === 'error') {
|
|
98
|
+
throw new Error(`模型调用失败:${chunk.reason.failure?.message ?? 'unknown error'}`)
|
|
99
|
+
}
|
|
100
|
+
if (chunk.reason.kind === 'aborted') throw new Error('模型调用已取消。')
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return { text: text.trim(), finish }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const first = await attempt(budget)
|
|
107
|
+
if (first.text !== '') return first.text
|
|
108
|
+
|
|
109
|
+
// Empty answer: almost always the reasoning side of the budget, not a refusal.
|
|
110
|
+
const retry = await attempt(Math.min(8000, budget * 3))
|
|
111
|
+
if (retry.text !== '') return retry.text
|
|
112
|
+
throw new Error(`模型返回了空内容(两次都空,finish=${retry.finish || 'unknown'})。可能是模型额度太小或该模型不支持这次请求。`)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Pull one JSON object out of a model answer that may wrap it in prose or fences.
|
|
117
|
+
* @returns {any}
|
|
118
|
+
* @throws {Error} when no parseable object is present.
|
|
119
|
+
*/
|
|
120
|
+
export function extractJson(text) {
|
|
121
|
+
const source = String(text ?? '')
|
|
122
|
+
const fenced = source.match(/```(?:json)?\s*([\s\S]*?)```/)
|
|
123
|
+
const body = fenced !== null ? fenced[1] : source
|
|
124
|
+
const start = body.indexOf('{')
|
|
125
|
+
const end = body.lastIndexOf('}')
|
|
126
|
+
if (start < 0 || end <= start) throw new Error('模型没有返回 JSON 对象。')
|
|
127
|
+
const slice = body.slice(start, end + 1)
|
|
128
|
+
try {
|
|
129
|
+
return JSON.parse(slice)
|
|
130
|
+
} catch {
|
|
131
|
+
// Trailing commas and smart quotes are common near-misses.
|
|
132
|
+
const repaired = slice
|
|
133
|
+
.replace(/[\u201c\u201d]/g, '"')
|
|
134
|
+
.replace(/,\s*([}\]])/g, '$1')
|
|
135
|
+
return JSON.parse(repaired)
|
|
136
|
+
}
|
|
137
|
+
}
|
package/lib/media.js
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
// Reading images and stickers out of QQ reports.
|
|
2
|
+
//
|
|
3
|
+
// Two inputs reach us: a CQ-code `raw_message` string (OneBot's string format)
|
|
4
|
+
// and a structured segment array (`messageFormat: 'array'`). Both carry image
|
|
5
|
+
// URLs. Nothing here downloads anything — it only names what was sent and where
|
|
6
|
+
// the bytes live, so the rest of the plugin can decide whether to look.
|
|
7
|
+
|
|
8
|
+
/** Classic QQ face ids, in the order QQ defines them. Names, not emoji: the
|
|
9
|
+
* model reads `[表情:微笑]` more reliably than a pictograph it must classify. */
|
|
10
|
+
const FACE_NAMES = [
|
|
11
|
+
'微笑', '撇嘴', '色', '发呆', '得意', '流泪', '害羞', '闭嘴', '睡', '大哭',
|
|
12
|
+
'尴尬', '发怒', '调皮', '呲牙', '惊讶', '难过', '酷', '冷汗', '抓狂', '吐',
|
|
13
|
+
'偷笑', '可爱', '白眼', '傲慢', '饥饿', '困', '惊恐', '流汗', '憨笑', '悠闲',
|
|
14
|
+
'奋斗', '咒骂', '疑问', '嘘', '晕', '疯了', '衰', '骷髅', '敲打', '再见',
|
|
15
|
+
'擦汗', '抠鼻', '鼓掌', '糗大了', '坏笑', '左哼哼', '右哼哼', '哈欠', '鄙视', '委屈',
|
|
16
|
+
'快哭了', '阴险', '亲亲', '吓', '可怜', '菜刀', '西瓜', '啤酒', '篮球', '乒乓',
|
|
17
|
+
'咖啡', '饭', '猪头', '玫瑰', '凋谢', '示爱', '爱心', '心碎', '蛋糕', '闪电',
|
|
18
|
+
'炸弹', '刀', '足球', '瓢虫', '便便', '月亮', '太阳', '礼物', '拥抱', '强',
|
|
19
|
+
'弱', '握手', '胜利', '抱拳', '勾引', '拳头', '差劲', '爱你', 'NO', 'OK',
|
|
20
|
+
'爱情', '飞吻', '跳跳', '发抖', '怄火', '转圈', '磕头', '回头', '跳绳', '挥手',
|
|
21
|
+
'激动', '街舞', '献吻', '左太极', '右太极',
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
/** Chinese name of one classic face id, or an empty string when unknown. */
|
|
25
|
+
export function faceName(id) {
|
|
26
|
+
const index = Number(id)
|
|
27
|
+
if (!Number.isFinite(index) || index < 0 || index >= FACE_NAMES.length) return ''
|
|
28
|
+
return FACE_NAMES[Math.floor(index)]
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** One character for the handful of faces that have an exact emoji. */
|
|
32
|
+
const FACE_EMOJI = { 0: '🙂', 5: '😭', 9: '😭', 13: '😁', 14: '😮', 18: '😫', 20: '🤭', 25: '😴', 27: '😅', 28: '😄', 63: '🌹', 66: '❤️', 67: '💔', 74: '💩', 76: '☀️', 77: '🎁', 79: '👍', 82: '✌️', 88: '🙅', 89: '🙆' }
|
|
33
|
+
|
|
34
|
+
/** Decode the CQ escaping (`,` is a comma inside a parameter value). */
|
|
35
|
+
function unescapeCq(value) {
|
|
36
|
+
return value.replace(/,/g, ',').replace(/&/g, '&').replace(/[/g, '[').replace(/]/g, ']')
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Parse `[CQ:image,...]` / `[CQ:face,id=..]` parameters into an object. */
|
|
40
|
+
function cqParams(body) {
|
|
41
|
+
const params = {}
|
|
42
|
+
for (const part of body.split(',')) {
|
|
43
|
+
const at = part.indexOf('=')
|
|
44
|
+
if (at < 0) continue
|
|
45
|
+
params[part.slice(0, at)] = unescapeCq(part.slice(at + 1))
|
|
46
|
+
}
|
|
47
|
+
return params
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Whether one image segment is a sticker rather than a photo.
|
|
52
|
+
* Bridges disagree on the field, so every spelling is checked.
|
|
53
|
+
*/
|
|
54
|
+
function isSticker(params) {
|
|
55
|
+
if (String(params.subType ?? params.sub_type ?? '') === '1') return true
|
|
56
|
+
const summary = String(params.summary ?? '')
|
|
57
|
+
return /表情|动画表情| sticker/i.test(summary)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Extract what a message contains: readable text plus the images it carried.
|
|
62
|
+
* @param {string} raw - CQ-code message text.
|
|
63
|
+
* @param {Array<any>} [segments] - OneBot array-format segments, when present.
|
|
64
|
+
* @returns {{ text: string, images: Array<{ url: string, kind: 'image' | 'sticker', summary: string }> }}
|
|
65
|
+
*/
|
|
66
|
+
export function extractMedia(raw, segments) {
|
|
67
|
+
const images = []
|
|
68
|
+
const pushImage = (params, summaryText) => {
|
|
69
|
+
const url = String(params.url ?? params.file ?? '')
|
|
70
|
+
if (url === '') return
|
|
71
|
+
images.push({
|
|
72
|
+
url,
|
|
73
|
+
kind: isSticker(params) ? 'sticker' : 'image',
|
|
74
|
+
summary: String(summaryText ?? params.summary ?? '').slice(0, 60),
|
|
75
|
+
})
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Structured segments win when the bridge sends them: no escaping to undo.
|
|
79
|
+
if (Array.isArray(segments) && segments.length > 0) {
|
|
80
|
+
const parts = []
|
|
81
|
+
for (const segment of segments) {
|
|
82
|
+
if (segment === null || typeof segment !== 'object') continue
|
|
83
|
+
const data = segment.data ?? {}
|
|
84
|
+
if (segment.type === 'text') {
|
|
85
|
+
parts.push(String(data.text ?? ''))
|
|
86
|
+
continue
|
|
87
|
+
}
|
|
88
|
+
if (segment.type === 'image') {
|
|
89
|
+
pushImage(data)
|
|
90
|
+
parts.push(isSticker(data) ? '[表情包]' : '[图片]')
|
|
91
|
+
continue
|
|
92
|
+
}
|
|
93
|
+
if (segment.type === 'face') {
|
|
94
|
+
const name = faceName(data.id)
|
|
95
|
+
parts.push(name === '' ? '[表情]' : `[表情:${name}]`)
|
|
96
|
+
continue
|
|
97
|
+
}
|
|
98
|
+
if (segment.type === 'mface') {
|
|
99
|
+
// A marketplace sticker: its `summary` is the label QQ shows.
|
|
100
|
+
images.push({
|
|
101
|
+
url: String(data.url ?? ''),
|
|
102
|
+
kind: 'sticker',
|
|
103
|
+
summary: String(data.summary ?? '').slice(0, 60),
|
|
104
|
+
})
|
|
105
|
+
parts.push(data.summary === undefined ? '[表情包]' : `[表情包:${String(data.summary).slice(0, 20)}]`)
|
|
106
|
+
continue
|
|
107
|
+
}
|
|
108
|
+
if (segment.type === 'at') {
|
|
109
|
+
parts.push(`@${String(data.qq ?? data.name ?? '')}`)
|
|
110
|
+
continue
|
|
111
|
+
}
|
|
112
|
+
if (segment.type === 'reply') continue
|
|
113
|
+
parts.push(`[${String(segment.type)}]`)
|
|
114
|
+
}
|
|
115
|
+
return { text: parts.join('').replace(/\s+/g, ' ').trim(), images }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const source = typeof raw === 'string' ? raw : ''
|
|
119
|
+
let text = ''
|
|
120
|
+
let index = 0
|
|
121
|
+
while (index < source.length) {
|
|
122
|
+
const at = source.indexOf('[CQ:', index)
|
|
123
|
+
if (at < 0) {
|
|
124
|
+
text += source.slice(index)
|
|
125
|
+
break
|
|
126
|
+
}
|
|
127
|
+
text += source.slice(index, at)
|
|
128
|
+
const end = source.indexOf(']', at)
|
|
129
|
+
if (end < 0) {
|
|
130
|
+
text += source.slice(at)
|
|
131
|
+
break
|
|
132
|
+
}
|
|
133
|
+
const body = source.slice(at + 4, end)
|
|
134
|
+
const comma = body.indexOf(',')
|
|
135
|
+
const type = comma < 0 ? body : body.slice(0, comma)
|
|
136
|
+
const params = comma < 0 ? {} : cqParams(body.slice(comma + 1))
|
|
137
|
+
if (type === 'image') {
|
|
138
|
+
pushImage(params)
|
|
139
|
+
text += isSticker(params) ? '[表情包]' : '[图片]'
|
|
140
|
+
} else if (type === 'face') {
|
|
141
|
+
const name = faceName(params.id)
|
|
142
|
+
text += name === '' ? '[表情]' : `[表情:${name}]`
|
|
143
|
+
} else if (type === 'mface') {
|
|
144
|
+
images.push({ url: String(params.url ?? ''), kind: 'sticker', summary: String(params.summary ?? '').slice(0, 60) })
|
|
145
|
+
text += params.summary === undefined ? '[表情包]' : `[表情包:${params.summary.slice(0, 20)}]`
|
|
146
|
+
} else if (type === 'at') {
|
|
147
|
+
text += `@${params.qq ?? ''}`
|
|
148
|
+
} else if (type === 'reply') {
|
|
149
|
+
// Quoted message id only; no text to keep.
|
|
150
|
+
} else {
|
|
151
|
+
text += `[${type}]`
|
|
152
|
+
}
|
|
153
|
+
index = end + 1
|
|
154
|
+
}
|
|
155
|
+
return { text: text.replace(/\s+/g, ' ').trim(), images }
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** The emoji for a face id when one exists (used by the panel to render). */
|
|
159
|
+
export function faceEmoji(id) {
|
|
160
|
+
return FACE_EMOJI[Number(id)] ?? ''
|
|
161
|
+
}
|