@cmach_socket/opencode-qq-bot 1.0.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -319
- package/chat-overrides.example.json +13 -3
- package/package.json +4 -1
- package/src/commands.ts +7 -7
- package/src/config/fields.ts +3 -27
- package/src/config/live.ts +2 -2
- package/src/config/store.ts +9 -0
- package/src/config/types.ts +2 -8
- package/src/config.ts +5 -12
- package/src/diary/command.ts +10 -8
- package/src/diary/scheduler.ts +11 -11
- package/src/diary/scope.ts +14 -23
- package/src/diary/summary.ts +91 -57
- package/src/fs/atomic.ts +17 -5
- package/src/home.ts +7 -7
- package/src/index.ts +57 -41
- package/src/media-path.ts +2 -12
- package/src/naplink/client.ts +50 -1
- package/src/naplink/history.ts +9 -2
- package/src/naplink/media.ts +3 -5
- package/src/naplink/render.ts +10 -3
- package/src/overrides.ts +43 -36
- package/src/panel/documents.ts +32 -44
- package/src/panel/server.ts +8 -1
- package/src/panel/status.ts +7 -1
- package/src/session/find.ts +2 -3
- package/src/session/manager.ts +27 -40
- package/src/tools/policy-guard.ts +9 -5
- package/src/tools/policy.ts +59 -37
- package/src/tools/qq.ts +132 -41
- package/src/user/inject.ts +66 -0
- package/src/user/store.ts +93 -0
- package/src/workspace.ts +113 -0
- package/tool-profiles.example.json +0 -4
- package/web/dist/assets/{index-B-3ZGYMq.js → index-Be9cCNMT.js} +2 -2
- package/web/dist/index.html +1 -1
package/src/tools/qq.ts
CHANGED
|
@@ -5,7 +5,7 @@ import { delay } from "../async"
|
|
|
5
5
|
import { type ChatTarget, targetKey, targetLabel } from "../chat"
|
|
6
6
|
import type { QQBotConfig } from "../config"
|
|
7
7
|
import { chatLabel, dateKey, isDateKey } from "../diary/format"
|
|
8
|
-
import {
|
|
8
|
+
import { diaryEnabled } from "../diary/scope"
|
|
9
9
|
import type { DiaryStore } from "../diary/store"
|
|
10
10
|
import {
|
|
11
11
|
checkDescription,
|
|
@@ -23,9 +23,9 @@ import {
|
|
|
23
23
|
import type { FavoriteIndex } from "../emoji/favorite-index"
|
|
24
24
|
import type { Logger } from "../logger"
|
|
25
25
|
import type { OutboundMedia } from "../media-path"
|
|
26
|
-
import { neutralizeStructureTags, sanitizeUntrustedText } from "../model-view"
|
|
26
|
+
import { neutralizeStructureTags, sanitizeDocumentText, sanitizeUntrustedText } from "../model-view"
|
|
27
27
|
import type { QQClient } from "../naplink/client"
|
|
28
|
-
import type {
|
|
28
|
+
import type { ChatOverrides } from "../overrides"
|
|
29
29
|
import { splitGraphemes, splitMessage, segmentDelayMs, toPlainText } from "../outbound"
|
|
30
30
|
import type { RateLimitVerdict, SendRateLimiter } from "../rate-limit"
|
|
31
31
|
import { modelSendScope, pluginSendScope } from "../rate-limit"
|
|
@@ -33,6 +33,9 @@ import type { SensitiveChecker } from "../sensitive"
|
|
|
33
33
|
import type { SessionManager } from "../session/manager"
|
|
34
34
|
import type { Tracer } from "../trace"
|
|
35
35
|
import { softTruncate } from "../text"
|
|
36
|
+
import { READ_USER_MD_TOOL, USER_PROFILE_TOOL, USER_PROFILE_WRITE_TOOL } from "../user/inject"
|
|
37
|
+
import type { UserStore } from "../user/store"
|
|
38
|
+
import type { ChatWorkspaces } from "../workspace"
|
|
36
39
|
|
|
37
40
|
/** 工具命名空间,最终工具名为 qq_send_message 等。 */
|
|
38
41
|
export const TOOL_NAMESPACE = "qq"
|
|
@@ -70,6 +73,9 @@ export const QQ_TOOL_NAMES = [
|
|
|
70
73
|
"qq_diary_write",
|
|
71
74
|
"qq_diary_read",
|
|
72
75
|
"qq_diary_list",
|
|
76
|
+
READ_USER_MD_TOOL,
|
|
77
|
+
USER_PROFILE_TOOL,
|
|
78
|
+
USER_PROFILE_WRITE_TOOL,
|
|
73
79
|
] as const
|
|
74
80
|
|
|
75
81
|
export interface ToolDeps {
|
|
@@ -90,19 +96,14 @@ export interface ToolDeps {
|
|
|
90
96
|
limiter: SendRateLimiter
|
|
91
97
|
/** 出站敏感信息检查,命中时整条消息不发送。 */
|
|
92
98
|
sensitive: SensitiveChecker
|
|
93
|
-
/**
|
|
94
|
-
|
|
95
|
-
/** 入站媒体存储,供 qq_download_file 定位落盘文件。 */
|
|
96
|
-
media: MediaStore
|
|
97
|
-
/**
|
|
98
|
-
* 普通成员可用的出站媒体把关,只放开媒体目录。
|
|
99
|
-
*
|
|
100
|
-
* owner/admin 用 `outbound`(工作区 + 媒体目录 + 配置的额外目录),
|
|
101
|
-
* 其他人只能用这个收窄过的实例,避免读到工作区里的源码与配置。
|
|
102
|
-
*/
|
|
103
|
-
outboundMember?: OutboundMedia
|
|
99
|
+
/** 每个聊天各自的工作目录、媒体存储与出站白名单。 */
|
|
100
|
+
workspaces: ChatWorkspaces
|
|
104
101
|
/** 日记读写,供 qq_diary_* 使用;不传就不注册日记工具。 */
|
|
105
102
|
diary?: DiaryStore
|
|
103
|
+
/** 用户档案与用户画像的存取,供 qq_read_user_md / qq_user_profile / qq_user_profile_write 使用。 */
|
|
104
|
+
users: UserStore
|
|
105
|
+
/** 会话覆盖:决定哪些聊天开着日记。 */
|
|
106
|
+
overrides: ChatOverrides
|
|
106
107
|
/** 调用链追踪器;不传就不记追踪。 */
|
|
107
108
|
tracer?: Tracer
|
|
108
109
|
/**
|
|
@@ -173,6 +174,12 @@ interface FileInput {
|
|
|
173
174
|
name?: string[]
|
|
174
175
|
}
|
|
175
176
|
|
|
177
|
+
/** 用户画像写入工具的入参:content 是正文,mode 决定覆盖还是追加。 */
|
|
178
|
+
interface UserProfileWriteInput {
|
|
179
|
+
content?: string
|
|
180
|
+
mode?: string
|
|
181
|
+
}
|
|
182
|
+
|
|
176
183
|
/** 合并转发里的一个节点:发送者固定为机器人自己,正文是纯文本。 */
|
|
177
184
|
interface ForwardNode {
|
|
178
185
|
user_id: number
|
|
@@ -413,18 +420,16 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
413
420
|
recentImages,
|
|
414
421
|
limiter,
|
|
415
422
|
sensitive,
|
|
416
|
-
|
|
417
|
-
outboundMember,
|
|
418
|
-
media,
|
|
423
|
+
workspaces,
|
|
419
424
|
diary,
|
|
425
|
+
users,
|
|
426
|
+
overrides,
|
|
420
427
|
tracer,
|
|
421
428
|
} = deps
|
|
422
429
|
|
|
423
|
-
/**
|
|
424
|
-
const
|
|
425
|
-
|
|
426
|
-
? outbound
|
|
427
|
-
: (outboundMember ?? outbound)
|
|
430
|
+
/** 按会话角色取这个聊天的出站媒体范围:只有 owner/admin 能碰整个工作区。 */
|
|
431
|
+
const outboundFor = (sessionID: string, target: ChatTarget): OutboundMedia =>
|
|
432
|
+
workspaces.outboundFor(target, manager.currentRole(sessionID))
|
|
428
433
|
|
|
429
434
|
const requireTarget = (sessionID: string): ChatTarget | undefined => {
|
|
430
435
|
const target = manager.targetForSession(sessionID)
|
|
@@ -845,7 +850,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
845
850
|
editor.add({
|
|
846
851
|
name: "send_image",
|
|
847
852
|
description:
|
|
848
|
-
"向当前 QQ 群聊或私聊发送图片。file 是图片来源列表(本地路径或 http(s) 地址),base64 是 base64 数据列表;两个列表合成一批图片,一条一个。本地路径:owner/admin
|
|
853
|
+
"向当前 QQ 群聊或私聊发送图片。file 是图片来源列表(本地路径或 http(s) 地址),base64 是 base64 数据列表;两个列表合成一批图片,一条一个。本地路径:owner/admin 可取机器人工作目录、本聊天目录和配置放开的目录,普通成员只能取本聊天目录;http(s) 地址只允许公网地址。",
|
|
849
854
|
input: {
|
|
850
855
|
type: "object",
|
|
851
856
|
properties: {
|
|
@@ -878,7 +883,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
878
883
|
]
|
|
879
884
|
if (sources.length === 0) return text("error: 缺少 file 或 base64")
|
|
880
885
|
// 整批先校验:一条不过关就整批不发。
|
|
881
|
-
const mediaCheck =
|
|
886
|
+
const mediaCheck = outboundFor(context.sessionID, target)
|
|
882
887
|
const payloads: unknown[][] = []
|
|
883
888
|
for (const source of sources) {
|
|
884
889
|
const tooLarge = checkInlineSize(source, "图片")
|
|
@@ -998,6 +1003,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
998
1003
|
const faces = await favorites.list()
|
|
999
1004
|
const rows = await favoriteIndex.sync(faces, await collection.list())
|
|
1000
1005
|
// 整批先校验:编号有一个对不上就整批不发。
|
|
1006
|
+
const mediaCheck = outboundFor(context.sessionID, target)
|
|
1001
1007
|
const stickers: { id: number; tag: string; payload: unknown[] }[] = []
|
|
1002
1008
|
for (const id of ids) {
|
|
1003
1009
|
const row = rows.find((item) => item.id === id)
|
|
@@ -1012,12 +1018,12 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
1012
1018
|
// 收藏表情的地址同样来自外部,要走和图片一致的路径与地址白名单。
|
|
1013
1019
|
let plan
|
|
1014
1020
|
try {
|
|
1015
|
-
plan = await
|
|
1021
|
+
plan = await mediaCheck.check(url)
|
|
1016
1022
|
} catch (error) {
|
|
1017
1023
|
return text(`error: ${error instanceof Error ? error.message : String(error)}`)
|
|
1018
1024
|
}
|
|
1019
1025
|
// QQ 收藏表情带 sub_type=1(KCUSTOM);本机收集的表情不在 QQ 收藏里,按普通图片发。
|
|
1020
|
-
const data: { file: string; sub_type?: number } = { file:
|
|
1026
|
+
const data: { file: string; sub_type?: number } = { file: mediaCheck.materialize(plan) }
|
|
1021
1027
|
if (!row.collected) data.sub_type = CUSTOM_FACE_SUB_TYPE
|
|
1022
1028
|
stickers.push({ id, tag: row.tag || "未标注", payload: [{ type: "image", data }] })
|
|
1023
1029
|
}
|
|
@@ -1035,7 +1041,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
1035
1041
|
editor.add({
|
|
1036
1042
|
name: "send_record",
|
|
1037
1043
|
description:
|
|
1038
|
-
"向当前 QQ 群聊或私聊发送语音。file 是语音来源列表(本地路径、http(s) 音频地址或 base64:// 数据),一条一个。本地路径:owner/admin
|
|
1044
|
+
"向当前 QQ 群聊或私聊发送语音。file 是语音来源列表(本地路径、http(s) 音频地址或 base64:// 数据),一条一个。本地路径:owner/admin 可取机器人工作目录、本聊天目录和配置放开的目录,普通成员只能取本聊天目录;http(s) 地址只允许公网地址。",
|
|
1039
1045
|
input: {
|
|
1040
1046
|
type: "object",
|
|
1041
1047
|
properties: {
|
|
@@ -1058,7 +1064,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
1058
1064
|
const sources = toStringList(input.file)
|
|
1059
1065
|
if (sources.length === 0) return text("error: 缺少 file")
|
|
1060
1066
|
// 整批先校验:一条不过关就整批不发。
|
|
1061
|
-
const mediaCheck =
|
|
1067
|
+
const mediaCheck = outboundFor(context.sessionID, target)
|
|
1062
1068
|
const payloads: unknown[][] = []
|
|
1063
1069
|
for (const source of sources) {
|
|
1064
1070
|
const tooLarge = checkInlineSize(source, "语音")
|
|
@@ -1260,7 +1266,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
1260
1266
|
if (prepared.error) return prepared.error
|
|
1261
1267
|
const id = typeof input.id === "string" ? input.id.trim().toLowerCase() : ""
|
|
1262
1268
|
if (!/^[0-9a-f]{8,64}$/u.test(id)) return text("error: 文件 id 无效")
|
|
1263
|
-
const found = await
|
|
1269
|
+
const found = await workspaces.mediaFor(prepared.target).locate(id)
|
|
1264
1270
|
if (!found) return text(`error: 没有找到文件 id=${id};可能已过期(文件保留 7 天)`)
|
|
1265
1271
|
return text(
|
|
1266
1272
|
`文件已保存到 ${found.path}(${found.ext},${found.size} 字节),可以直接用 read 工具读取。`,
|
|
@@ -1289,16 +1295,21 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
1289
1295
|
const diaryStore = diary
|
|
1290
1296
|
if (diaryStore) {
|
|
1291
1297
|
/**
|
|
1292
|
-
*
|
|
1298
|
+
* 日记工具的目标:全局开关必须开着、目标聊天必须开着日记,且调用者是 owner。
|
|
1293
1299
|
*
|
|
1294
1300
|
* owner 与 admin 共用 admin 配置档,只在配置里收权限不够,
|
|
1295
1301
|
* 这里按会话实际角色再判一次。
|
|
1296
1302
|
*/
|
|
1297
|
-
const diaryTarget = (sessionID: string): ChatTarget | undefined => {
|
|
1303
|
+
const diaryTarget = async (sessionID: string): Promise<ChatTarget | undefined> => {
|
|
1298
1304
|
const target = requireTarget(sessionID)
|
|
1299
1305
|
if (!target) return undefined
|
|
1300
|
-
|
|
1301
|
-
|
|
1306
|
+
// 全局开关是总开关:关掉后连每聊天开关都救不回来。
|
|
1307
|
+
if (!config.diary.enabled) {
|
|
1308
|
+
logger.warn("日记总开关已关闭,拒绝日记工具调用")
|
|
1309
|
+
return undefined
|
|
1310
|
+
}
|
|
1311
|
+
if (!diaryEnabled(await overrides.for(target))) {
|
|
1312
|
+
logger.warn(`${targetLabel(target)} 没有开启日记,拒绝日记工具调用`)
|
|
1302
1313
|
return undefined
|
|
1303
1314
|
}
|
|
1304
1315
|
if (manager.currentRole(sessionID) !== "owner") {
|
|
@@ -1332,8 +1343,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
1332
1343
|
options: { namespace: TOOL_NAMESPACE, codemode: false },
|
|
1333
1344
|
execute: async (raw, context) => {
|
|
1334
1345
|
const input = (raw ?? {}) as DiaryWriteInput
|
|
1335
|
-
const target = diaryTarget(context.sessionID)
|
|
1336
|
-
if (!target) return text("error:
|
|
1346
|
+
const target = await diaryTarget(context.sessionID)
|
|
1347
|
+
if (!target) return text("error: 这个聊天没有开启日记,或调用者不是 owner")
|
|
1337
1348
|
const content = (input.content ?? "").trim()
|
|
1338
1349
|
if (!content) return text("error: 缺少 content")
|
|
1339
1350
|
const date = input.date?.trim() || dateKey()
|
|
@@ -1361,8 +1372,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
1361
1372
|
options: { namespace: TOOL_NAMESPACE, codemode: false },
|
|
1362
1373
|
execute: async (raw, context) => {
|
|
1363
1374
|
const input = (raw ?? {}) as DiaryReadInput
|
|
1364
|
-
const target = diaryTarget(context.sessionID)
|
|
1365
|
-
if (!target) return text("error:
|
|
1375
|
+
const target = await diaryTarget(context.sessionID)
|
|
1376
|
+
if (!target) return text("error: 这个聊天没有开启日记,或调用者不是 owner")
|
|
1366
1377
|
const chat = targetKey(target)
|
|
1367
1378
|
const date = input.date?.trim()
|
|
1368
1379
|
if (!date) {
|
|
@@ -1391,8 +1402,8 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
1391
1402
|
options: { namespace: TOOL_NAMESPACE, codemode: false },
|
|
1392
1403
|
execute: async (raw, context) => {
|
|
1393
1404
|
const input = (raw ?? {}) as DiaryListInput
|
|
1394
|
-
const target = diaryTarget(context.sessionID)
|
|
1395
|
-
if (!target) return text("error:
|
|
1405
|
+
const target = await diaryTarget(context.sessionID)
|
|
1406
|
+
if (!target) return text("error: 这个聊天没有开启日记,或调用者不是 owner")
|
|
1396
1407
|
const days = Number.isInteger(input.days) && (input.days ?? 0) > 0 ? (input.days ?? 7) : 7
|
|
1397
1408
|
const chat = targetKey(target)
|
|
1398
1409
|
const entries = await diaryStore.list(chat, days)
|
|
@@ -1407,10 +1418,90 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
1407
1418
|
})
|
|
1408
1419
|
}
|
|
1409
1420
|
|
|
1421
|
+
// 用户档案与用户画像:作用域是当前聊天,模型不能跨聊天读写。
|
|
1422
|
+
editor.add({
|
|
1423
|
+
name: "read_user_md",
|
|
1424
|
+
description:
|
|
1425
|
+
"读取当前 QQ 群聊或私聊的 USER.md:用户自己写的档案(称呼、偏好、约定等)。需要按用户写下的资料回答、或回看这份资料时使用;USER.md 由用户维护,插件与模型都不会改它。文件还没有时只回报一句,不会替用户创建。",
|
|
1426
|
+
input: {
|
|
1427
|
+
type: "object",
|
|
1428
|
+
properties: {},
|
|
1429
|
+
additionalProperties: false,
|
|
1430
|
+
},
|
|
1431
|
+
options: { namespace: TOOL_NAMESPACE, codemode: false },
|
|
1432
|
+
execute: async (_raw, context) => {
|
|
1433
|
+
const prepared = prepareQuery(context.sessionID)
|
|
1434
|
+
if (prepared.error) return prepared.error
|
|
1435
|
+
const content = await users.readUserMd(prepared.target)
|
|
1436
|
+
if (!content?.trim()) return text("当前聊天还没有 USER.md,用户还没写过档案。")
|
|
1437
|
+
// 文件正文进模型前先净化:结构标签、零宽字符都不能带进去。
|
|
1438
|
+
return text(sanitizeDocumentText(content))
|
|
1439
|
+
},
|
|
1440
|
+
})
|
|
1441
|
+
|
|
1442
|
+
editor.add({
|
|
1443
|
+
name: "user_profile",
|
|
1444
|
+
description:
|
|
1445
|
+
"读取当前 QQ 群聊或私聊的用户画像:你自己维护的长期记忆(用户的偏好、习惯、正在做的事)。要回看或修正之前的判断时使用。要写入新内容时改用 qq_user_profile_write。画像与 USER.md 是两回事,这个工具不会碰 USER.md。",
|
|
1446
|
+
input: {
|
|
1447
|
+
type: "object",
|
|
1448
|
+
properties: {},
|
|
1449
|
+
additionalProperties: false,
|
|
1450
|
+
},
|
|
1451
|
+
options: { namespace: TOOL_NAMESPACE, codemode: false },
|
|
1452
|
+
execute: async (_raw, context) => {
|
|
1453
|
+
const prepared = prepareQuery(context.sessionID)
|
|
1454
|
+
if (prepared.error) return prepared.error
|
|
1455
|
+
const target = prepared.target
|
|
1456
|
+
const profile = await users.readProfile(target)
|
|
1457
|
+
if (!profile?.trim()) return text("当前聊天还没有用户画像。")
|
|
1458
|
+
// 画像里可能有群友可控的原文,回给模型前先净化。
|
|
1459
|
+
return text(sanitizeDocumentText(profile))
|
|
1460
|
+
},
|
|
1461
|
+
})
|
|
1462
|
+
|
|
1463
|
+
editor.add({
|
|
1464
|
+
name: "user_profile_write",
|
|
1465
|
+
description:
|
|
1466
|
+
"更新当前 QQ 群聊或私聊的用户画像:你自己维护的长期记忆(用户的偏好、习惯、正在做的事)。要记住新信息时用它写入。写入默认整份覆盖(mode=replace),只想追加一条用 mode=append。只对主人开放;画像与 USER.md 是两回事,这个工具不会碰 USER.md。",
|
|
1467
|
+
input: {
|
|
1468
|
+
type: "object",
|
|
1469
|
+
properties: {
|
|
1470
|
+
content: { type: "string", description: "要写入画像的内容(必填)" },
|
|
1471
|
+
mode: {
|
|
1472
|
+
type: "string",
|
|
1473
|
+
description: "写入方式:replace 整份覆盖(默认),append 追加到末尾",
|
|
1474
|
+
},
|
|
1475
|
+
},
|
|
1476
|
+
required: ["content"],
|
|
1477
|
+
additionalProperties: false,
|
|
1478
|
+
},
|
|
1479
|
+
options: { namespace: TOOL_NAMESPACE, codemode: false },
|
|
1480
|
+
execute: async (raw, context) => {
|
|
1481
|
+
const input = (raw ?? {}) as UserProfileWriteInput
|
|
1482
|
+
const prepared = prepareQuery(context.sessionID)
|
|
1483
|
+
if (prepared.error) return prepared.error
|
|
1484
|
+
const target = prepared.target
|
|
1485
|
+
const content = typeof input.content === "string" ? input.content : ""
|
|
1486
|
+
if (!content.trim()) return text("error: 缺少 content")
|
|
1487
|
+
const mode = input.mode === "append" ? "append" : "replace"
|
|
1488
|
+
try {
|
|
1489
|
+
await users.writeProfile(target, content, mode)
|
|
1490
|
+
} catch (error) {
|
|
1491
|
+
const reason = error instanceof Error ? error.message : String(error)
|
|
1492
|
+
logger.warn(`${targetLabel(target)} 写用户画像失败`, { reason })
|
|
1493
|
+
return text(`error: 写用户画像失败:${reason}`)
|
|
1494
|
+
}
|
|
1495
|
+
return text(
|
|
1496
|
+
mode === "append" ? "已把内容追加到当前聊天的用户画像。" : "已更新当前聊天的用户画像。",
|
|
1497
|
+
)
|
|
1498
|
+
},
|
|
1499
|
+
})
|
|
1500
|
+
|
|
1410
1501
|
editor.add({
|
|
1411
1502
|
name: "send_file",
|
|
1412
1503
|
description:
|
|
1413
|
-
"向当前 QQ 群聊或私聊发送本地文件。file 是文件路径列表,只能是机器人允许发送的目录里的普通文件;name 是对方看到的文件名列表,与 file 一一对应,省略时用原文件名。本地路径:owner/admin
|
|
1504
|
+
"向当前 QQ 群聊或私聊发送本地文件。file 是文件路径列表,只能是机器人允许发送的目录里的普通文件;name 是对方看到的文件名列表,与 file 一一对应,省略时用原文件名。本地路径:owner/admin 可取机器人工作目录、本聊天目录和配置放开的目录,普通成员只能取本聊天目录。",
|
|
1414
1505
|
input: {
|
|
1415
1506
|
type: "object",
|
|
1416
1507
|
properties: {
|
|
@@ -1439,7 +1530,7 @@ export async function registerTools(deps: ToolDeps): Promise<{ dispose(): Promis
|
|
|
1439
1530
|
const files = toStringList(input.file)
|
|
1440
1531
|
if (files.length === 0) return text("error: 缺少 file")
|
|
1441
1532
|
const names = toStringSlots(input.name)
|
|
1442
|
-
const mediaCheck =
|
|
1533
|
+
const mediaCheck = outboundFor(context.sessionID, target)
|
|
1443
1534
|
// 整批先校验:一条不过关就整批不发。
|
|
1444
1535
|
const payloads: unknown[][] = []
|
|
1445
1536
|
for (const [index, file] of files.entries()) {
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { ChatTarget } from "../chat"
|
|
2
|
+
import { sanitizeDocumentText } from "../model-view"
|
|
3
|
+
import { softTruncate } from "../text"
|
|
4
|
+
import type { UserStore } from "./store"
|
|
5
|
+
|
|
6
|
+
/** 读取用户档案的工具名。 */
|
|
7
|
+
export const READ_USER_MD_TOOL = "qq_read_user_md"
|
|
8
|
+
|
|
9
|
+
/** 读取用户画像的工具名。 */
|
|
10
|
+
export const USER_PROFILE_TOOL = "qq_user_profile"
|
|
11
|
+
|
|
12
|
+
/** 写入用户画像的工具名。 */
|
|
13
|
+
export const USER_PROFILE_WRITE_TOOL = "qq_user_profile_write"
|
|
14
|
+
|
|
15
|
+
/** 注入文本里每份文件的上限:超出的部分温和截断。 */
|
|
16
|
+
export const USER_CONTEXT_MAX_CHARS = 2000
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 会话开始时把用户档案与用户画像注入一次。
|
|
20
|
+
*
|
|
21
|
+
* 同一份档案每轮都塞一遍,模型上下文会被撑大;这里每个会话只注入一次,
|
|
22
|
+
* 之后模型自己按需调用工具再取。
|
|
23
|
+
*/
|
|
24
|
+
export class UserInjector {
|
|
25
|
+
/** 已经注入过的会话:每个会话只尝试一次。 */
|
|
26
|
+
private readonly attempted = new Set<string>()
|
|
27
|
+
|
|
28
|
+
constructor(private readonly store: UserStore) {}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 会话的第一轮把档案与画像注入一次。
|
|
32
|
+
*
|
|
33
|
+
* 两份文件都没有内容时不注入:这个会话也就算尝试过了,
|
|
34
|
+
* 用户后来补上文件,模型可以用工具自己去读。
|
|
35
|
+
*
|
|
36
|
+
* @returns 注入文本;不需要注入时返回 undefined。
|
|
37
|
+
*/
|
|
38
|
+
async injectOnce(sessionID: string, target: ChatTarget): Promise<string | undefined> {
|
|
39
|
+
if (this.attempted.has(sessionID)) return undefined
|
|
40
|
+
this.attempted.add(sessionID)
|
|
41
|
+
const [userMd, profile] = await Promise.all([
|
|
42
|
+
this.store.readUserMd(target),
|
|
43
|
+
this.store.readProfile(target),
|
|
44
|
+
])
|
|
45
|
+
const blocks: string[] = []
|
|
46
|
+
const archive = this.prepare(userMd)
|
|
47
|
+
if (archive) {
|
|
48
|
+
blocks.push(`用户档案 USER.md(用户自己写的,以用户为准):\n${archive}`)
|
|
49
|
+
}
|
|
50
|
+
const picture = this.prepare(profile)
|
|
51
|
+
if (picture) {
|
|
52
|
+
blocks.push(`用户画像(你自己维护的记忆):\n${picture}`)
|
|
53
|
+
}
|
|
54
|
+
if (blocks.length === 0) return undefined
|
|
55
|
+
blocks.push(
|
|
56
|
+
`(档案与画像随时可以再用 ${READ_USER_MD_TOOL}、${USER_PROFILE_TOOL} 取,写画像用 ${USER_PROFILE_WRITE_TOOL},只有主人能用。)`,
|
|
57
|
+
)
|
|
58
|
+
return blocks.join("\n\n")
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 净化并截断一份文件内容;空文件按没有内容处理。 */
|
|
62
|
+
private prepare(content: string | undefined): string | undefined {
|
|
63
|
+
if (!content?.trim()) return undefined
|
|
64
|
+
return softTruncate(sanitizeDocumentText(content).trim(), USER_CONTEXT_MAX_CHARS)
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises"
|
|
2
|
+
import { join } from "node:path"
|
|
3
|
+
import type { ChatTarget } from "../chat"
|
|
4
|
+
import { writeTextAtomic } from "../fs/atomic"
|
|
5
|
+
import type { Logger } from "../logger"
|
|
6
|
+
import { chatWorkspace } from "../workspace"
|
|
7
|
+
|
|
8
|
+
/** 用户自己写的档案文件名:放在聊天目录根部。 */
|
|
9
|
+
export const USER_MD_NAME = "USER.md"
|
|
10
|
+
|
|
11
|
+
/** 模型自己维护的画像文件名:放在会话工作目录里。 */
|
|
12
|
+
export const USER_PROFILE_NAME = "PROFILE.md"
|
|
13
|
+
|
|
14
|
+
/** 画像的写入方式:整份覆盖,或追加到末尾。 */
|
|
15
|
+
export type ProfileWriteMode = "replace" | "append"
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* 用户档案(USER.md)与用户画像的存取。
|
|
19
|
+
*
|
|
20
|
+
* 两份文件各管各的,互不覆盖:
|
|
21
|
+
* - `USER.md` 在聊天目录根部,由用户自己写,插件只读,从不修改;
|
|
22
|
+
* - 画像在会话工作目录里,由模型维护,插件负责落盘。
|
|
23
|
+
*
|
|
24
|
+
* 分处两个目录:插件的画像写入动不到用户档案。
|
|
25
|
+
* 但模型自带的文件工具不受插件约束:上游默认权限放行工作目录外的读写,
|
|
26
|
+
* 所以「模型够不着 `USER.md`」只在插件这一侧成立。
|
|
27
|
+
*/
|
|
28
|
+
export class UserStore {
|
|
29
|
+
constructor(
|
|
30
|
+
private readonly home: string,
|
|
31
|
+
private readonly logger: Logger,
|
|
32
|
+
) {}
|
|
33
|
+
|
|
34
|
+
/** 用户档案的路径:`<home>/chats/<kind>-<id>/USER.md`。 */
|
|
35
|
+
userMdPath(target: ChatTarget): string {
|
|
36
|
+
return join(chatWorkspace(this.home, target).root, USER_MD_NAME)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 用户画像的路径:`<home>/chats/<kind>-<id>/workspace/PROFILE.md`。 */
|
|
40
|
+
profilePath(target: ChatTarget): string {
|
|
41
|
+
return join(chatWorkspace(this.home, target).directory, USER_PROFILE_NAME)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 读用户档案。
|
|
46
|
+
*
|
|
47
|
+
* 文件不存在按「用户还没写」处理;读不出来时记一条警告,同样按没有档案处理。
|
|
48
|
+
*/
|
|
49
|
+
async readUserMd(target: ChatTarget): Promise<string | undefined> {
|
|
50
|
+
return await this.read(this.userMdPath(target))
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 读用户画像;文件不存在返回 undefined。 */
|
|
54
|
+
async readProfile(target: ChatTarget): Promise<string | undefined> {
|
|
55
|
+
return await this.read(this.profilePath(target))
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 写用户画像。
|
|
60
|
+
*
|
|
61
|
+
* `replace` 整份覆盖,`append` 追加到末尾;目录不存在时按 `0700` 建好。
|
|
62
|
+
* 走原子写:中途失败不会留下半截画像。
|
|
63
|
+
*/
|
|
64
|
+
async writeProfile(
|
|
65
|
+
target: ChatTarget,
|
|
66
|
+
content: string,
|
|
67
|
+
mode: ProfileWriteMode = "replace",
|
|
68
|
+
): Promise<void> {
|
|
69
|
+
const body = content.trim()
|
|
70
|
+
if (!body) return
|
|
71
|
+
const path = this.profilePath(target)
|
|
72
|
+
if (mode === "append") {
|
|
73
|
+
const existing = await this.readProfile(target)
|
|
74
|
+
const merged = existing?.trim() ? `${existing.trimEnd()}\n${body}\n` : `${body}\n`
|
|
75
|
+
await writeTextAtomic(path, merged)
|
|
76
|
+
return
|
|
77
|
+
}
|
|
78
|
+
await writeTextAtomic(path, `${body}\n`)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** 读一个文件;不存在返回 undefined,其它读错误记一条警告。 */
|
|
82
|
+
private async read(path: string): Promise<string | undefined> {
|
|
83
|
+
try {
|
|
84
|
+
return await readFile(path, "utf8")
|
|
85
|
+
} catch (error) {
|
|
86
|
+
const code = (error as NodeJS.ErrnoException).code
|
|
87
|
+
if (code !== "ENOENT") {
|
|
88
|
+
this.logger.warn(`读取用户文件失败:${path}`, { code })
|
|
89
|
+
}
|
|
90
|
+
return undefined
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
package/src/workspace.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { readdir } from "node:fs/promises"
|
|
2
|
+
import { join } from "node:path"
|
|
3
|
+
import { type ChatTarget, targetKey } from "./chat"
|
|
4
|
+
import type { Logger } from "./logger"
|
|
5
|
+
import { OutboundMedia } from "./media-path"
|
|
6
|
+
import { MediaStore } from "./naplink/media"
|
|
7
|
+
import type { SafeFetcher } from "./safe-fetch"
|
|
8
|
+
import type { Role } from "./tools/policy"
|
|
9
|
+
|
|
10
|
+
/** 一个聊天的专属目录:会话与媒体都在这里,按聊天隔离。 */
|
|
11
|
+
export interface ChatWorkspace {
|
|
12
|
+
/** 这个聊天的根目录,出站白名单按它授权。 */
|
|
13
|
+
root: string
|
|
14
|
+
/** 会话所在目录。 */
|
|
15
|
+
directory: string
|
|
16
|
+
/** 这个聊天的入站媒体目录。 */
|
|
17
|
+
mediaDir: string
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** 聊天目录的固定位置:`chats/<kind>-<id>/{workspace,media}`。 */
|
|
21
|
+
export function chatWorkspace(home: string, target: ChatTarget): ChatWorkspace {
|
|
22
|
+
const root = join(home, "chats", `${target.kind}-${target.id}`)
|
|
23
|
+
return { root, directory: join(root, "workspace"), mediaDir: join(root, "media") }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** 出站媒体白名单:owner/admin 能用机器人工作目录与聊天目录,其他人只能用自己的聊天目录和全局媒体。 */
|
|
27
|
+
function allowedDirs(
|
|
28
|
+
home: string,
|
|
29
|
+
shared: string,
|
|
30
|
+
chat: ChatWorkspace,
|
|
31
|
+
role: Role,
|
|
32
|
+
extra: readonly string[],
|
|
33
|
+
) {
|
|
34
|
+
return role === "owner" || role === "admin" ? [home, chat.root, ...extra] : [chat.root, shared]
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* 每个聊天的媒体存储与出站媒体策略。
|
|
39
|
+
*
|
|
40
|
+
* 存储按需创建并复用;启动时清一遍所有聊天目录里的过期媒体。
|
|
41
|
+
*/
|
|
42
|
+
export class ChatWorkspaces {
|
|
43
|
+
/** 机器人共用的媒体目录:收藏表情这类不属于任何聊天的文件。 */
|
|
44
|
+
readonly sharedMediaDir: string
|
|
45
|
+
private readonly media = new Map<string, MediaStore>()
|
|
46
|
+
private readonly outbound = new Map<string, OutboundMedia>()
|
|
47
|
+
|
|
48
|
+
constructor(
|
|
49
|
+
private readonly home: string,
|
|
50
|
+
private readonly logger: Logger,
|
|
51
|
+
private readonly extraDirs: readonly string[] = [],
|
|
52
|
+
private readonly mediaOptions: { ttlMs?: number; fetcher?: SafeFetcher } = {},
|
|
53
|
+
) {
|
|
54
|
+
this.sharedMediaDir = join(home, "media")
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 聊天的工作目录与媒体目录。 */
|
|
58
|
+
for(target: ChatTarget): ChatWorkspace {
|
|
59
|
+
return chatWorkspace(this.home, target)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** 聊天的入站媒体存储。 */
|
|
63
|
+
mediaFor(target: ChatTarget): MediaStore {
|
|
64
|
+
const key = targetKey(target)
|
|
65
|
+
let store = this.media.get(key)
|
|
66
|
+
if (!store) {
|
|
67
|
+
store = new MediaStore(
|
|
68
|
+
this.for(target).mediaDir,
|
|
69
|
+
this.logger,
|
|
70
|
+
this.mediaOptions.ttlMs,
|
|
71
|
+
this.mediaOptions.fetcher,
|
|
72
|
+
)
|
|
73
|
+
this.media.set(key, store)
|
|
74
|
+
}
|
|
75
|
+
return store
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** 按角色取这个聊天的出站媒体白名单。 */
|
|
79
|
+
outboundFor(target: ChatTarget, role: Role): OutboundMedia {
|
|
80
|
+
const member = role !== "owner" && role !== "admin"
|
|
81
|
+
const key = `${targetKey(target)}:${member ? "member" : "full"}`
|
|
82
|
+
let policy = this.outbound.get(key)
|
|
83
|
+
if (!policy) {
|
|
84
|
+
const chat = this.for(target)
|
|
85
|
+
policy = new OutboundMedia({
|
|
86
|
+
workspace: chat.directory,
|
|
87
|
+
allowedDirs: allowedDirs(this.home, this.sharedMediaDir, chat, role, this.extraDirs),
|
|
88
|
+
})
|
|
89
|
+
this.outbound.set(key, policy)
|
|
90
|
+
}
|
|
91
|
+
return policy
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** 清理所有聊天目录里超过保留期的媒体。 */
|
|
95
|
+
async cleanup(): Promise<void> {
|
|
96
|
+
const chats = join(this.home, "chats")
|
|
97
|
+
let entries: string[]
|
|
98
|
+
try {
|
|
99
|
+
entries = await readdir(chats)
|
|
100
|
+
} catch {
|
|
101
|
+
return
|
|
102
|
+
}
|
|
103
|
+
for (const entry of entries) {
|
|
104
|
+
const store = new MediaStore(
|
|
105
|
+
join(chats, entry, "media"),
|
|
106
|
+
this.logger,
|
|
107
|
+
this.mediaOptions.ttlMs,
|
|
108
|
+
this.mediaOptions.fetcher,
|
|
109
|
+
)
|
|
110
|
+
await store.cleanup()
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|