dsh-qqbot-plus 0.0.0-stage → 0.1.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/CHANGELOG.md +188 -0
- package/CHANGELOG_EN.md +188 -0
- package/LICENSE +21 -0
- package/README.md +281 -2
- package/README_EN.md +248 -0
- package/cordis.patch.yml +163 -0
- package/cordis.yml +112 -0
- package/install.sh +108 -0
- package/lib/alarms.js +371 -0
- package/lib/client.js +2411 -0
- package/lib/commands/auth.d.ts +18 -0
- package/lib/commands/auth.d.ts.map +1 -0
- package/lib/commands/auth.js +15 -0
- package/lib/commands/auth.js.map +1 -0
- package/lib/commands/help.d.ts +10 -0
- package/lib/commands/help.d.ts.map +1 -0
- package/lib/commands/help.js +39 -0
- package/lib/commands/help.js.map +1 -0
- package/lib/commands/index.d.ts +15 -0
- package/lib/commands/index.d.ts.map +1 -0
- package/lib/commands/index.js +30 -0
- package/lib/commands/index.js.map +1 -0
- package/lib/commands/misc.d.ts +21 -0
- package/lib/commands/misc.d.ts.map +1 -0
- package/lib/commands/misc.js +93 -0
- package/lib/commands/misc.js.map +1 -0
- package/lib/commands/model.d.ts +6 -0
- package/lib/commands/model.d.ts.map +1 -0
- package/lib/commands/model.js +63 -0
- package/lib/commands/model.js.map +1 -0
- package/lib/commands/new.js +17 -0
- package/lib/commands/preset.d.ts +8 -0
- package/lib/commands/preset.d.ts.map +1 -0
- package/lib/commands/preset.js +56 -0
- package/lib/commands/preset.js.map +1 -0
- package/lib/commands/session.d.ts +14 -0
- package/lib/commands/session.d.ts.map +1 -0
- package/lib/commands/session.js +34 -0
- package/lib/commands/session.js.map +1 -0
- package/lib/commands/status.d.ts +7 -0
- package/lib/commands/status.d.ts.map +1 -0
- package/lib/commands/status.js +26 -0
- package/lib/commands/status.js.map +1 -0
- package/lib/commands/types.d.ts +21 -0
- package/lib/commands/types.d.ts.map +1 -0
- package/lib/commands/types.js +2 -0
- package/lib/commands/types.js.map +1 -0
- package/lib/config.d.ts +95 -0
- package/lib/config.js +88 -0
- package/lib/features/answer-parser.d.ts +9 -0
- package/lib/features/answer-parser.d.ts.map +1 -0
- package/lib/features/answer-parser.js +23 -0
- package/lib/features/answer-parser.js.map +1 -0
- package/lib/features/approval-channel.d.ts +94 -0
- package/lib/features/approval-channel.d.ts.map +1 -0
- package/lib/features/approval-channel.js +158 -0
- package/lib/features/approval-channel.js.map +1 -0
- package/lib/features/approval-renderer.d.ts +18 -0
- package/lib/features/approval-renderer.d.ts.map +1 -0
- package/lib/features/approval-renderer.js +52 -0
- package/lib/features/approval-renderer.js.map +1 -0
- package/lib/features/button-utils.d.ts +34 -0
- package/lib/features/button-utils.d.ts.map +1 -0
- package/lib/features/button-utils.js +27 -0
- package/lib/features/button-utils.js.map +1 -0
- package/lib/features/history-store.d.ts +8 -0
- package/lib/features/history-store.d.ts.map +1 -0
- package/lib/features/history-store.js +23 -0
- package/lib/features/history-store.js.map +1 -0
- package/lib/features/question-channel.d.ts +96 -0
- package/lib/features/question-channel.d.ts.map +1 -0
- package/lib/features/question-channel.js +234 -0
- package/lib/features/question-channel.js.map +1 -0
- package/lib/features/question-renderer.d.ts +20 -0
- package/lib/features/question-renderer.d.ts.map +1 -0
- package/lib/features/question-renderer.js +70 -0
- package/lib/features/question-renderer.js.map +1 -0
- package/lib/fishcheck/measure.js +230 -0
- package/lib/fishcheck/rules.js +99 -0
- package/lib/fishmeme/plugin.js +605 -0
- package/lib/fishmeme/routes.js +141 -0
- package/lib/fishmemory/plugin.js +1052 -0
- package/lib/gateway/bootstrap.d.ts +12 -0
- package/lib/gateway/bootstrap.d.ts.map +1 -0
- package/lib/gateway/bootstrap.js +200 -0
- package/lib/gateway/bootstrap.js.map +1 -0
- package/lib/gateway/index.d.ts +3 -0
- package/lib/gateway/index.d.ts.map +1 -0
- package/lib/gateway/index.js +3 -0
- package/lib/gateway/index.js.map +1 -0
- package/lib/gateway/middleware-setup.d.ts +12 -0
- package/lib/gateway/middleware-setup.d.ts.map +1 -0
- package/lib/gateway/middleware-setup.js +82 -0
- package/lib/gateway/middleware-setup.js.map +1 -0
- package/lib/host/adapter.d.ts +48 -0
- package/lib/host/adapter.d.ts.map +1 -0
- package/lib/host/adapter.js +127 -0
- package/lib/host/adapter.js.map +1 -0
- package/lib/humanlike/ENV_PROMPT.md +28 -0
- package/lib/humanlike/affinity.js +316 -0
- package/lib/humanlike/learn.js +343 -0
- package/lib/humanlike/life.js +899 -0
- package/lib/humanlike/mind.js +323 -0
- package/lib/humanlike/plugin.js +587 -0
- package/lib/humanlike/reach.js +119 -0
- package/lib/humanlike/real.js +276 -0
- package/lib/humanlike/rules.js +67 -0
- package/lib/humanlike/settings-api.js +159 -0
- package/lib/humanlike/settings.js +370 -0
- package/lib/humanlike/together.js +251 -0
- package/lib/identity/paths.js +27 -0
- package/lib/identity/persona.js +75 -0
- package/lib/identity/portrait.js +25 -0
- package/lib/identity/runtime.js +78 -0
- package/lib/index.d.ts +15 -0
- package/lib/index.js +117 -0
- package/lib/media/draft-tool.js +442 -0
- package/lib/media/draft-tool.js.bak-to-182027 +389 -0
- package/lib/media/media-cleaner.d.ts +19 -0
- package/lib/media/media-cleaner.d.ts.map +1 -0
- package/lib/media/media-cleaner.js +81 -0
- package/lib/media/media-cleaner.js.map +1 -0
- package/lib/media/say-tool.js +72 -0
- package/lib/media/send-file-tool.d.ts +12 -0
- package/lib/media/send-file-tool.d.ts.map +1 -0
- package/lib/media/send-file-tool.js +122 -0
- package/lib/media/send-file-tool.js.map +1 -0
- package/lib/media/send-media.d.ts +61 -0
- package/lib/media/send-media.d.ts.map +1 -0
- package/lib/media/send-media.js +104 -0
- package/lib/media/send-media.js.map +1 -0
- package/lib/media/vision-tool.d.ts +22 -0
- package/lib/media/vision-tool.d.ts.map +1 -0
- package/lib/media/vision-tool.js +288 -0
- package/lib/media/vision-tool.js.map +1 -0
- package/lib/middleware/attachment.d.ts +11 -0
- package/lib/middleware/attachment.d.ts.map +1 -0
- package/lib/middleware/attachment.js +30 -0
- package/lib/middleware/attachment.js.map +1 -0
- package/lib/middleware/question-answer.d.ts +10 -0
- package/lib/middleware/question-answer.d.ts.map +1 -0
- package/lib/middleware/question-answer.js +19 -0
- package/lib/middleware/question-answer.js.map +1 -0
- package/lib/model/index.d.ts +10 -0
- package/lib/model/index.d.ts.map +1 -0
- package/lib/model/index.js +9 -0
- package/lib/model/index.js.map +1 -0
- package/lib/model/model-resolver.d.ts +102 -0
- package/lib/model/model-resolver.d.ts.map +1 -0
- package/lib/model/model-resolver.js +206 -0
- package/lib/model/model-resolver.js.map +1 -0
- package/lib/model/prefs-store.d.ts +50 -0
- package/lib/model/prefs-store.d.ts.map +1 -0
- package/lib/model/prefs-store.js +215 -0
- package/lib/model/prefs-store.js.map +1 -0
- package/lib/model/settings-reader.d.ts +19 -0
- package/lib/model/settings-reader.d.ts.map +1 -0
- package/lib/model/settings-reader.js +76 -0
- package/lib/model/settings-reader.js.map +1 -0
- package/lib/model/types.d.ts +15 -0
- package/lib/model/types.d.ts.map +1 -0
- package/lib/model/types.js +5 -0
- package/lib/model/types.js.map +1 -0
- package/lib/resume-check.js +122 -0
- package/lib/resume-tool.js +29 -0
- package/lib/rules.js +57 -0
- package/lib/session/idle-evictor.d.ts +18 -0
- package/lib/session/idle-evictor.d.ts.map +1 -0
- package/lib/session/idle-evictor.js +31 -0
- package/lib/session/idle-evictor.js.map +1 -0
- package/lib/session/index.d.ts +9 -0
- package/lib/session/index.d.ts.map +1 -0
- package/lib/session/index.js +8 -0
- package/lib/session/index.js.map +1 -0
- package/lib/session/pick-agent.js +116 -0
- package/lib/session/session-id.d.ts +5 -0
- package/lib/session/session-id.d.ts.map +1 -0
- package/lib/session/session-id.js +15 -0
- package/lib/session/session-id.js.map +1 -0
- package/lib/session/session-manager.d.ts +138 -0
- package/lib/session/session-manager.d.ts.map +1 -0
- package/lib/session/session-manager.js +1157 -0
- package/lib/session/session-manager.js.bak-target +1081 -0
- package/lib/session/session-manager.js.bak-title-20261118 +1119 -0
- package/lib/session/session-manager.js.map +1 -0
- package/lib/session/types.d.ts +162 -0
- package/lib/session/types.d.ts.map +1 -0
- package/lib/session/types.js +2 -0
- package/lib/session/types.js.map +1 -0
- package/lib/setup/bind-routes.d.ts +78 -0
- package/lib/setup/bind-routes.d.ts.map +1 -0
- package/lib/setup/bind-routes.js +588 -0
- package/lib/setup/bind-routes.js.bak-join-163944 +761 -0
- package/lib/setup/bind-routes.js.map +1 -0
- package/lib/setup/binding-service.d.ts +86 -0
- package/lib/setup/binding-service.d.ts.map +1 -0
- package/lib/setup/binding-service.js +175 -0
- package/lib/setup/binding-service.js.map +1 -0
- package/lib/setup/index.d.ts +50 -0
- package/lib/setup/index.d.ts.map +1 -0
- package/lib/setup/index.js +163 -0
- package/lib/setup/index.js.map +1 -0
- package/lib/setup/persist.d.ts +42 -0
- package/lib/setup/persist.d.ts.map +1 -0
- package/lib/setup/persist.js +344 -0
- package/lib/setup/persist.js.map +1 -0
- package/lib/setup/presenters.d.ts +40 -0
- package/lib/setup/presenters.d.ts.map +1 -0
- package/lib/setup/presenters.js +84 -0
- package/lib/setup/presenters.js.map +1 -0
- package/lib/setup/qr-svg.d.ts +9 -0
- package/lib/setup/qr-svg.d.ts.map +1 -0
- package/lib/setup/qr-svg.js +33 -0
- package/lib/setup/qr-svg.js.map +1 -0
- package/lib/shared/bind-protocol.d.ts +42 -0
- package/lib/shared/bind-protocol.d.ts.map +1 -0
- package/lib/shared/bind-protocol.js +33 -0
- package/lib/shared/bind-protocol.js.map +1 -0
- package/lib/shared/dirs.d.ts +10 -0
- package/lib/shared/dirs.d.ts.map +1 -0
- package/lib/shared/dirs.js +20 -0
- package/lib/shared/dirs.js.map +1 -0
- package/lib/shared/http-body.js +43 -0
- package/lib/shared/index.d.ts +8 -0
- package/lib/shared/index.d.ts.map +1 -0
- package/lib/shared/index.js +8 -0
- package/lib/shared/index.js.map +1 -0
- package/lib/shared/json-file.js +34 -0
- package/lib/shared/orders.js +26 -0
- package/lib/shared/scope.d.ts +14 -0
- package/lib/shared/scope.d.ts.map +1 -0
- package/lib/shared/scope.js +12 -0
- package/lib/shared/scope.js.map +1 -0
- package/lib/shared/send-helper.d.ts +11 -0
- package/lib/shared/send-helper.d.ts.map +1 -0
- package/lib/shared/send-helper.js +13 -0
- package/lib/shared/send-helper.js.map +1 -0
- package/lib/shared/utils.d.ts +31 -0
- package/lib/shared/utils.d.ts.map +1 -0
- package/lib/shared/utils.js +228 -0
- package/lib/shared/utils.js.map +1 -0
- package/lib/tool-guard.js +74 -0
- package/lib/transport/attachment.d.ts +41 -0
- package/lib/transport/attachment.d.ts.map +1 -0
- package/lib/transport/attachment.js +191 -0
- package/lib/transport/attachment.js.map +1 -0
- package/lib/transport/chunker.d.ts +14 -0
- package/lib/transport/chunker.d.ts.map +1 -0
- package/lib/transport/chunker.js +78 -0
- package/lib/transport/chunker.js.map +1 -0
- package/lib/transport/deliverables.d.ts +20 -0
- package/lib/transport/deliverables.d.ts.map +1 -0
- package/lib/transport/deliverables.js +72 -0
- package/lib/transport/deliverables.js.map +1 -0
- package/lib/transport/events.d.ts +117 -0
- package/lib/transport/events.d.ts.map +1 -0
- package/lib/transport/events.js +112 -0
- package/lib/transport/events.js.map +1 -0
- package/lib/transport/inbound.d.ts +11 -0
- package/lib/transport/inbound.d.ts.map +1 -0
- package/lib/transport/inbound.js +511 -0
- package/lib/transport/inbound.js.map +1 -0
- package/lib/transport/index.d.ts +10 -0
- package/lib/transport/index.d.ts.map +1 -0
- package/lib/transport/index.js +10 -0
- package/lib/transport/index.js.map +1 -0
- package/lib/transport/msgid-cache.d.ts +23 -0
- package/lib/transport/msgid-cache.d.ts.map +1 -0
- package/lib/transport/msgid-cache.js +57 -0
- package/lib/transport/msgid-cache.js.map +1 -0
- package/lib/transport/notify.js +147 -0
- package/lib/transport/outbound-buffer.d.ts +42 -0
- package/lib/transport/outbound-buffer.d.ts.map +1 -0
- package/lib/transport/outbound-buffer.js +68 -0
- package/lib/transport/outbound-buffer.js.map +1 -0
- package/lib/transport/outbound.d.ts +42 -0
- package/lib/transport/outbound.d.ts.map +1 -0
- package/lib/transport/outbound.js +183 -0
- package/lib/transport/outbound.js.map +1 -0
- package/lib/transport/reply-limiter.d.ts +31 -0
- package/lib/transport/reply-limiter.d.ts.map +1 -0
- package/lib/transport/reply-limiter.js +50 -0
- package/lib/transport/reply-limiter.js.map +1 -0
- package/lib/transport/reply-target.d.ts +32 -0
- package/lib/transport/reply-target.d.ts.map +1 -0
- package/lib/transport/reply-target.js +64 -0
- package/lib/transport/reply-target.js.map +1 -0
- package/lib/transport/streaming-writer.d.ts +55 -0
- package/lib/transport/streaming-writer.d.ts.map +1 -0
- package/lib/transport/streaming-writer.js +122 -0
- package/lib/transport/streaming-writer.js.map +1 -0
- package/lib/transport/tool-presenter.d.ts +37 -0
- package/lib/transport/tool-presenter.d.ts.map +1 -0
- package/lib/transport/tool-presenter.js +116 -0
- package/lib/transport/tool-presenter.js.map +1 -0
- package/lib/turn-check.js +85 -0
- package/lib/types.d.ts +39 -0
- package/lib/types.js +5 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +127 -4
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// 主动找人的定时器。
|
|
2
|
+
//
|
|
3
|
+
// 原版走 host.pushEvent(一条「想找他说句话」的事件,再由宿主总线投给 agent)。
|
|
4
|
+
// dsh 这边没有那条总线,就照 dsh-day / dsh-map 那套自己投:
|
|
5
|
+
// setInterval 每分钟 → shouldReachOut() 过闸 → pickReachTarget(true) 挑到人
|
|
6
|
+
// → 找会话 → agent.followup 投一条念头 → 投不出去就存 missed,下一轮由注入段带出来。
|
|
7
|
+
//
|
|
8
|
+
// 分寸都在 life.js 里(half 夜不找、刚说过话不找、间隔 55/180 分钟、概率 0.4/0.25),
|
|
9
|
+
// 这里只负责「到点了就真去说一次」,不重复判一遍。
|
|
10
|
+
|
|
11
|
+
import { pickAgent } from '../session/pick-agent.js'
|
|
12
|
+
|
|
13
|
+
const MAX_MISSED = 5
|
|
14
|
+
|
|
15
|
+
export function mountReachOut (ctx, { life, logger, intervalSec = 60, warmupSec = 30 } = {}) {
|
|
16
|
+
const missed = []
|
|
17
|
+
|
|
18
|
+
function silentText (hours) {
|
|
19
|
+
if (!Number.isFinite(hours)) return '很久没说过话'
|
|
20
|
+
const n = Math.max(0, Math.round(hours))
|
|
21
|
+
if (n >= 48) return `静了 ${Math.round(n / 24)} 天`
|
|
22
|
+
return `静了 ${n} 小时`
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function compose (target) {
|
|
26
|
+
const tail = target?.lastSaid
|
|
27
|
+
? `他上一句是「${target.lastSaid}」,接得上就接着聊。`
|
|
28
|
+
: ''
|
|
29
|
+
return `你有点想找 ${target.qq} 说句话(交情 ${Math.round(target.score)} 分,${silentText(target.silentHours)})。`
|
|
30
|
+
+ tail
|
|
31
|
+
+ '想说就说,不想说就算了。'
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function deliver (text) {
|
|
35
|
+
// 和闹钟叫醒同一套:先找主人私聊那条会话,别把念头投进群里。
|
|
36
|
+
let agent = null
|
|
37
|
+
try {
|
|
38
|
+
agent = await pickAgent(ctx.get?.('agents'))
|
|
39
|
+
} catch (error) {
|
|
40
|
+
logger?.warn?.(`humanlike: 挑会话失败 ${String(error)}`)
|
|
41
|
+
}
|
|
42
|
+
if (!agent) return false
|
|
43
|
+
const message = {
|
|
44
|
+
id: `humanlike-reach-${Date.now()}`,
|
|
45
|
+
role: 'user',
|
|
46
|
+
content: [{ type: 'text', text }],
|
|
47
|
+
source: { kind: 'humanlike', type: 'reach' },
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
if (typeof agent.followup === 'function') {
|
|
51
|
+
Promise.resolve(agent.followup(message)).catch((error) => {
|
|
52
|
+
logger?.warn?.(`humanlike: 主动找人投递失败 ${String(error)}`)
|
|
53
|
+
push(text)
|
|
54
|
+
})
|
|
55
|
+
return true
|
|
56
|
+
}
|
|
57
|
+
const sessionId = agent?.session?.id
|
|
58
|
+
const sc = ctx.get?.('sessionController')
|
|
59
|
+
if (sessionId && typeof sc?.prompt === 'function') {
|
|
60
|
+
Promise.resolve(sc.prompt({ sessionId, content: message.content, mode: 'queue' }, { source: 'humanlike' })).catch((error) => {
|
|
61
|
+
logger?.warn?.(`humanlike: 主动找人排队投递失败 ${String(error)}`)
|
|
62
|
+
push(text)
|
|
63
|
+
})
|
|
64
|
+
return true
|
|
65
|
+
}
|
|
66
|
+
} catch (error) {
|
|
67
|
+
logger?.warn?.(`humanlike: 主动找人投递异常 ${String(error)}`)
|
|
68
|
+
}
|
|
69
|
+
return false
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function push (text) {
|
|
73
|
+
if (missed.includes(text)) return
|
|
74
|
+
missed.push(text)
|
|
75
|
+
while (missed.length > MAX_MISSED) missed.shift()
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function tick () {
|
|
79
|
+
try {
|
|
80
|
+
if (!life?.shouldReachOut?.()) return
|
|
81
|
+
const target = life.pickReachTarget?.(true)
|
|
82
|
+
if (!target) return
|
|
83
|
+
const text = compose(target)
|
|
84
|
+
if (!(await deliver(text))) push(text)
|
|
85
|
+
// 投出去就算「找过他了」:不记这一笔,一分钟一跳的闸门下一轮还会放行,
|
|
86
|
+
// 隔够分钟数就再投一遍,两分钟里能连着起两遍念。
|
|
87
|
+
else life.noteReached?.(target)
|
|
88
|
+
} catch (error) {
|
|
89
|
+
logger?.warn?.(`humanlike: 主动找人这一轮出错 ${String(error)}`)
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
let timer = null
|
|
94
|
+
try {
|
|
95
|
+
const first = setTimeout(() => { void tick() }, Math.max(5, warmupSec) * 1000)
|
|
96
|
+
first.unref?.()
|
|
97
|
+
timer = setInterval(() => { void tick() }, Math.max(15, intervalSec) * 1000)
|
|
98
|
+
timer.unref?.()
|
|
99
|
+
} catch (error) {
|
|
100
|
+
logger?.warn?.(`humanlike: 主动找人定时器没起起来 ${String(error)}`)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
try {
|
|
104
|
+
ctx.effect?.(() => () => {
|
|
105
|
+
if (timer) clearInterval(timer)
|
|
106
|
+
timer = null
|
|
107
|
+
})
|
|
108
|
+
} catch {
|
|
109
|
+
// 没有 effect 就留着定时器,进程退了自然没
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return {
|
|
113
|
+
tick,
|
|
114
|
+
// 只读:注入段每轮都可能被渲两次,读一次就清空会只送到一半(见 dsh-day 那套)。
|
|
115
|
+
missedText: () => missed.map((t) => `- ${t}`).join('\n'),
|
|
116
|
+
clearMissed: () => { missed.length = 0 },
|
|
117
|
+
stats: () => ({ missed: missed.length }),
|
|
118
|
+
}
|
|
119
|
+
}
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
// 「看得见的事」家族工具:humanlike_real { desk | cost | prefix | config }
|
|
2
|
+
//
|
|
3
|
+
// 从 cortico-world-humanlike-alont1/src/modules/real/world.ts 搬过来。四个动作全是只读。
|
|
4
|
+
// 回执文案、节流、价目表、高峰判定都照原样。跟原版的差别只在「数据从哪来」:
|
|
5
|
+
//
|
|
6
|
+
// 1. desk 走 PowerShell 调 user32 读前台窗口。原版就是 Windows-only;
|
|
7
|
+
// 这台机器是 macOS,powershell 不存在,所以必然落到那句「问不到」——不编窗口名。
|
|
8
|
+
// 2. cost 读 <dataDir>/usage.jsonl(一行一条请求),跟原版一样的账本格式。
|
|
9
|
+
// dsh 自己不写这份账本;要接别处的用量,用 config.usageFile 指过去。
|
|
10
|
+
// 3. prefix 打的是原版控制台的 /api/prompts/prefix。dsh 没有那个控制台,
|
|
11
|
+
// 所以要么调用方把 config.consoleUrl 指到一个真端点,要么就返回「取前缀失败:…」。
|
|
12
|
+
// 4. config 读 <botDir>/config.json(默认是 dataDir 的上一级)。dsh 没有那份部署配置,
|
|
13
|
+
// 所以通常就是「读不到部署配置。」——不编数字。
|
|
14
|
+
//
|
|
15
|
+
// 这四个动作都不写盘、不抛错(desk 之外全同步)。
|
|
16
|
+
|
|
17
|
+
import fs from 'node:fs'
|
|
18
|
+
import path from 'node:path'
|
|
19
|
+
import { spawn } from 'node:child_process'
|
|
20
|
+
import { DEFAULT_VALUES } from './settings.js'
|
|
21
|
+
|
|
22
|
+
// 2026-09-23 抄自官方文档(元 / 百万 tokens:hit = 命中缓存的输入,miss = 未命中,out = 输出)
|
|
23
|
+
const REAL_DEFAULT_PRICING = {
|
|
24
|
+
'deepseek-flash': { hit: [0.04, 0.02], miss: [2, 1], out: [8, 4] },
|
|
25
|
+
'deepseek-v4-pro': { hit: [0.30, 0.15], miss: [9.0, 4.5], out: [27.0, 13.5] },
|
|
26
|
+
'deepseek-v4-flash': { hit: [0.04, 0.02], miss: [2, 1], out: [8, 4] },
|
|
27
|
+
'deepseek-v4-flash-vision-exp': { hit: [0.04, 0.02], miss: [2, 1], out: [8, 4] },
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// 默认值由 lib/settings.js 统一提供;后面几个是内部项,不上面板。
|
|
31
|
+
const DEFAULTS = {
|
|
32
|
+
...DEFAULT_VALUES.real,
|
|
33
|
+
pricingJson: DEFAULT_VALUES.real.pricingJson || JSON.stringify(REAL_DEFAULT_PRICING),
|
|
34
|
+
consolePort: 7788,
|
|
35
|
+
timezone: 'Asia/Shanghai',
|
|
36
|
+
botDir: '',
|
|
37
|
+
usageFile: '',
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** PowerShell 脚本:只取进程名与标题,绝不截屏。 */
|
|
41
|
+
const FOREGROUND_SCRIPT = [
|
|
42
|
+
// 先把输出编码钉成 UTF-8:默认按控制台代码页(中文机器是 GBK)吐字节,
|
|
43
|
+
// 这边按 UTF-8 读,中文标题就会整条变成乱码——实测踩过。
|
|
44
|
+
'[Console]::OutputEncoding = [System.Text.Encoding]::UTF8',
|
|
45
|
+
'$OutputEncoding = [System.Text.Encoding]::UTF8',
|
|
46
|
+
'$sig = @"',
|
|
47
|
+
'using System; using System.Text; using System.Runtime.InteropServices;',
|
|
48
|
+
'public class Fg {',
|
|
49
|
+
' [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();',
|
|
50
|
+
' [DllImport("user32.dll")] public static extern int GetWindowText(IntPtr h, StringBuilder s, int n);',
|
|
51
|
+
' [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);',
|
|
52
|
+
'}',
|
|
53
|
+
'"@',
|
|
54
|
+
'Add-Type -TypeDefinition $sig -ErrorAction Stop',
|
|
55
|
+
'$h = [Fg]::GetForegroundWindow()',
|
|
56
|
+
'if ($h -eq [IntPtr]::Zero) { Write-Output "{}"; exit 0 }',
|
|
57
|
+
'$sb = New-Object System.Text.StringBuilder 512',
|
|
58
|
+
'[void][Fg]::GetWindowText($h, $sb, 512)',
|
|
59
|
+
'$procId = 0',
|
|
60
|
+
'[void][Fg]::GetWindowThreadProcessId($h, [ref]$procId)',
|
|
61
|
+
'$p = Get-Process -Id $procId -ErrorAction SilentlyContinue',
|
|
62
|
+
'$name = if ($p) { $p.ProcessName } else { "?" }',
|
|
63
|
+
'$t = $sb.ToString()',
|
|
64
|
+
'@{ process = $name; title = $t } | ConvertTo-Json -Compress',
|
|
65
|
+
].join('\n')
|
|
66
|
+
|
|
67
|
+
export function createReal (opts) {
|
|
68
|
+
// 入参叫 rawConfig:下面那个只读动作叫 config,同名会撞
|
|
69
|
+
const { dataDir, config: rawConfig = {}, logger } = opts
|
|
70
|
+
const cfg = { ...DEFAULTS, ...rawConfig }
|
|
71
|
+
const botDir = cfg.botDir ? String(cfg.botDir) : path.dirname(dataDir)
|
|
72
|
+
const usageFile = cfg.usageFile ? String(cfg.usageFile) : path.join(dataDir, 'usage.jsonl')
|
|
73
|
+
|
|
74
|
+
// 桌面读数的缓存只活在实例上,不落盘(原版也一样)
|
|
75
|
+
let lastDesk = null
|
|
76
|
+
let deskAt = 0
|
|
77
|
+
|
|
78
|
+
// ── 他的桌面 ──────────────────────────────────────────────────────────────
|
|
79
|
+
|
|
80
|
+
function readForeground () {
|
|
81
|
+
return new Promise((resolve) => {
|
|
82
|
+
let proc = null
|
|
83
|
+
let done = false
|
|
84
|
+
const finish = (value) => {
|
|
85
|
+
if (done) return
|
|
86
|
+
done = true
|
|
87
|
+
resolve(value)
|
|
88
|
+
}
|
|
89
|
+
try {
|
|
90
|
+
proc = spawn('powershell', ['-NoProfile', '-NonInteractive', '-Command', FOREGROUND_SCRIPT], {
|
|
91
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
92
|
+
windowsHide: true,
|
|
93
|
+
})
|
|
94
|
+
const chunks = []
|
|
95
|
+
proc.stdout?.on('data', (d) => chunks.push(d))
|
|
96
|
+
proc.on('close', (code) => {
|
|
97
|
+
if (code !== 0) return finish(null)
|
|
98
|
+
try {
|
|
99
|
+
const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8').trim() || '{}')
|
|
100
|
+
if (!parsed.process) return finish(null)
|
|
101
|
+
finish({ ts: Date.now(), process: parsed.process, title: parsed.title ?? '' })
|
|
102
|
+
} catch {
|
|
103
|
+
finish(null)
|
|
104
|
+
}
|
|
105
|
+
})
|
|
106
|
+
proc.on('error', () => finish(null))
|
|
107
|
+
const killer = setTimeout(() => {
|
|
108
|
+
try { proc?.kill() } catch { /* 已经退了 */ }
|
|
109
|
+
finish(null)
|
|
110
|
+
}, 15000)
|
|
111
|
+
killer.unref?.()
|
|
112
|
+
} catch {
|
|
113
|
+
finish(null)
|
|
114
|
+
}
|
|
115
|
+
})
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function desk () {
|
|
119
|
+
const gap = Math.max(0, Number(cfg.deskGapSec) || 0) * 1000
|
|
120
|
+
// 缓存分支不带过滤器提示——原版就是这样,别自作多情补一行
|
|
121
|
+
if (lastDesk && Date.now() - deskAt < gap) {
|
|
122
|
+
return `(刚看过,${Math.round((Date.now() - deskAt) / 1000)} 秒前)`
|
|
123
|
+
+ `前台是 ${lastDesk.process}:${lastDesk.title || '(没有标题)'}`
|
|
124
|
+
}
|
|
125
|
+
const r = await readForeground()
|
|
126
|
+
if (!r) return '问不到:拿不到前台窗口(可能在锁屏,或者这台机器的查询被挡了)。'
|
|
127
|
+
lastDesk = r
|
|
128
|
+
deskAt = Date.now()
|
|
129
|
+
const filter = String(cfg.deskProcessFilter ?? '').trim()
|
|
130
|
+
// 逗号 / 中文逗号 / 空白任意分隔,大小写不敏感的子串匹配
|
|
131
|
+
const hit = !filter || filter.split(/[,,\s]+/).filter(Boolean)
|
|
132
|
+
.some((k) => r.process.toLowerCase().includes(k.toLowerCase()))
|
|
133
|
+
return `前台是 ${r.process}:${r.title || '(没有标题)'}`
|
|
134
|
+
+ (filter && !hit ? `\n(他设过"只关心 ${filter}",这个不在里面——多半是后台杂项。)` : '')
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// ── 花销 ──────────────────────────────────────────────────────────────────
|
|
138
|
+
|
|
139
|
+
function readUsage (days) {
|
|
140
|
+
try {
|
|
141
|
+
if (!fs.existsSync(usageFile)) return []
|
|
142
|
+
// 毫秒滑动窗口,不是自然日零点
|
|
143
|
+
const from = Date.now() - days * 86400_000
|
|
144
|
+
const out = []
|
|
145
|
+
for (const line of fs.readFileSync(usageFile, 'utf8').split(/\r?\n/)) {
|
|
146
|
+
if (!line.trim()) continue
|
|
147
|
+
try {
|
|
148
|
+
const r = JSON.parse(line)
|
|
149
|
+
// ts 解析失败会是 NaN,NaN < from 为 false —— 这条会被留下,跟原版一致
|
|
150
|
+
if (!r.ts || Date.parse(r.ts) < from) continue
|
|
151
|
+
out.push({
|
|
152
|
+
model: String(r.model ?? '?'),
|
|
153
|
+
ts: r.ts,
|
|
154
|
+
input: Number(r.promptTokens ?? 0),
|
|
155
|
+
cached: Number(r.cacheHitTokens ?? 0),
|
|
156
|
+
output: Number(r.completionTokens ?? 0),
|
|
157
|
+
})
|
|
158
|
+
} catch { /* 坏行跳过:账本是外部输入 */ }
|
|
159
|
+
}
|
|
160
|
+
return out
|
|
161
|
+
} catch {
|
|
162
|
+
return []
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function priceTable () {
|
|
167
|
+
try {
|
|
168
|
+
const parsed = typeof cfg.pricingJson === 'string' ? JSON.parse(cfg.pricingJson) : cfg.pricingJson
|
|
169
|
+
if (parsed && typeof parsed === 'object') return parsed
|
|
170
|
+
} catch {
|
|
171
|
+
logger?.warn?.('humanlike: 价格表 JSON 读不出来,用内置那份')
|
|
172
|
+
}
|
|
173
|
+
return REAL_DEFAULT_PRICING
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** 高峰 = 配置时区的工作日 9-12 点、14-18 点(法定节假日不另算)。 */
|
|
177
|
+
function isPeak (d) {
|
|
178
|
+
const fmt = (extra) => new Intl.DateTimeFormat('en-US', { timeZone: cfg.timezone, ...extra }).format(d)
|
|
179
|
+
const weekday = fmt({ weekday: 'short' })
|
|
180
|
+
if (weekday === 'Sat' || weekday === 'Sun') return false
|
|
181
|
+
// 某些环境会把 24 点格式成 24,% 24 之后才是 0
|
|
182
|
+
const h = Number(fmt({ hour: 'numeric', hour12: false })) % 24
|
|
183
|
+
return (h >= 9 && h < 12) || (h >= 14 && h < 18)
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** 这一条请求大概花了多少元。高峰取 [0],空闲取 [1]。 */
|
|
187
|
+
function estimate (r, table) {
|
|
188
|
+
const price = table[r.model] ?? table['deepseek-flash'] ?? { hit: [0.04, 0.02], miss: [2, 1], out: [8, 4] }
|
|
189
|
+
const idx = isPeak(new Date(Date.parse(r.ts))) ? 0 : 1
|
|
190
|
+
const uncachedIn = Math.max(0, r.input - r.cached)
|
|
191
|
+
const per = (arr, fallback) => (Array.isArray(arr) && arr.length > idx ? arr[idx] : fallback)
|
|
192
|
+
return (r.cached / 1e6) * per(price.hit, 0.04)
|
|
193
|
+
+ (uncachedIn / 1e6) * per(price.miss, 2)
|
|
194
|
+
+ (r.output / 1e6) * per(price.out, 8)
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function cost (args) {
|
|
198
|
+
// 0 / NaN / undefined 都当 1;超界夹到 1~30
|
|
199
|
+
const days = Math.max(1, Math.min(30, Number(args?.days) || 1))
|
|
200
|
+
const rows = readUsage(days)
|
|
201
|
+
if (!rows.length) return `最近 ${days} 天账本里没有记录。`
|
|
202
|
+
const table = priceTable()
|
|
203
|
+
let total = 0
|
|
204
|
+
const byModel = new Map()
|
|
205
|
+
for (const r of rows) {
|
|
206
|
+
// 原版 estimate 外面没有 try:坏 ts 会让 isPeak 抛 RangeError。这里兜住,
|
|
207
|
+
// 单条坏记录不该把整次查询打掉(差别写进回报里)。
|
|
208
|
+
let yuan
|
|
209
|
+
try {
|
|
210
|
+
yuan = estimate(r, table)
|
|
211
|
+
} catch {
|
|
212
|
+
continue
|
|
213
|
+
}
|
|
214
|
+
total += yuan
|
|
215
|
+
const cur = byModel.get(r.model) ?? { yuan: 0, turns: 0, tokens: 0 }
|
|
216
|
+
cur.yuan += yuan
|
|
217
|
+
cur.turns += 1
|
|
218
|
+
cur.tokens += r.input + r.output
|
|
219
|
+
byModel.set(r.model, cur)
|
|
220
|
+
}
|
|
221
|
+
if (!byModel.size) return `最近 ${days} 天账本里没有记录。`
|
|
222
|
+
const lines = [...byModel.entries()]
|
|
223
|
+
.sort((a, b) => b[1].yuan - a[1].yuan)
|
|
224
|
+
.map(([model, v]) => `- ${model}:约 ¥${v.yuan.toFixed(2)}(${v.turns} 次请求,${(v.tokens / 1000).toFixed(0)}k tokens)`)
|
|
225
|
+
return `最近 ${days} 天:约 **¥${total.toFixed(2)}**(估算)\n${lines.join('\n')}`
|
|
226
|
+
+ `\n(价目表:${Object.keys(table).join('、')};高峰时段按 2 倍算,其余时段半价。)`
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// ── 她自己的规矩 ──────────────────────────────────────────────────────────
|
|
230
|
+
//
|
|
231
|
+
// dsh 没有 Coopanion 那个控制台,也没有部署 config.json:
|
|
232
|
+
// prefix 返回本插件自己注入的那一段(别的段读不到),config 报硬编码的模块清单。
|
|
233
|
+
|
|
234
|
+
async function prefix () {
|
|
235
|
+
try {
|
|
236
|
+
const read = typeof opts.prefixText === 'function' ? opts.prefixText : null
|
|
237
|
+
if (!read) return '取前缀失败:这个实例没接上自己那一段。'
|
|
238
|
+
const text = String(read() ?? '')
|
|
239
|
+
const sections = text.split(/\n(?=- )/).filter(Boolean)
|
|
240
|
+
return `你的系统前缀里,本插件注入的是一段(order 70,name humanlike/env),`
|
|
241
|
+
+ `按段落切出来是这样,共 ${text.length} 字:\n\n${text}`
|
|
242
|
+
+ (sections.length > 1 ? '' : '')
|
|
243
|
+
} catch (e) {
|
|
244
|
+
return `取前缀失败:${String(e)}`
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function config () {
|
|
249
|
+
return '正在约束你的配置(只读):\n'
|
|
250
|
+
+ '- 模块:affinity、learn、life、clock、together、mind、real 全开,参数是硬编码默认值\n'
|
|
251
|
+
+ '- 配置页、面板、legacy 迁移都没搬,改不了也读不到宿主配置\n'
|
|
252
|
+
+ '\n(这份插件只有工具和前缀段两样东西。觉得哪条挡着你了,写进自己的笔记或者直接跟他说。)\n'
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
return {
|
|
256
|
+
desk, cost, prefix, config,
|
|
257
|
+
stats: () => ({ deskAt, lastDesk: lastDesk ? lastDesk.process : null, usageFile, botDir }),
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export const REAL_TOOL = {
|
|
262
|
+
name: 'humanlike_real',
|
|
263
|
+
description:
|
|
264
|
+
'只读观察。desk 只读前台窗口标题和进程,不是截图;cost 估算用量费用;'
|
|
265
|
+
+ 'prefix 查提示词组成;config 查约束。不能控制桌面或修改配置。'
|
|
266
|
+
+ '操作及必填参数:desk;cost(days);prefix;config。',
|
|
267
|
+
parameters: {
|
|
268
|
+
type: 'object',
|
|
269
|
+
additionalProperties: false,
|
|
270
|
+
properties: {
|
|
271
|
+
action: { type: 'string', enum: ['desk', 'cost', 'prefix', 'config'], description: '选择一次操作;只传此操作使用的参数。' },
|
|
272
|
+
days: { type: 'integer', minimum: 1, maximum: 30, description: 'cost:看最近几天,默认 1(今天)。' },
|
|
273
|
+
},
|
|
274
|
+
required: ['action'],
|
|
275
|
+
},
|
|
276
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 人味插件自己的「追加规则」:存在 <dataDir>/append-rules.md,面板里能改。
|
|
3
|
+
*
|
|
4
|
+
* 跟 dsh-bili 的 src/rules.js 是同一套做法。规则作为一段系统提示注入,
|
|
5
|
+
* 所以它必须短、稳、可核对;空串等于恢复默认。
|
|
6
|
+
*
|
|
7
|
+
* @module dsh-humanlike/lib/rules
|
|
8
|
+
*/
|
|
9
|
+
import fs from 'node:fs'
|
|
10
|
+
import path from 'node:path'
|
|
11
|
+
|
|
12
|
+
const MAX = 4000
|
|
13
|
+
|
|
14
|
+
export class RulesStore {
|
|
15
|
+
#file
|
|
16
|
+
#defaults
|
|
17
|
+
#logger
|
|
18
|
+
|
|
19
|
+
constructor({ dataDir, defaults, logger }) {
|
|
20
|
+
this.#file = path.join(dataDir, 'append-rules.md')
|
|
21
|
+
this.#defaults = defaults
|
|
22
|
+
this.#logger = logger
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
get file() {
|
|
26
|
+
return this.#file
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
get defaults() {
|
|
30
|
+
return this.#defaults
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** @returns {{text: string, isDefault: boolean}} */
|
|
34
|
+
read() {
|
|
35
|
+
try {
|
|
36
|
+
const text = fs.readFileSync(this.#file, 'utf8')
|
|
37
|
+
if (text.trim() !== '') return { text, isDefault: false }
|
|
38
|
+
} catch {
|
|
39
|
+
// 没有文件就用默认
|
|
40
|
+
}
|
|
41
|
+
return { text: this.#defaults, isDefault: true }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 保存;空串等于恢复默认 */
|
|
45
|
+
save(text) {
|
|
46
|
+
const body = typeof text === 'string' ? text : ''
|
|
47
|
+
if (body.trim() === '') return this.reset()
|
|
48
|
+
if (body.length > MAX) {
|
|
49
|
+
const error = new Error(`规则太长(${body.length} 字,上限 ${MAX})`)
|
|
50
|
+
error.status = 400
|
|
51
|
+
throw error
|
|
52
|
+
}
|
|
53
|
+
fs.mkdirSync(path.dirname(this.#file), { recursive: true })
|
|
54
|
+
fs.writeFileSync(this.#file, body, 'utf8')
|
|
55
|
+
this.#logger?.info?.(`humanlike: 规则已保存 ${this.#file}`)
|
|
56
|
+
return { text: body, isDefault: false }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
reset() {
|
|
60
|
+
try {
|
|
61
|
+
fs.rmSync(this.#file, { force: true })
|
|
62
|
+
} catch {
|
|
63
|
+
// 删不掉也无所谓,read() 会继续用默认
|
|
64
|
+
}
|
|
65
|
+
return { text: this.#defaults, isDefault: true }
|
|
66
|
+
}
|
|
67
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
// 设置面板用的本地 HTTP 接口。
|
|
2
|
+
//
|
|
3
|
+
// 前缀 /qqbot/im-qqbot/humanlike,跟 qqbot 自己的接口命名空间对齐;前端(client.js)只认这一个常量。
|
|
4
|
+
// 数据全部走 settings.js,这个文件只管 HTTP 那一层:读、改、重置。
|
|
5
|
+
//
|
|
6
|
+
// 只服务回环地址(桌面版的 fetch 走 IPC 桥,合成请求可能没有 remoteAddress,也算回环)。
|
|
7
|
+
// 改完 settings.onChange 会把工具实例与前缀段一起重建,所以这里不需要「重启生效」这种话。
|
|
8
|
+
|
|
9
|
+
import { SETTINGS_GROUPS } from './settings.js';
|
|
10
|
+
import { readJsonBody as readJsonBodyShared } from '../shared/http-body.js';
|
|
11
|
+
|
|
12
|
+
export const PREFIX = '/qqbot/im-qqbot/humanlike';
|
|
13
|
+
const MAX_BODY = 64 * 1024;
|
|
14
|
+
|
|
15
|
+
class HttpError extends Error {
|
|
16
|
+
constructor(status, message) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.status = status;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function send(res, status, payload) {
|
|
23
|
+
const body = JSON.stringify(payload);
|
|
24
|
+
res.writeHead(status, {
|
|
25
|
+
'content-type': 'application/json; charset=utf-8',
|
|
26
|
+
'content-length': Buffer.byteLength(body),
|
|
27
|
+
'cache-control': 'no-store',
|
|
28
|
+
});
|
|
29
|
+
res.end(body);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 只认本机。空 remoteAddress 也算(IPC 桥合成的请求没有这一项)。 */
|
|
33
|
+
export function isLoopback(req) {
|
|
34
|
+
const address = req?.socket?.remoteAddress ?? '';
|
|
35
|
+
if (address === '') return true;
|
|
36
|
+
return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1';
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function readJsonBody(req) {
|
|
40
|
+
try {
|
|
41
|
+
return await readJsonBodyShared(req, { maxBytes: MAX_BODY, allowEmpty: true });
|
|
42
|
+
} catch (err) {
|
|
43
|
+
if (err?.code === 'body-too-large') throw new HttpError(413, '请求体过大');
|
|
44
|
+
if (err?.code === 'body-invalid-json') throw new HttpError(400, '请求体不是合法 JSON');
|
|
45
|
+
throw err;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 面板要的一整份:分组结构(标题、范围、单位)+ 当前值。 */
|
|
50
|
+
function view(settings) {
|
|
51
|
+
const values = settings.get();
|
|
52
|
+
return {
|
|
53
|
+
ok: true,
|
|
54
|
+
version: 1,
|
|
55
|
+
file: settings.file,
|
|
56
|
+
groups: SETTINGS_GROUPS.map((group) => ({
|
|
57
|
+
id: group.id,
|
|
58
|
+
title: group.title,
|
|
59
|
+
description: group.description ?? '',
|
|
60
|
+
keys: group.keys.map((item) => ({
|
|
61
|
+
key: item.key,
|
|
62
|
+
type: item.type,
|
|
63
|
+
title: item.title,
|
|
64
|
+
description: item.description ?? '',
|
|
65
|
+
min: item.min,
|
|
66
|
+
max: item.max,
|
|
67
|
+
suffix: item.suffix ?? '',
|
|
68
|
+
value: values[group.id]?.[item.key],
|
|
69
|
+
})),
|
|
70
|
+
})),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** 把前端交上来的「分组 → 键值」拆成一次一次 update,一次失败就整体报错。 */
|
|
75
|
+
function applyPatch(settings, groupId, patch) {
|
|
76
|
+
const result = settings.update(groupId, patch);
|
|
77
|
+
if (!result.ok) throw new HttpError(400, result.error ?? '没改成功');
|
|
78
|
+
return result;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function mountHumanlikeApi(ctx, { settings, rules, logger = console } = {}) {
|
|
82
|
+
if (!settings) throw new Error('mountHumanlikeApi 缺 settings');
|
|
83
|
+
|
|
84
|
+
const handle = async (req, res) => {
|
|
85
|
+
try {
|
|
86
|
+
if (req.method === 'OPTIONS') {
|
|
87
|
+
send(res, 204, {});
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
if (!isLoopback(req)) {
|
|
91
|
+
send(res, 403, { ok: false, error: '只服务本机' });
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
95
|
+
const route = url.pathname.slice(PREFIX.length) || '/';
|
|
96
|
+
|
|
97
|
+
if (req.method === 'GET' && (route === '/' || route === '/settings')) {
|
|
98
|
+
send(res, 200, view(settings));
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
if (req.method === 'POST' && route === '/settings') {
|
|
103
|
+
const body = await readJsonBody(req);
|
|
104
|
+
const groupId = typeof body.group === 'string' ? body.group : '';
|
|
105
|
+
const patch = body.patch;
|
|
106
|
+
if (groupId === '' || patch === null || typeof patch !== 'object') {
|
|
107
|
+
throw new HttpError(400, '要给 group 和 patch');
|
|
108
|
+
}
|
|
109
|
+
applyPatch(settings, groupId, patch);
|
|
110
|
+
send(res, 200, view(settings));
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (route === '/rules') {
|
|
115
|
+
if (!rules) throw new HttpError(404, '这个版本没有规则存储');
|
|
116
|
+
if (req.method === 'GET') {
|
|
117
|
+
const read = rules.read();
|
|
118
|
+
send(res, 200, { ok: true, ...read, defaults: rules.defaults, file: rules.file });
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
if (req.method === 'POST') {
|
|
122
|
+
const body = await readJsonBody(req);
|
|
123
|
+
send(res, 200, { ok: true, ...rules.save(body?.text) });
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
if (req.method === 'DELETE') {
|
|
127
|
+
send(res, 200, { ok: true, ...rules.reset() });
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
throw new HttpError(405, '只支持 GET / POST / DELETE');
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (req.method === 'POST' && route === '/reset') {
|
|
134
|
+
const body = await readJsonBody(req);
|
|
135
|
+
const groupId = typeof body.group === 'string' && body.group !== '' ? body.group : undefined;
|
|
136
|
+
const result = settings.reset(groupId);
|
|
137
|
+
if (!result.ok) throw new HttpError(500, '重置没写进去');
|
|
138
|
+
send(res, 200, view(settings));
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
send(res, 404, { ok: false, error: '没有这个接口' });
|
|
143
|
+
} catch (error) {
|
|
144
|
+
const status = error instanceof HttpError ? error.status : 500;
|
|
145
|
+
if (status === 500) logger?.warn?.(`humanlike: 设置接口出错 ${String(error?.stack ?? error)}`);
|
|
146
|
+
send(res, status, { ok: false, error: String(error?.message ?? error) });
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
ctx.inject(['webServer'], (scoped) => {
|
|
151
|
+
const server = scoped.webServer;
|
|
152
|
+
if (server === undefined || typeof server.register !== 'function') return;
|
|
153
|
+
scoped.effect(
|
|
154
|
+
() => server.register({ kind: 'prefix', path: PREFIX, handler: handle }),
|
|
155
|
+
'dsh-humanlike: settings api',
|
|
156
|
+
);
|
|
157
|
+
logger?.info?.(`humanlike: 设置接口已挂载 ${PREFIX}`);
|
|
158
|
+
});
|
|
159
|
+
}
|