@linjz/opencode-qqbot 0.3.12 → 0.3.13

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.
Files changed (45) hide show
  1. package/bin/openqq-setup.mjs +50 -50
  2. package/bin/openqq.js +47 -47
  3. package/dist/opencode-qqbot-plugin.js +3 -3
  4. package/dist/openqq-bot.js +1033 -191
  5. package/package.json +2 -2
  6. package/src/_FOLDER.md +19 -19
  7. package/src/bridge.ts +135 -15
  8. package/src/commands.ts +554 -554
  9. package/src/config.ts +121 -121
  10. package/src/core/bot-launcher.ts +146 -146
  11. package/src/core/card-approval.ts +146 -146
  12. package/src/core/context-buffer.ts +78 -78
  13. package/src/core/delivery.ts +105 -13
  14. package/src/core/discovery.ts +151 -151
  15. package/src/core/error-rescue.ts +33 -33
  16. package/src/core/file-log.ts +45 -45
  17. package/src/core/form-bridge.ts +388 -72
  18. package/src/core/form-journal.ts +214 -0
  19. package/src/core/gateway-state.ts +68 -0
  20. package/src/core/inbound-dedupe.ts +43 -0
  21. package/src/core/inflight-journal.ts +148 -21
  22. package/src/core/instance-lock.ts +28 -1
  23. package/src/core/linkwatch.ts +195 -195
  24. package/src/core/message-queue.ts +11 -0
  25. package/src/core/mirror.ts +182 -182
  26. package/src/core/outbox.ts +522 -0
  27. package/src/core/permission.ts +301 -301
  28. package/src/core/reply-limiter.ts +106 -106
  29. package/src/core/send-media.ts +90 -90
  30. package/src/core/util.ts +8 -8
  31. package/src/index.ts +162 -162
  32. package/src/opencode/_FOLDER.md +11 -11
  33. package/src/opencode/client.ts +89 -8
  34. package/src/opencode/eventstream.ts +138 -138
  35. package/src/opencode/history.ts +143 -143
  36. package/src/opencode/mirror.ts +85 -85
  37. package/src/opencode/sessions.ts +158 -158
  38. package/src/plugin-entry.ts +112 -112
  39. package/src/qq/_FOLDER.md +13 -13
  40. package/src/qq/api.ts +539 -539
  41. package/src/qq/gateway.ts +69 -20
  42. package/src/qq/media.ts +219 -219
  43. package/src/qq/sender.ts +300 -300
  44. package/src/qq/types.ts +154 -154
  45. package/tsconfig.json +24 -24
@@ -1,85 +1,85 @@
1
- // @input: ./client (SessionMessage), ./history (redactSecrets)
2
- // @output: buildDigest
3
- // @pos: opencode层 - 摘要镜像(桌面轮次完成 → QQ 摘要卡)
4
- //
5
- // GET /session/{id}/message 实测倒序(新→旧):最后一条 user 消息至末尾 = 最近一轮。
6
- // 无 assistant 正文的轮次(纯工具/中断)返回 null 不镜像,避免噪音(E1 债务清单)。
7
-
8
- import type { SessionMessage } from "./client.js"
9
- import { redactSecrets } from "./history.js"
10
-
11
- const USER_CLIP = 160
12
-
13
- // E2(2026-10-29,用户要求"摘要回全文"):答案截断上限改为运行时可配——
14
- // 默认 0=不截断回全文(投递层 splitMessage 自动分条送达);设
15
- // QQ_DIGEST_ANSWER_MAX_CHARS>0 可恢复旧的截断模式。用户提问行(USER_CLIP)
16
- // 保持截断不变(问题行只是定位上下文,全文意义不大)。
17
- function answerClipLimit(): number {
18
- const n = Number(process.env.QQ_DIGEST_ANSWER_MAX_CHARS ?? "0")
19
- return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0
20
- }
21
-
22
- // 逻辑回合并发幂等键:同一用户消息 + 最终 assistant。不同 location 的
23
- // execution.succeeded 事件 ID 可以不同,但同一逻辑回合仍只应镜像一次。
24
- export function digestTurnKey(messages: SessionMessage[]): string | null {
25
- const ordered = [...messages].reverse()
26
- let lastUserIdx = -1
27
- for (let i = ordered.length - 1; i >= 0; i--) {
28
- if (ordered[i].type === "user") {
29
- lastUserIdx = i
30
- break
31
- }
32
- }
33
- if (lastUserIdx < 0) return null
34
- for (let i = ordered.length - 1; i > lastUserIdx; i--) {
35
- const m = ordered[i]
36
- if (m.type !== "assistant" || !(m.content ?? []).some((p) => p.type === "text" && p.text?.trim())) continue
37
- return `${ordered[lastUserIdx].id ?? `user@${lastUserIdx}`}:${m.id ?? `assistant@${i}`}`
38
- }
39
- return null
40
- }
41
-
42
- // 构建最近一轮问答的摘要卡;返回 null = 无可镜像正文。
43
- export function buildDigest(messages: SessionMessage[]): string | null {
44
- const ordered = [...messages].reverse()
45
-
46
- let lastUserIdx = -1
47
- for (let i = ordered.length - 1; i >= 0; i--) {
48
- if (ordered[i].type === "user") {
49
- lastUserIdx = i
50
- break
51
- }
52
- }
53
- if (lastUserIdx < 0) return null
54
-
55
- const userText = ((ordered[lastUserIdx] as { text?: string }).text ?? "").trim()
56
-
57
- let answer = ""
58
- for (let i = ordered.length - 1; i > lastUserIdx; i--) {
59
- const m = ordered[i]
60
- if (m.type !== "assistant") continue
61
- const parts = (m.content ?? []).filter((p) => p.type === "text" && p.text?.trim()).map((p) => p.text!.trim())
62
- if (parts.length > 0) {
63
- answer = parts.join("\n").trim()
64
- break
65
- }
66
- }
67
- if (!answer) return null
68
-
69
- const lines = ["📋 桌面问答摘要"]
70
- if (userText) lines.push(`🧑 ${clip(userText, USER_CLIP)}`)
71
- const clipLimit = answerClipLimit()
72
- if (clipLimit > 0) {
73
- lines.push(`🤖 ${clip(answer, clipLimit)}`)
74
- if (answer.length > clipLimit) lines.push(`(答案共 ${answer.length} 字,回 /history 看更多)`)
75
- } else {
76
- // 全文模式:保留原文换行/排版(clip 的空白折叠只用于截断模式)
77
- lines.push(`🤖 ${answer}`)
78
- }
79
- return redactSecrets(lines.join("\n"))
80
- }
81
-
82
- function clip(value: string, max: number): string {
83
- const s = value.replace(/\s+/g, " ").trim()
84
- return s.length > max ? `${s.slice(0, max)}…` : s
85
- }
1
+ // @input: ./client (SessionMessage), ./history (redactSecrets)
2
+ // @output: buildDigest
3
+ // @pos: opencode层 - 摘要镜像(桌面轮次完成 → QQ 摘要卡)
4
+ //
5
+ // GET /session/{id}/message 实测倒序(新→旧):最后一条 user 消息至末尾 = 最近一轮。
6
+ // 无 assistant 正文的轮次(纯工具/中断)返回 null 不镜像,避免噪音(E1 债务清单)。
7
+
8
+ import type { SessionMessage } from "./client.js"
9
+ import { redactSecrets } from "./history.js"
10
+
11
+ const USER_CLIP = 160
12
+
13
+ // E2(2026-10-29,用户要求"摘要回全文"):答案截断上限改为运行时可配——
14
+ // 默认 0=不截断回全文(投递层 splitMessage 自动分条送达);设
15
+ // QQ_DIGEST_ANSWER_MAX_CHARS>0 可恢复旧的截断模式。用户提问行(USER_CLIP)
16
+ // 保持截断不变(问题行只是定位上下文,全文意义不大)。
17
+ function answerClipLimit(): number {
18
+ const n = Number(process.env.QQ_DIGEST_ANSWER_MAX_CHARS ?? "0")
19
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0
20
+ }
21
+
22
+ // 逻辑回合并发幂等键:同一用户消息 + 最终 assistant。不同 location 的
23
+ // execution.succeeded 事件 ID 可以不同,但同一逻辑回合仍只应镜像一次。
24
+ export function digestTurnKey(messages: SessionMessage[]): string | null {
25
+ const ordered = [...messages].reverse()
26
+ let lastUserIdx = -1
27
+ for (let i = ordered.length - 1; i >= 0; i--) {
28
+ if (ordered[i].type === "user") {
29
+ lastUserIdx = i
30
+ break
31
+ }
32
+ }
33
+ if (lastUserIdx < 0) return null
34
+ for (let i = ordered.length - 1; i > lastUserIdx; i--) {
35
+ const m = ordered[i]
36
+ if (m.type !== "assistant" || !(m.content ?? []).some((p) => p.type === "text" && p.text?.trim())) continue
37
+ return `${ordered[lastUserIdx].id ?? `user@${lastUserIdx}`}:${m.id ?? `assistant@${i}`}`
38
+ }
39
+ return null
40
+ }
41
+
42
+ // 构建最近一轮问答的摘要卡;返回 null = 无可镜像正文。
43
+ export function buildDigest(messages: SessionMessage[]): string | null {
44
+ const ordered = [...messages].reverse()
45
+
46
+ let lastUserIdx = -1
47
+ for (let i = ordered.length - 1; i >= 0; i--) {
48
+ if (ordered[i].type === "user") {
49
+ lastUserIdx = i
50
+ break
51
+ }
52
+ }
53
+ if (lastUserIdx < 0) return null
54
+
55
+ const userText = ((ordered[lastUserIdx] as { text?: string }).text ?? "").trim()
56
+
57
+ let answer = ""
58
+ for (let i = ordered.length - 1; i > lastUserIdx; i--) {
59
+ const m = ordered[i]
60
+ if (m.type !== "assistant") continue
61
+ const parts = (m.content ?? []).filter((p) => p.type === "text" && p.text?.trim()).map((p) => p.text!.trim())
62
+ if (parts.length > 0) {
63
+ answer = parts.join("\n").trim()
64
+ break
65
+ }
66
+ }
67
+ if (!answer) return null
68
+
69
+ const lines = ["📋 桌面问答摘要"]
70
+ if (userText) lines.push(`🧑 ${clip(userText, USER_CLIP)}`)
71
+ const clipLimit = answerClipLimit()
72
+ if (clipLimit > 0) {
73
+ lines.push(`🤖 ${clip(answer, clipLimit)}`)
74
+ if (answer.length > clipLimit) lines.push(`(答案共 ${answer.length} 字,回 /history 看更多)`)
75
+ } else {
76
+ // 全文模式:保留原文换行/排版(clip 的空白折叠只用于截断模式)
77
+ lines.push(`🤖 ${answer}`)
78
+ }
79
+ return redactSecrets(lines.join("\n"))
80
+ }
81
+
82
+ function clip(value: string, max: number): string {
83
+ const s = value.replace(/\s+/g, " ").trim()
84
+ return s.length > max ? `${s.slice(0, max)}…` : s
85
+ }
@@ -1,158 +1,158 @@
1
- // @input: ./client (OpencodeClient)
2
- // @output: SessionManager, UserSession
3
- // @pos: opencode层 - QQ用户<->OpenCode Session 映射管理(持久化到 ~/.openqq/sessions.json)
4
- import { existsSync, readFileSync, mkdirSync, writeFileSync } from "fs"
5
- import { join } from "path"
6
- import { homedir } from "os"
7
- import type { OpencodeClient } from "./client.js"
8
-
9
- interface UserSession {
10
- sessionId: string
11
- title?: string
12
- modelId?: string
13
- providerId?: string
14
- agentId?: string
15
- }
16
-
17
- const STORE_DIR = join(homedir(), ".openqq")
18
- const STORE_FILE = join(STORE_DIR, "sessions.json")
19
-
20
- export class SessionManager {
21
- private sessions = new Map<string, UserSession>()
22
- private client: OpencodeClient
23
-
24
- constructor(client: OpencodeClient) {
25
- this.client = client
26
- this.loadSessions()
27
- }
28
-
29
- // 持久化映射:bot 重启(升级/故障)不再丢失 QQ↔会话绑定
30
- //(2026-10-13 实测教训:重启清空内存映射 → 用户 QQ 消息落到全新会话,AI 失忆从零探索)。
31
- private loadSessions(): void {
32
- try {
33
- if (!existsSync(STORE_FILE)) return
34
- // 手工编辑或 PowerShell Out-File 常带 BOM,JSON.parse 会炸——先剥掉
35
- const raw = readFileSync(STORE_FILE, "utf8").replace(/^\uFEFF/, "")
36
- const parsed = JSON.parse(raw) as Record<string, UserSession>
37
- for (const [userId, session] of Object.entries(parsed)) {
38
- if (session?.sessionId) this.sessions.set(userId, session)
39
- }
40
- if (this.sessions.size > 0) {
41
- console.log(`[sessions] 已从磁盘恢复 ${this.sessions.size} 个用户会话映射`)
42
- }
43
- } catch (error) {
44
- console.error("[sessions] 会话映射加载失败(忽略,按全新处理):", error)
45
- }
46
- }
47
-
48
- private saveSessions(): void {
49
- try {
50
- if (!existsSync(STORE_DIR)) mkdirSync(STORE_DIR, { recursive: true })
51
- writeFileSync(STORE_FILE, JSON.stringify(Object.fromEntries(this.sessions), null, 2), "utf8")
52
- } catch (error) {
53
- console.error("[sessions] 会话映射持久化失败:", error)
54
- }
55
- }
56
-
57
- async getOrCreate(userId: string): Promise<UserSession> {
58
- const existing = this.sessions.get(userId)
59
- if (existing) return existing
60
-
61
- const result = await this.client.session.create({})
62
- const session: UserSession = {
63
- sessionId: result.data!.id,
64
- title: result.data!.title,
65
- }
66
- this.sessions.set(userId, session)
67
- this.saveSessions()
68
- return session
69
- }
70
-
71
- async createNew(userId: string): Promise<UserSession> {
72
- const result = await this.client.session.create({})
73
- const session: UserSession = {
74
- sessionId: result.data!.id,
75
- title: result.data!.title,
76
- }
77
- this.sessions.set(userId, session)
78
- this.saveSessions()
79
- return session
80
- }
81
-
82
- switchSession(userId: string, sessionId: string, title?: string): void {
83
- const prev = this.sessions.get(userId)
84
- const changed = prev?.sessionId !== sessionId
85
- this.sessions.set(userId, {
86
- ...prev,
87
- sessionId,
88
- title,
89
- })
90
- this.saveSessions()
91
- // 切到别的会话时,把本用户记住的模型/Agent 重放到目标会话
92
- //(v2 模型是 session 级设置,不跟随 prompt)。
93
- if (changed) {
94
- void this.applySettings(userId)
95
- }
96
- }
97
-
98
- getSession(userId: string): UserSession | undefined {
99
- return this.sessions.get(userId)
100
- }
101
-
102
- // 枚举全部映射(摘要镜像订阅、会话→用户反查用)
103
- all(): Array<{ userId: string; sessionId: string }> {
104
- return [...this.sessions.entries()].map(([userId, s]) => ({ userId, sessionId: s.sessionId }))
105
- }
106
-
107
- // v2: 模型/agent 是 session 级(/prompt body 会被剥离),必须调 session 端点。
108
- // 先服务端成功再落本地,避免 /model 显示成功但实际没生效。
109
- async setModel(userId: string, providerId: string, modelId: string): Promise<void> {
110
- const s = this.sessions.get(userId)
111
- if (!s) return
112
- await this.client.session.setModel({
113
- path: { id: s.sessionId },
114
- body: { model: { providerID: providerId, id: modelId } },
115
- })
116
- s.providerId = providerId
117
- s.modelId = modelId
118
- this.saveSessions()
119
- }
120
-
121
- async setAgent(userId: string, agentId: string): Promise<void> {
122
- const s = this.sessions.get(userId)
123
- if (!s) return
124
- await this.client.session.setAgent({ path: { id: s.sessionId }, body: { agent: agentId } })
125
- s.agentId = agentId
126
- this.saveSessions()
127
- }
128
-
129
- private async applySettings(userId: string): Promise<void> {
130
- const s = this.sessions.get(userId)
131
- if (!s) return
132
- try {
133
- if (s.providerId && s.modelId) {
134
- await this.client.session.setModel({
135
- path: { id: s.sessionId },
136
- body: { model: { providerID: s.providerId, id: s.modelId } },
137
- })
138
- }
139
- if (s.agentId) {
140
- await this.client.session.setAgent({ path: { id: s.sessionId }, body: { agent: s.agentId } })
141
- }
142
- } catch (error) {
143
- // 切会话是主操作,设置重放失败只记日志(目标会话用其自身/默认设置)
144
- console.error("[sessions] 重放模型/Agent 设置失败:", error)
145
- }
146
- }
147
-
148
- getModel(userId: string): { providerId?: string; modelId?: string } {
149
- const s = this.sessions.get(userId)
150
- return { providerId: s?.providerId, modelId: s?.modelId }
151
- }
152
-
153
- getAgent(userId: string): string | undefined {
154
- return this.sessions.get(userId)?.agentId
155
- }
156
- }
157
-
158
- export type { UserSession }
1
+ // @input: ./client (OpencodeClient)
2
+ // @output: SessionManager, UserSession
3
+ // @pos: opencode层 - QQ用户<->OpenCode Session 映射管理(持久化到 ~/.openqq/sessions.json)
4
+ import { existsSync, readFileSync, mkdirSync, writeFileSync } from "fs"
5
+ import { join } from "path"
6
+ import { homedir } from "os"
7
+ import type { OpencodeClient } from "./client.js"
8
+
9
+ interface UserSession {
10
+ sessionId: string
11
+ title?: string
12
+ modelId?: string
13
+ providerId?: string
14
+ agentId?: string
15
+ }
16
+
17
+ const STORE_DIR = join(homedir(), ".openqq")
18
+ const STORE_FILE = join(STORE_DIR, "sessions.json")
19
+
20
+ export class SessionManager {
21
+ private sessions = new Map<string, UserSession>()
22
+ private client: OpencodeClient
23
+
24
+ constructor(client: OpencodeClient) {
25
+ this.client = client
26
+ this.loadSessions()
27
+ }
28
+
29
+ // 持久化映射:bot 重启(升级/故障)不再丢失 QQ↔会话绑定
30
+ //(2026-10-13 实测教训:重启清空内存映射 → 用户 QQ 消息落到全新会话,AI 失忆从零探索)。
31
+ private loadSessions(): void {
32
+ try {
33
+ if (!existsSync(STORE_FILE)) return
34
+ // 手工编辑或 PowerShell Out-File 常带 BOM,JSON.parse 会炸——先剥掉
35
+ const raw = readFileSync(STORE_FILE, "utf8").replace(/^\uFEFF/, "")
36
+ const parsed = JSON.parse(raw) as Record<string, UserSession>
37
+ for (const [userId, session] of Object.entries(parsed)) {
38
+ if (session?.sessionId) this.sessions.set(userId, session)
39
+ }
40
+ if (this.sessions.size > 0) {
41
+ console.log(`[sessions] 已从磁盘恢复 ${this.sessions.size} 个用户会话映射`)
42
+ }
43
+ } catch (error) {
44
+ console.error("[sessions] 会话映射加载失败(忽略,按全新处理):", error)
45
+ }
46
+ }
47
+
48
+ private saveSessions(): void {
49
+ try {
50
+ if (!existsSync(STORE_DIR)) mkdirSync(STORE_DIR, { recursive: true })
51
+ writeFileSync(STORE_FILE, JSON.stringify(Object.fromEntries(this.sessions), null, 2), "utf8")
52
+ } catch (error) {
53
+ console.error("[sessions] 会话映射持久化失败:", error)
54
+ }
55
+ }
56
+
57
+ async getOrCreate(userId: string): Promise<UserSession> {
58
+ const existing = this.sessions.get(userId)
59
+ if (existing) return existing
60
+
61
+ const result = await this.client.session.create({})
62
+ const session: UserSession = {
63
+ sessionId: result.data!.id,
64
+ title: result.data!.title,
65
+ }
66
+ this.sessions.set(userId, session)
67
+ this.saveSessions()
68
+ return session
69
+ }
70
+
71
+ async createNew(userId: string): Promise<UserSession> {
72
+ const result = await this.client.session.create({})
73
+ const session: UserSession = {
74
+ sessionId: result.data!.id,
75
+ title: result.data!.title,
76
+ }
77
+ this.sessions.set(userId, session)
78
+ this.saveSessions()
79
+ return session
80
+ }
81
+
82
+ switchSession(userId: string, sessionId: string, title?: string): void {
83
+ const prev = this.sessions.get(userId)
84
+ const changed = prev?.sessionId !== sessionId
85
+ this.sessions.set(userId, {
86
+ ...prev,
87
+ sessionId,
88
+ title,
89
+ })
90
+ this.saveSessions()
91
+ // 切到别的会话时,把本用户记住的模型/Agent 重放到目标会话
92
+ //(v2 模型是 session 级设置,不跟随 prompt)。
93
+ if (changed) {
94
+ void this.applySettings(userId)
95
+ }
96
+ }
97
+
98
+ getSession(userId: string): UserSession | undefined {
99
+ return this.sessions.get(userId)
100
+ }
101
+
102
+ // 枚举全部映射(摘要镜像订阅、会话→用户反查用)
103
+ all(): Array<{ userId: string; sessionId: string }> {
104
+ return [...this.sessions.entries()].map(([userId, s]) => ({ userId, sessionId: s.sessionId }))
105
+ }
106
+
107
+ // v2: 模型/agent 是 session 级(/prompt body 会被剥离),必须调 session 端点。
108
+ // 先服务端成功再落本地,避免 /model 显示成功但实际没生效。
109
+ async setModel(userId: string, providerId: string, modelId: string): Promise<void> {
110
+ const s = this.sessions.get(userId)
111
+ if (!s) return
112
+ await this.client.session.setModel({
113
+ path: { id: s.sessionId },
114
+ body: { model: { providerID: providerId, id: modelId } },
115
+ })
116
+ s.providerId = providerId
117
+ s.modelId = modelId
118
+ this.saveSessions()
119
+ }
120
+
121
+ async setAgent(userId: string, agentId: string): Promise<void> {
122
+ const s = this.sessions.get(userId)
123
+ if (!s) return
124
+ await this.client.session.setAgent({ path: { id: s.sessionId }, body: { agent: agentId } })
125
+ s.agentId = agentId
126
+ this.saveSessions()
127
+ }
128
+
129
+ private async applySettings(userId: string): Promise<void> {
130
+ const s = this.sessions.get(userId)
131
+ if (!s) return
132
+ try {
133
+ if (s.providerId && s.modelId) {
134
+ await this.client.session.setModel({
135
+ path: { id: s.sessionId },
136
+ body: { model: { providerID: s.providerId, id: s.modelId } },
137
+ })
138
+ }
139
+ if (s.agentId) {
140
+ await this.client.session.setAgent({ path: { id: s.sessionId }, body: { agent: s.agentId } })
141
+ }
142
+ } catch (error) {
143
+ // 切会话是主操作,设置重放失败只记日志(目标会话用其自身/默认设置)
144
+ console.error("[sessions] 重放模型/Agent 设置失败:", error)
145
+ }
146
+ }
147
+
148
+ getModel(userId: string): { providerId?: string; modelId?: string } {
149
+ const s = this.sessions.get(userId)
150
+ return { providerId: s?.providerId, modelId: s?.modelId }
151
+ }
152
+
153
+ getAgent(userId: string): string | undefined {
154
+ return this.sessions.get(userId)?.agentId
155
+ }
156
+ }
157
+
158
+ export type { UserSession }