@cmach_socket/opencode-qq-bot 0.6.8 → 0.7.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 +132 -71
- package/package.json +1 -1
- package/src/config.ts +136 -0
- package/src/diary/collector.ts +187 -0
- package/src/diary/command.ts +277 -0
- package/src/diary/format.ts +157 -0
- package/src/diary/scheduler.ts +169 -0
- package/src/diary/store.ts +144 -0
- package/src/diary/summary.ts +380 -0
- package/src/index.ts +103 -2
- package/src/naplink/render.ts +42 -0
- package/src/tools/policy.ts +11 -3
- package/src/tools/qq.ts +224 -0
- package/tool-profiles.example.json +6 -2
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { appendFile, mkdir, readFile, readdir, rm, stat } from "node:fs/promises"
|
|
2
|
+
import { join } from "node:path"
|
|
3
|
+
import type { Logger } from "../logger"
|
|
4
|
+
import { chatSlug, dateKey } from "./format"
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 一行聊天素材。
|
|
8
|
+
*
|
|
9
|
+
* 素材是给模型看的中间态:只保留文本,图片与语音只留占位符。
|
|
10
|
+
*/
|
|
11
|
+
export interface DiaryLine {
|
|
12
|
+
/** NapCat 消息 ID,回补时用它去重。 */
|
|
13
|
+
id: string
|
|
14
|
+
/** 消息时间(秒)。 */
|
|
15
|
+
time: number
|
|
16
|
+
/** 发送者 QQ 号。 */
|
|
17
|
+
userId: string
|
|
18
|
+
/** 发送者显示名,取不到时退到 QQ 号。 */
|
|
19
|
+
name: string
|
|
20
|
+
/** 净化并截断后的正文。 */
|
|
21
|
+
text: string
|
|
22
|
+
/** 是否是机器人自己的消息。 */
|
|
23
|
+
self: boolean
|
|
24
|
+
/** 是否来自历史回补。 */
|
|
25
|
+
backfilled: boolean
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** 素材收集器的依赖。 */
|
|
29
|
+
export interface DiaryCollectorDeps {
|
|
30
|
+
/** 日记根目录,素材放在它下面的 `raw/` 子目录里。 */
|
|
31
|
+
root: string
|
|
32
|
+
logger: Logger
|
|
33
|
+
/** 单行素材的最大字符数。 */
|
|
34
|
+
maxLineChars: number
|
|
35
|
+
/** 单天单聊天的素材行数上限。 */
|
|
36
|
+
maxLinesPerDay: number
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 素材文件名的形状。 */
|
|
40
|
+
const RAW_FILE = /^(\d{4}-\d{2}-\d{2})\.jsonl$/
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 按码点截断。
|
|
44
|
+
*
|
|
45
|
+
* 按码点而不是 UTF-16 码元截:emoji 不会被切成半个。
|
|
46
|
+
*/
|
|
47
|
+
export function truncateChars(value: string, max: number): string {
|
|
48
|
+
const chars = Array.from(value)
|
|
49
|
+
if (chars.length <= max) return value
|
|
50
|
+
return chars.slice(0, max).join("")
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 聊天素材的累积与落盘。
|
|
55
|
+
*
|
|
56
|
+
* 素材按天分文件:`<root>/raw/<聊天目录>/<日期>.jsonl`,每行一个 JSON 对象。
|
|
57
|
+
* 素材是中间产物,按保留天数清理,不影响已生成的日记。
|
|
58
|
+
*/
|
|
59
|
+
export class DiaryCollector {
|
|
60
|
+
/** 每天的行数缓存,避免每条消息都重新数一遍文件。 */
|
|
61
|
+
private readonly counts = new Map<string, number>()
|
|
62
|
+
|
|
63
|
+
constructor(private readonly deps: DiaryCollectorDeps) {}
|
|
64
|
+
|
|
65
|
+
/** 素材根目录。 */
|
|
66
|
+
rawRoot(): string {
|
|
67
|
+
return join(this.deps.root, "raw")
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 某个聊天的素材目录。 */
|
|
71
|
+
rawDir(chat: string): string {
|
|
72
|
+
return join(this.rawRoot(), chatSlug(chat))
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 某天的素材文件。 */
|
|
76
|
+
rawFile(chat: string, date: string): string {
|
|
77
|
+
return join(this.rawDir(chat), `${date}.jsonl`)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 追加一行素材。
|
|
82
|
+
*
|
|
83
|
+
* 落盘失败只记日志,不影响聊天本身。
|
|
84
|
+
*
|
|
85
|
+
* @returns 是否真的写进去了;超过单天行数上限时返回 false。
|
|
86
|
+
*/
|
|
87
|
+
async append(chat: string, line: DiaryLine): Promise<boolean> {
|
|
88
|
+
const date = dateKey(new Date(line.time * 1000))
|
|
89
|
+
const count = await this.lineCount(chat, date)
|
|
90
|
+
if (count >= this.deps.maxLinesPerDay) {
|
|
91
|
+
this.deps.logger.warn(
|
|
92
|
+
`${chat} ${date} 的日记素材已达上限 ${this.deps.maxLinesPerDay} 行,丢弃新素材`,
|
|
93
|
+
)
|
|
94
|
+
return false
|
|
95
|
+
}
|
|
96
|
+
const record: DiaryLine = { ...line, text: truncateChars(line.text, this.deps.maxLineChars) }
|
|
97
|
+
try {
|
|
98
|
+
await mkdir(this.rawDir(chat), { recursive: true })
|
|
99
|
+
await appendFile(this.rawFile(chat, date), `${JSON.stringify(record)}\n`, "utf8")
|
|
100
|
+
} catch (error) {
|
|
101
|
+
this.deps.logger.warn(`${chat} ${date} 的日记素材写入失败`, error)
|
|
102
|
+
return false
|
|
103
|
+
}
|
|
104
|
+
this.counts.set(`${chat}|${date}`, count + 1)
|
|
105
|
+
return true
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 读某天的全部素材行。 */
|
|
109
|
+
async read(chat: string, date: string): Promise<DiaryLine[]> {
|
|
110
|
+
let content: string
|
|
111
|
+
try {
|
|
112
|
+
content = await readFile(this.rawFile(chat, date), "utf8")
|
|
113
|
+
} catch {
|
|
114
|
+
return []
|
|
115
|
+
}
|
|
116
|
+
const lines: DiaryLine[] = []
|
|
117
|
+
for (const raw of content.split("\n")) {
|
|
118
|
+
const trimmed = raw.trim()
|
|
119
|
+
if (!trimmed) continue
|
|
120
|
+
try {
|
|
121
|
+
const parsed = JSON.parse(trimmed) as DiaryLine
|
|
122
|
+
if (typeof parsed?.text !== "string") continue
|
|
123
|
+
lines.push(parsed)
|
|
124
|
+
} catch {
|
|
125
|
+
// 半行或坏行:跳过,不让一行坏数据毁掉整天的素材。
|
|
126
|
+
this.deps.logger.warn(`${chat} ${date} 的日记素材有一行无法解析,已跳过`)
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return lines
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** 某天有多少行素材。 */
|
|
133
|
+
async count(chat: string, date: string): Promise<number> {
|
|
134
|
+
return await this.lineCount(chat, date)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** 某天有没有素材。 */
|
|
138
|
+
async has(chat: string, date: string): Promise<boolean> {
|
|
139
|
+
return (await this.count(chat, date)) > 0
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** 某天的行数;第一次访问时数一遍文件并缓存。 */
|
|
143
|
+
private async lineCount(chat: string, date: string): Promise<number> {
|
|
144
|
+
const key = `${chat}|${date}`
|
|
145
|
+
const cached = this.counts.get(key)
|
|
146
|
+
if (cached !== undefined) return cached
|
|
147
|
+
let count = 0
|
|
148
|
+
try {
|
|
149
|
+
const content = await readFile(this.rawFile(chat, date), "utf8")
|
|
150
|
+
count = content.split("\n").filter((line) => line.trim().length > 0).length
|
|
151
|
+
} catch {
|
|
152
|
+
count = 0
|
|
153
|
+
}
|
|
154
|
+
this.counts.set(key, count)
|
|
155
|
+
return count
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* 清理过期的素材文件。
|
|
160
|
+
*
|
|
161
|
+
* 只清素材,成品日记不动:日记不设条数上限,也不自动清理。
|
|
162
|
+
*
|
|
163
|
+
* @returns 删掉的文件数。
|
|
164
|
+
*/
|
|
165
|
+
async cleanup(retentionDays: number): Promise<number> {
|
|
166
|
+
const days = Math.max(1, Math.floor(retentionDays))
|
|
167
|
+
const cutoff = Date.now() - days * 24 * 60 * 60 * 1000
|
|
168
|
+
const dirs = await readdir(this.rawRoot(), { withFileTypes: true }).catch(() => [])
|
|
169
|
+
let removed = 0
|
|
170
|
+
for (const dir of dirs) {
|
|
171
|
+
if (!dir.isDirectory()) continue
|
|
172
|
+
const files = await readdir(join(this.rawRoot(), dir.name)).catch(() => [] as string[])
|
|
173
|
+
for (const name of files) {
|
|
174
|
+
const date = RAW_FILE.exec(name)?.[1]
|
|
175
|
+
if (!date) continue
|
|
176
|
+
const file = join(this.rawRoot(), dir.name, name)
|
|
177
|
+
const info = await stat(file).catch(() => undefined)
|
|
178
|
+
if (!info) continue
|
|
179
|
+
if (info.mtimeMs >= cutoff) continue
|
|
180
|
+
await rm(file, { force: true }).catch(() => {})
|
|
181
|
+
removed += 1
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
if (removed > 0) this.deps.logger.info(`已清理 ${removed} 个过期日记素材文件`)
|
|
185
|
+
return removed
|
|
186
|
+
}
|
|
187
|
+
}
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import { type ChatTarget, targetKey, targetLabel } from "../chat"
|
|
2
|
+
import type { CommandDefinition } from "../commands"
|
|
3
|
+
import type { QQBotConfig } from "../config"
|
|
4
|
+
import type { Logger } from "../logger"
|
|
5
|
+
import type { OutboundMedia } from "../media-path"
|
|
6
|
+
import type { QQClient } from "../naplink/client"
|
|
7
|
+
import type { SendRateLimiter } from "../rate-limit"
|
|
8
|
+
import type { SensitiveChecker } from "../sensitive"
|
|
9
|
+
import { createPlainSender, sendFileMessage } from "../tools/qq"
|
|
10
|
+
import type { DiaryCollector } from "./collector"
|
|
11
|
+
import { dateKey, isDateKey } from "./format"
|
|
12
|
+
import type { DiaryStore } from "./store"
|
|
13
|
+
import type { DiarySummarizer } from "./summary"
|
|
14
|
+
|
|
15
|
+
/** 命令名。TUI 侧注册为 `qq-diary`,QQ 私聊里用 `/diary`。 */
|
|
16
|
+
export const DIARY_COMMAND = "diary"
|
|
17
|
+
|
|
18
|
+
/** `/diary` 支持的动作。 */
|
|
19
|
+
export type DiaryAction = "write" | "list" | "show" | "auto" | "usage"
|
|
20
|
+
|
|
21
|
+
/** 解析出来的命令参数。 */
|
|
22
|
+
export interface DiaryCommandArgs {
|
|
23
|
+
action: DiaryAction
|
|
24
|
+
/** 日期键,形如 `2026-11-10`。 */
|
|
25
|
+
date?: string
|
|
26
|
+
/** 手写日记的正文。 */
|
|
27
|
+
content?: string
|
|
28
|
+
/** 列出最近几篇。 */
|
|
29
|
+
days?: number
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 列出日记时默认看几篇。 */
|
|
33
|
+
export const DIARY_LIST_DAYS = 7
|
|
34
|
+
|
|
35
|
+
/** 命令用法说明。 */
|
|
36
|
+
export const DIARY_USAGE = [
|
|
37
|
+
"用法:/diary <write|list|show|auto>",
|
|
38
|
+
"write [日期] <内容> 写一篇日记(默认今天)",
|
|
39
|
+
"list [天数] 列出最近几篇日记(默认 7 篇)",
|
|
40
|
+
"show <日期> 看某天的日记,日期用 YYYY-MM-DD",
|
|
41
|
+
"auto [日期] 立刻生成或重生成某天的自动总结",
|
|
42
|
+
].join("\n")
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 解析命令参数。
|
|
46
|
+
*
|
|
47
|
+
* 兼容 `/diary write ...`、`/qq-diary write ...` 与 `diary write ...` 三种写法。
|
|
48
|
+
*/
|
|
49
|
+
export function parseDiaryArgs(text: string): DiaryCommandArgs {
|
|
50
|
+
const raw = text.trim()
|
|
51
|
+
const withoutName = raw.replace(/^\/?(?:qq-)?diary\b[::]?/i, "").trim()
|
|
52
|
+
if (!withoutName) return { action: "usage" }
|
|
53
|
+
const parts = withoutName.split(/\s+/)
|
|
54
|
+
const action = (parts[0] ?? "").toLowerCase()
|
|
55
|
+
const tail = parts.slice(1).join(" ").trim()
|
|
56
|
+
|
|
57
|
+
if (action === "write") {
|
|
58
|
+
// 正文前面可以带一个日期:`write 2026-11-10 今天聊了…`。
|
|
59
|
+
const match = /^(\d{4}-\d{2}-\d{2})\s+([\s\S]*)$/.exec(tail)
|
|
60
|
+
const date = match?.[1]
|
|
61
|
+
if (date && isDateKey(date)) {
|
|
62
|
+
return { action: "write", date, content: (match?.[2] ?? "").trim() }
|
|
63
|
+
}
|
|
64
|
+
return { action: "write", content: tail }
|
|
65
|
+
}
|
|
66
|
+
if (action === "list") {
|
|
67
|
+
const days = Number(tail)
|
|
68
|
+
return { action: "list", days: Number.isInteger(days) && days > 0 ? days : DIARY_LIST_DAYS }
|
|
69
|
+
}
|
|
70
|
+
if (action === "show") {
|
|
71
|
+
const date = (parts[1] ?? "").trim()
|
|
72
|
+
return date ? { action: "show", date } : { action: "show" }
|
|
73
|
+
}
|
|
74
|
+
if (action === "auto") {
|
|
75
|
+
const date = (parts[1] ?? "").trim()
|
|
76
|
+
return date ? { action: "auto", date } : { action: "auto" }
|
|
77
|
+
}
|
|
78
|
+
return { action: "usage" }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** 日记命令的执行依赖。 */
|
|
82
|
+
export interface DiaryRunnerDeps {
|
|
83
|
+
config: QQBotConfig
|
|
84
|
+
logger: Logger
|
|
85
|
+
client: QQClient
|
|
86
|
+
limiter: SendRateLimiter
|
|
87
|
+
/** 出站媒体的路径把关,发送日记文件时用。 */
|
|
88
|
+
outbound: OutboundMedia
|
|
89
|
+
/** 出站敏感信息检查。 */
|
|
90
|
+
sensitive: SensitiveChecker
|
|
91
|
+
/** 日记读写。 */
|
|
92
|
+
store: DiaryStore
|
|
93
|
+
/** 素材读取。 */
|
|
94
|
+
collector: DiaryCollector
|
|
95
|
+
/** 自动总结。 */
|
|
96
|
+
summarizer: DiarySummarizer
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** 日记命令的执行器:TUI 命令与 QQ 私聊共用。 */
|
|
100
|
+
export interface DiaryCommandRunner {
|
|
101
|
+
/** 在指定聊天里执行命令文本。 */
|
|
102
|
+
run(target: ChatTarget, text: string): Promise<void>
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** 列出日记的文本。 */
|
|
106
|
+
export function formatDiaryList(
|
|
107
|
+
chat: string,
|
|
108
|
+
days: number,
|
|
109
|
+
entries: readonly { date: string; title: string }[],
|
|
110
|
+
): string {
|
|
111
|
+
const head = `日记(${chat},最近 ${days} 篇)`
|
|
112
|
+
if (entries.length === 0) return `${head}\n还没有日记。`
|
|
113
|
+
return [head, ...entries.map((entry) => `${entry.date} ${entry.title}`)].join("\n")
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** 创建日记命令执行器;同一时间只跑一个自动总结任务。 */
|
|
117
|
+
export function createDiaryRunner(deps: DiaryRunnerDeps): DiaryCommandRunner {
|
|
118
|
+
const { config, logger, client, limiter, outbound, sensitive, store, collector, summarizer } =
|
|
119
|
+
deps
|
|
120
|
+
let running = false
|
|
121
|
+
|
|
122
|
+
const report = createPlainSender(client, {
|
|
123
|
+
delayMs: config.sendDelayMs,
|
|
124
|
+
limiter,
|
|
125
|
+
logger,
|
|
126
|
+
failure: (target) => `${targetLabel(target)} 发送日记结果失败`,
|
|
127
|
+
})
|
|
128
|
+
|
|
129
|
+
/** 发一篇日记:一行说明加文件本身。 */
|
|
130
|
+
const sendDiaryFile = async (target: ChatTarget, date: string): Promise<void> => {
|
|
131
|
+
const file = store.filePath(targetKey(target), date)
|
|
132
|
+
await sendFileMessage(client, target, file, {
|
|
133
|
+
name: `日记-${date}.md`,
|
|
134
|
+
limiter,
|
|
135
|
+
outbound,
|
|
136
|
+
sensitive,
|
|
137
|
+
})
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const runWrite = async (target: ChatTarget, args: DiaryCommandArgs): Promise<void> => {
|
|
141
|
+
const content = (args.content ?? "").trim()
|
|
142
|
+
if (!content) {
|
|
143
|
+
await report(target, "要写什么?用法:/diary write [日期] <内容>")
|
|
144
|
+
return
|
|
145
|
+
}
|
|
146
|
+
const date = args.date ?? dateKey()
|
|
147
|
+
const entry = await store.write(targetKey(target), date, {
|
|
148
|
+
title: firstLine(content),
|
|
149
|
+
body: content,
|
|
150
|
+
source: "manual",
|
|
151
|
+
})
|
|
152
|
+
await report(target, `已写入 ${date} 的日记:${entry.title}`)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const runList = async (target: ChatTarget, args: DiaryCommandArgs): Promise<void> => {
|
|
156
|
+
const days = args.days ?? DIARY_LIST_DAYS
|
|
157
|
+
const entries = await store.list(targetKey(target), days)
|
|
158
|
+
await report(target, formatDiaryList(targetKey(target), days, entries))
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const runShow = async (target: ChatTarget, args: DiaryCommandArgs): Promise<void> => {
|
|
162
|
+
const date = args.date ?? ""
|
|
163
|
+
if (!date || !isDateKey(date)) {
|
|
164
|
+
await report(target, "要看哪天的日记?用法:/diary show <日期>,日期用 YYYY-MM-DD")
|
|
165
|
+
return
|
|
166
|
+
}
|
|
167
|
+
const entry = await store.read(targetKey(target), date)
|
|
168
|
+
if (!entry) {
|
|
169
|
+
await report(target, `没有找到 ${date} 的日记。`)
|
|
170
|
+
return
|
|
171
|
+
}
|
|
172
|
+
await report(target, `${date} 的日记`)
|
|
173
|
+
await sendDiaryFile(target, date).catch((error: unknown) => {
|
|
174
|
+
logger.error(`${targetLabel(target)} 发送日记文件失败`, error)
|
|
175
|
+
return report(
|
|
176
|
+
target,
|
|
177
|
+
`日记文件发送失败:${error instanceof Error ? error.message : String(error)}`,
|
|
178
|
+
)
|
|
179
|
+
})
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const runAuto = async (target: ChatTarget, args: DiaryCommandArgs): Promise<void> => {
|
|
183
|
+
const date = args.date ?? dateKey()
|
|
184
|
+
if (!isDateKey(date)) {
|
|
185
|
+
await report(target, "要生成哪天的日记?用法:/diary auto [日期],日期用 YYYY-MM-DD")
|
|
186
|
+
return
|
|
187
|
+
}
|
|
188
|
+
if (!(await collector.has(targetKey(target), date))) {
|
|
189
|
+
await report(target, `${date} 没有聊天素材,跳过总结。`)
|
|
190
|
+
return
|
|
191
|
+
}
|
|
192
|
+
if (running) {
|
|
193
|
+
await report(target, "已经有日记总结任务在跑了,请等它结束。")
|
|
194
|
+
return
|
|
195
|
+
}
|
|
196
|
+
running = true
|
|
197
|
+
// 总结可能要跑很久,放到后台执行,结果用 QQ 消息回。
|
|
198
|
+
void (async () => {
|
|
199
|
+
await report(target, `开始生成 ${date} 的日记…`)
|
|
200
|
+
const title = await summarizer.summarize(targetKey(target), date)
|
|
201
|
+
if (!title) {
|
|
202
|
+
await report(target, `${date} 的日记总结失败,素材保留待下次重试。`)
|
|
203
|
+
return
|
|
204
|
+
}
|
|
205
|
+
await report(target, `${date} 的日记已生成:${title}`)
|
|
206
|
+
await sendDiaryFile(target, date).catch((error: unknown) => {
|
|
207
|
+
logger.error(`${targetLabel(target)} 发送日记文件失败`, error)
|
|
208
|
+
})
|
|
209
|
+
})()
|
|
210
|
+
.catch((error: unknown) => {
|
|
211
|
+
logger.error("日记总结任务失败", error)
|
|
212
|
+
return report(
|
|
213
|
+
target,
|
|
214
|
+
`日记总结失败:${error instanceof Error ? error.message : String(error)}`,
|
|
215
|
+
)
|
|
216
|
+
})
|
|
217
|
+
.finally(() => {
|
|
218
|
+
running = false
|
|
219
|
+
})
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const run = async (target: ChatTarget, text: string): Promise<void> => {
|
|
223
|
+
const args = parseDiaryArgs(text)
|
|
224
|
+
switch (args.action) {
|
|
225
|
+
case "write":
|
|
226
|
+
await runWrite(target, args)
|
|
227
|
+
return
|
|
228
|
+
case "list":
|
|
229
|
+
await runList(target, args)
|
|
230
|
+
return
|
|
231
|
+
case "show":
|
|
232
|
+
await runShow(target, args)
|
|
233
|
+
return
|
|
234
|
+
case "auto":
|
|
235
|
+
await runAuto(target, args)
|
|
236
|
+
return
|
|
237
|
+
default:
|
|
238
|
+
await report(target, DIARY_USAGE)
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
return { run }
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** 取正文的第一行做标题。 */
|
|
246
|
+
function firstLine(content: string): string {
|
|
247
|
+
const line = content
|
|
248
|
+
.split(/\r?\n/)
|
|
249
|
+
.map((item) => item.trim())
|
|
250
|
+
.find((item) => item.length > 0)
|
|
251
|
+
return line ?? ""
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** 日记命令的用法行,`/help` 直接复用。 */
|
|
255
|
+
const DIARY_USAGE_LINES = [
|
|
256
|
+
"/diary write [日期] <内容> — 写一篇日记(默认今天)",
|
|
257
|
+
"/diary list [天数] — 列出最近几篇日记(默认 7 篇)",
|
|
258
|
+
"/diary show <日期> — 看某天的日记,日期用 YYYY-MM-DD",
|
|
259
|
+
"/diary auto [日期] — 立刻生成或重生成某天的自动总结",
|
|
260
|
+
]
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* 把日记命令接进共享命令表。
|
|
264
|
+
*
|
|
265
|
+
* TUI 侧注册成 `/qq-diary`,QQ 私聊里是 `/diary`;
|
|
266
|
+
* 命令自己负责发消息,所以 `run` 不返回文本。
|
|
267
|
+
*/
|
|
268
|
+
export function diaryCommand(runner: DiaryCommandRunner): CommandDefinition {
|
|
269
|
+
return {
|
|
270
|
+
name: DIARY_COMMAND,
|
|
271
|
+
description: "写、看、列出聊天日记:write 手写,show 看某天,list 列最近几篇,auto 自动总结。",
|
|
272
|
+
usage: DIARY_USAGE_LINES,
|
|
273
|
+
run: async (context, args) => {
|
|
274
|
+
await runner.run(context.target, args.join(" "))
|
|
275
|
+
},
|
|
276
|
+
}
|
|
277
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 日记的文件格式:日期键、聊天目录名与 front matter。
|
|
3
|
+
*
|
|
4
|
+
* 日记是自包含的 Markdown 文件:元数据放在 front matter 里,
|
|
5
|
+
* 程序读它,人也能直接打开看。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** 日记来源:自动总结、命令手写、模型用工具写入。 */
|
|
9
|
+
export type DiarySource = "auto" | "manual" | "model"
|
|
10
|
+
|
|
11
|
+
/** 日记的元数据,对应文件里的 front matter。 */
|
|
12
|
+
export interface DiaryMeta {
|
|
13
|
+
/** 日期键,形如 `2026-11-10`。 */
|
|
14
|
+
date: string
|
|
15
|
+
/** 聊天键,形如 `group:123`。 */
|
|
16
|
+
chat: string
|
|
17
|
+
/** 来源。 */
|
|
18
|
+
source: DiarySource
|
|
19
|
+
/** 首次写入时间(ISO 字符串)。 */
|
|
20
|
+
created: string
|
|
21
|
+
/** 最近更新时间(ISO 字符串)。 */
|
|
22
|
+
updated: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 一篇日记的完整内容。 */
|
|
26
|
+
export interface DiaryEntry extends DiaryMeta {
|
|
27
|
+
/** 标题,不含 `#`。 */
|
|
28
|
+
title: string
|
|
29
|
+
/** 正文。 */
|
|
30
|
+
body: string
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** 解析出来的日记。 */
|
|
34
|
+
export interface ParsedDiary {
|
|
35
|
+
meta: DiaryMeta
|
|
36
|
+
title: string
|
|
37
|
+
body: string
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 合法的来源。 */
|
|
41
|
+
const SOURCES: readonly DiarySource[] = ["auto", "manual", "model"]
|
|
42
|
+
|
|
43
|
+
/** 日期键的形状。 */
|
|
44
|
+
const DATE_KEY = /^\d{4}-\d{2}-\d{2}$/
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 本地时区的日期键。
|
|
48
|
+
*
|
|
49
|
+
* 用本地时区而不是 UTC:聊天里的「今天」是用户所在时区的今天。
|
|
50
|
+
*/
|
|
51
|
+
export function dateKey(date: Date = new Date()): string {
|
|
52
|
+
const year = date.getFullYear()
|
|
53
|
+
const month = String(date.getMonth() + 1).padStart(2, "0")
|
|
54
|
+
const day = String(date.getDate()).padStart(2, "0")
|
|
55
|
+
return `${year}-${month}-${day}`
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 日期键是否合法。
|
|
60
|
+
*
|
|
61
|
+
* 只看形状不够:`2026-02-30` 形状对得上,实际并不存在。
|
|
62
|
+
*/
|
|
63
|
+
export function isDateKey(value: string): boolean {
|
|
64
|
+
if (!DATE_KEY.test(value)) return false
|
|
65
|
+
const parsed = new Date(`${value}T00:00:00`)
|
|
66
|
+
return !Number.isNaN(parsed.getTime()) && dateKey(parsed) === value
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* 聊天目录名:聊天键里的 `:` 换成 `-`。
|
|
71
|
+
*
|
|
72
|
+
* 目录名直接来自外部输入(群号、私聊号),先兜一层字符白名单,
|
|
73
|
+
* 免得出现路径分隔符或隐藏目录。
|
|
74
|
+
*/
|
|
75
|
+
export function chatSlug(chat: string): string {
|
|
76
|
+
const slug = chat.replace(/[^A-Za-z0-9_-]/g, "-")
|
|
77
|
+
return slug || "unknown"
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 日记成品文件名。 */
|
|
81
|
+
export function diaryFileName(date: string): string {
|
|
82
|
+
return `${date}.md`
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** 标题为空时的兜底。 */
|
|
86
|
+
export function fallbackTitle(date: string): string {
|
|
87
|
+
return `${date} 的日记`
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 序列化一篇日记。
|
|
92
|
+
*
|
|
93
|
+
* 顺序固定,便于人工阅读与 `diff`。
|
|
94
|
+
*/
|
|
95
|
+
export function serializeDiary(entry: DiaryEntry): string {
|
|
96
|
+
return [
|
|
97
|
+
"---",
|
|
98
|
+
`date: ${entry.date}`,
|
|
99
|
+
`chat: ${entry.chat}`,
|
|
100
|
+
`source: ${entry.source}`,
|
|
101
|
+
`created: ${entry.created}`,
|
|
102
|
+
`updated: ${entry.updated}`,
|
|
103
|
+
"---",
|
|
104
|
+
"",
|
|
105
|
+
`# ${entry.title}`,
|
|
106
|
+
"",
|
|
107
|
+
entry.body.trim(),
|
|
108
|
+
"",
|
|
109
|
+
].join("\n")
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* 解析一篇日记。
|
|
114
|
+
*
|
|
115
|
+
* front matter 与正文之间用空行分开;正文第一行是标题。
|
|
116
|
+
* 解析不了就返回 undefined,调用方按「没有日记」处理。
|
|
117
|
+
*/
|
|
118
|
+
export function parseDiary(content: string): ParsedDiary | undefined {
|
|
119
|
+
const text = String(content ?? "").replace(/\r\n/g, "\n")
|
|
120
|
+
if (!text.startsWith("---\n")) return undefined
|
|
121
|
+
const end = text.indexOf("\n---", 3)
|
|
122
|
+
if (end < 0) return undefined
|
|
123
|
+
const meta: Record<string, string> = {}
|
|
124
|
+
for (const line of text.slice(4, end).split("\n")) {
|
|
125
|
+
const separator = line.indexOf(": ")
|
|
126
|
+
if (separator <= 0) continue
|
|
127
|
+
meta[line.slice(0, separator).trim()] = line.slice(separator + 1).trim()
|
|
128
|
+
}
|
|
129
|
+
const rest = text.slice(end + 4).replace(/^\n+/, "")
|
|
130
|
+
const lines = rest.split("\n")
|
|
131
|
+
let title = ""
|
|
132
|
+
let bodyStart = 0
|
|
133
|
+
for (const [index, line] of lines.entries()) {
|
|
134
|
+
const trimmed = line.trim()
|
|
135
|
+
if (!trimmed) continue
|
|
136
|
+
if (trimmed.startsWith("# ")) {
|
|
137
|
+
title = trimmed.slice(2).trim()
|
|
138
|
+
bodyStart = index + 1
|
|
139
|
+
}
|
|
140
|
+
break
|
|
141
|
+
}
|
|
142
|
+
const date = meta.date ?? ""
|
|
143
|
+
const source = SOURCES.includes(meta.source as DiarySource)
|
|
144
|
+
? (meta.source as DiarySource)
|
|
145
|
+
: "auto"
|
|
146
|
+
return {
|
|
147
|
+
meta: {
|
|
148
|
+
date,
|
|
149
|
+
chat: meta.chat ?? "",
|
|
150
|
+
source,
|
|
151
|
+
created: meta.created ?? "",
|
|
152
|
+
updated: meta.updated ?? "",
|
|
153
|
+
},
|
|
154
|
+
title: title || fallbackTitle(date),
|
|
155
|
+
body: lines.slice(bodyStart).join("\n").trim(),
|
|
156
|
+
}
|
|
157
|
+
}
|