@linjz/opencode-qqbot 0.3.5 → 0.3.7
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 +74 -39
- package/bin/openqq-setup.mjs +50 -50
- package/bin/openqq.js +47 -47
- package/dist/opencode-qqbot-plugin.js +10 -1
- package/dist/openqq-bot.js +365 -70
- package/package.json +69 -61
- package/src/_FOLDER.md +19 -19
- package/src/bridge.ts +936 -796
- package/src/commands.ts +554 -514
- package/src/config.ts +121 -121
- package/src/core/bot-launcher.ts +146 -134
- package/src/core/card-approval.ts +146 -146
- package/src/core/context-buffer.ts +78 -78
- package/src/core/delivery.ts +284 -284
- package/src/core/discovery.ts +151 -151
- package/src/core/error-rescue.ts +33 -0
- package/src/core/file-log.ts +45 -45
- package/src/core/form-bridge.ts +304 -304
- package/src/core/inflight-journal.ts +217 -151
- package/src/core/instance-lock.ts +122 -122
- package/src/core/linkwatch.ts +195 -195
- package/src/core/message-queue.ts +80 -0
- package/src/core/mirror.ts +173 -173
- package/src/core/permission.ts +301 -301
- package/src/core/reply-limiter.ts +106 -106
- package/src/core/send-media.ts +90 -90
- package/src/core/util.ts +8 -8
- package/src/index.ts +162 -162
- package/src/opencode/_FOLDER.md +11 -11
- package/src/opencode/client.ts +387 -386
- package/src/opencode/eventstream.ts +138 -138
- package/src/opencode/history.ts +143 -143
- package/src/opencode/mirror.ts +65 -65
- package/src/opencode/sessions.ts +158 -158
- package/src/plugin-entry.ts +112 -112
- package/src/qq/_FOLDER.md +13 -13
- package/src/qq/api.ts +539 -539
- package/src/qq/gateway.ts +492 -492
- package/src/qq/media.ts +219 -204
- package/src/qq/sender.ts +300 -300
- package/src/qq/types.ts +154 -152
- package/tsconfig.json +24 -24
package/src/core/form-bridge.ts
CHANGED
|
@@ -1,304 +1,304 @@
|
|
|
1
|
-
// @input: ../opencode/client (FormInfo/FormField/FormOption), ../qq/types (MessageContext)
|
|
2
|
-
// @output: renderFormPrompt, parseFormAnswer, createFormBridge, FORM_PROMPT_TTL_MS
|
|
3
|
-
// @pos: core - 表单桥接(L 项 2026-10-30):V2 Form(选择弹窗 A/B/C/D)的 QQ 同步与作答回传。
|
|
4
|
-
//
|
|
5
|
-
// 背景:昨晚"卡到今天"事故的真凶即此类弹窗(V2 Form:MCP input form/选择表单)。
|
|
6
|
-
// 2.1.3 即有完整 REST(GET /api/form 全局列表 / POST .../form/{id}/reply)+ SSE 事件
|
|
7
|
-
// (form.created/form.replied,探针实采)——纯外部 bot 可桥,无需插件无需升级。
|
|
8
|
-
// MVP 边界:单交互字段完整支持(选择/多选/布尔/自由文本);多字段表单提示回桌面。
|
|
9
|
-
import type { FormInfo, OpencodeClient } from "../opencode/client.js"
|
|
10
|
-
import type { MessageContext } from "../qq/types.js"
|
|
11
|
-
import type { InlineKeyboard, KeyboardButton } from "../qq/api.js"
|
|
12
|
-
import { redactSecrets } from "../opencode/history.js"
|
|
13
|
-
|
|
14
|
-
export const FORM_PROMPT_TTL_MS = 30 * 60 * 1000
|
|
15
|
-
const LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
16
|
-
const BUTTON_LABEL_MAX = 10
|
|
17
|
-
const BUTTONS_PER_ROW = 2
|
|
18
|
-
|
|
19
|
-
// 宽松字段视图:V2 字段类型可能扩展(external 等),运行时用宽类型读取可选属性,
|
|
20
|
-
// 未知类型走自由文本兜底而不是报错。
|
|
21
|
-
interface FieldLike {
|
|
22
|
-
key: string
|
|
23
|
-
type: string
|
|
24
|
-
title?: string
|
|
25
|
-
description?: string
|
|
26
|
-
required?: boolean
|
|
27
|
-
hidden?: boolean
|
|
28
|
-
options?: Array<{ value: string; label: string; description?: string }>
|
|
29
|
-
minimum?: number
|
|
30
|
-
maximum?: number
|
|
31
|
-
minItems?: number
|
|
32
|
-
maxItems?: number
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
// 找第一个可交互字段(MVP:单字段表单完整支持)
|
|
36
|
-
export function primaryField(form: FormInfo): FieldLike | undefined {
|
|
37
|
-
return form.fields.find((f) => !(f as FieldLike).hidden)
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/** 渲染表单为 QQ 文本(选项字母化 A/B/C/D;多选提示逗号分隔)。 */
|
|
41
|
-
export function renderFormPrompt(form: FormInfo): string {
|
|
42
|
-
const field = primaryField(form)
|
|
43
|
-
const lines = [`📝 需要你的选择:${redactSecrets(form.title)}`]
|
|
44
|
-
if (!field) {
|
|
45
|
-
lines.push("(空表单,请回桌面处理)")
|
|
46
|
-
return lines.join("\n")
|
|
47
|
-
}
|
|
48
|
-
const visible = form.fields.filter((f) => !(f as FieldLike).hidden)
|
|
49
|
-
if (visible.length > 1) {
|
|
50
|
-
lines.push("(该表单含多个输入项,请在桌面端完成)")
|
|
51
|
-
return lines.join("\n")
|
|
52
|
-
}
|
|
53
|
-
if (field.title) lines.push(redactSecrets(field.title))
|
|
54
|
-
if (field.description) lines.push(redactSecrets(field.description))
|
|
55
|
-
if ((field.type === "multiselect" || field.type === "string") && field.options?.length) {
|
|
56
|
-
field.options.slice(0, LETTERS.length).forEach((opt, i) => {
|
|
57
|
-
lines.push(`${LETTERS[i]}) ${redactSecrets(opt.label)}`)
|
|
58
|
-
})
|
|
59
|
-
lines.push(field.type === "multiselect" ? '回复字母(多选用逗号,如 "A,C")' : "回复字母/序号或选项文字")
|
|
60
|
-
} else if (field.type === "boolean") {
|
|
61
|
-
lines.push("回复 是 / 否")
|
|
62
|
-
} else {
|
|
63
|
-
lines.push("请直接回复内容")
|
|
64
|
-
}
|
|
65
|
-
lines.push("(30 分钟未答自动取消)")
|
|
66
|
-
return lines.join("\n")
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
function tokenToOption(token: string, field: FieldLike): string | undefined {
|
|
70
|
-
const t = token.trim()
|
|
71
|
-
if (!t) return undefined
|
|
72
|
-
const opts = field.options ?? []
|
|
73
|
-
// 字母 A/B/C...
|
|
74
|
-
const letterIdx = LETTERS.indexOf(t.toUpperCase())
|
|
75
|
-
if (letterIdx >= 0 && letterIdx < opts.length) return opts[letterIdx].value
|
|
76
|
-
// 1-based 序号
|
|
77
|
-
const num = Number(t)
|
|
78
|
-
if (Number.isInteger(num) && num >= 1 && num <= opts.length) return opts[num - 1].value
|
|
79
|
-
// 精确匹配 value 或 label
|
|
80
|
-
const hit = opts.find((o) => o.value === t || o.label === t)
|
|
81
|
-
return hit?.value
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
/** 解析用户回复为 Form.Answer;无法解析返回 null(调用方发提示)。 */
|
|
85
|
-
export function parseFormAnswer(form: FormInfo, text: string): Record<string, unknown> | null {
|
|
86
|
-
const field = primaryField(form)
|
|
87
|
-
if (!field) return null
|
|
88
|
-
const t = text.trim()
|
|
89
|
-
if (!t) return null
|
|
90
|
-
|
|
91
|
-
if (field.type === "boolean") {
|
|
92
|
-
if (/^(是|yes|y|true|1|对)$/i.test(t)) return { [field.key]: true }
|
|
93
|
-
if (/^(否|no|n|false|0|不对)$/i.test(t)) return { [field.key]: false }
|
|
94
|
-
return null
|
|
95
|
-
}
|
|
96
|
-
if (field.type === "number" || field.type === "integer") {
|
|
97
|
-
const n = Number(t)
|
|
98
|
-
if (!Number.isFinite(n)) return null
|
|
99
|
-
if (field.type === "integer" && !Number.isInteger(n)) return null
|
|
100
|
-
if (typeof field.minimum === "number" && n < field.minimum) return null
|
|
101
|
-
if (typeof field.maximum === "number" && n > field.maximum) return null
|
|
102
|
-
return { [field.key]: field.type === "integer" ? Math.floor(n) : n }
|
|
103
|
-
}
|
|
104
|
-
if (field.type === "multiselect") {
|
|
105
|
-
const tokens = t.split(/[,,、\s]+/).filter(Boolean)
|
|
106
|
-
if (tokens.length === 0) return null
|
|
107
|
-
const values: string[] = []
|
|
108
|
-
for (const token of tokens) {
|
|
109
|
-
const v = tokenToOption(token, field)
|
|
110
|
-
if (v === undefined) return null
|
|
111
|
-
if (!values.includes(v)) values.push(v)
|
|
112
|
-
}
|
|
113
|
-
if (typeof field.minItems === "number" && values.length < field.minItems) return null
|
|
114
|
-
if (typeof field.maxItems === "number" && values.length > field.maxItems) return null
|
|
115
|
-
return { [field.key]: values }
|
|
116
|
-
}
|
|
117
|
-
if (field.type === "string" && field.options?.length) {
|
|
118
|
-
const v = tokenToOption(t, field)
|
|
119
|
-
return v === undefined ? null : { [field.key]: v }
|
|
120
|
-
}
|
|
121
|
-
// string 无选项 / 未知类型 = 自由文本兜底
|
|
122
|
-
return { [field.key]: t }
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
export interface PendingForm {
|
|
126
|
-
form: FormInfo
|
|
127
|
-
ctx: MessageContext
|
|
128
|
-
timer: ReturnType<typeof setTimeout> | null
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
// ── 表单按钮(2026-10-30 弹窗验证前置:点选式作答)──
|
|
132
|
-
|
|
133
|
-
/** button_data:t 判别 + formID + 字段 key + 选项 value(明文 JSON,与审批同款 P0 格式) */
|
|
134
|
-
export interface FormButtonData {
|
|
135
|
-
t: "form"
|
|
136
|
-
f: string
|
|
137
|
-
k: string
|
|
138
|
-
v: string
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
export function encodeFormButton(data: FormButtonData): string {
|
|
142
|
-
return JSON.stringify(data)
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
export function decodeFormButton(raw: string | undefined): FormButtonData | undefined {
|
|
146
|
-
if (!raw) return undefined
|
|
147
|
-
try {
|
|
148
|
-
const parsed = JSON.parse(raw) as Partial<FormButtonData>
|
|
149
|
-
if (parsed && typeof parsed === "object" && parsed.t === "form" && typeof parsed.f === "string" && typeof parsed.k === "string" && typeof parsed.v === "string") {
|
|
150
|
-
return parsed as FormButtonData
|
|
151
|
-
}
|
|
152
|
-
} catch {
|
|
153
|
-
// fall through
|
|
154
|
-
}
|
|
155
|
-
return undefined
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
function clipButtonLabel(text: string): string {
|
|
159
|
-
const s = text.trim()
|
|
160
|
-
return s.length > BUTTON_LABEL_MAX ? s.slice(0, BUTTON_LABEL_MAX - 1) + "…" : s
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
/**
|
|
164
|
-
* 构建表单选项键盘:单可见字段 + 有 options 时可用(string=单选直点直交;
|
|
165
|
-
* multiselect=点一个先交单值数组,多值仍走文字)。多字段/无选项 → null(文字作答)。
|
|
166
|
-
*/
|
|
167
|
-
export function buildFormKeyboard(form: FormInfo, ownerOpenid: string): InlineKeyboard | null {
|
|
168
|
-
const visible = form.fields.filter((f) => !(f as FieldLike).hidden)
|
|
169
|
-
if (visible.length !== 1) return null
|
|
170
|
-
const field = visible[0] as FieldLike
|
|
171
|
-
const opts = field.options
|
|
172
|
-
if (!opts?.length) return null
|
|
173
|
-
if (field.type !== "string" && field.type !== "multiselect") return null
|
|
174
|
-
const buttons: KeyboardButton[] = opts.slice(0, 20).map((opt) => ({
|
|
175
|
-
id: `form-${form.id}-${opt.value}`.slice(0, 64),
|
|
176
|
-
// visited_label:点击后原生回显(按钮变已访问态、其余置灰),不再发明文确认消息
|
|
177
|
-
render_data: { label: clipButtonLabel(opt.label), visited_label: clipButtonLabel(`✓ ${opt.label}`), style: 1 },
|
|
178
|
-
action: {
|
|
179
|
-
type: 1,
|
|
180
|
-
permission: { type: 2, specify_user_ids: [ownerOpenid] },
|
|
181
|
-
data: encodeFormButton({ t: "form", f: form.id, k: field.key, v: opt.value }),
|
|
182
|
-
},
|
|
183
|
-
}))
|
|
184
|
-
const rows: Array<{ buttons: KeyboardButton[] }> = []
|
|
185
|
-
for (let i = 0; i < buttons.length; i += BUTTONS_PER_ROW) {
|
|
186
|
-
rows.push({ buttons: buttons.slice(i, i + BUTTONS_PER_ROW) })
|
|
187
|
-
}
|
|
188
|
-
return { content: { rows } }
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
export interface FormBridgeDeps {
|
|
192
|
-
client: OpencodeClient
|
|
193
|
-
sendReply: (ctx: MessageContext, text: string) => Promise<void>
|
|
194
|
-
safeDeliver: (ctx: MessageContext, text: string) => Promise<void>
|
|
195
|
-
/** 按钮卡片发送(有键盘时优先;返回 false 自动降级文字) */
|
|
196
|
-
sendFormCard?: (ctx: MessageContext, form: FormInfo, keyboard: InlineKeyboard) => Promise<boolean>
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
export interface FormBridge {
|
|
200
|
-
pushForm: (userId: string, ctx: MessageContext, form: FormInfo) => void
|
|
201
|
-
tryResolveText: (userId: string, text: string) => boolean
|
|
202
|
-
/** 按钮互动回调:匹配挂起表单则提交并返回 true;非本域返回 false */
|
|
203
|
-
handleButton: (event: { user_openid?: string; group_member_openid?: string; data?: { resolved?: { button_data?: string } } }) => boolean
|
|
204
|
-
hasPending: (userId: string) => boolean
|
|
205
|
-
getPending: (userId: string) => PendingForm | undefined
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
export function createFormBridge(deps: FormBridgeDeps): FormBridge {
|
|
209
|
-
const pending = new Map<string, PendingForm>()
|
|
210
|
-
|
|
211
|
-
function clear(userId: string): PendingForm | undefined {
|
|
212
|
-
const entry = pending.get(userId)
|
|
213
|
-
if (!entry) return undefined
|
|
214
|
-
if (entry.timer) clearTimeout(entry.timer)
|
|
215
|
-
pending.delete(userId)
|
|
216
|
-
return entry
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
function submit(userId: string, form: FormInfo, ctx: MessageContext, answer: Record<string, unknown>, display: string, silent = false): void {
|
|
220
|
-
clear(userId)
|
|
221
|
-
void (async () => {
|
|
222
|
-
try {
|
|
223
|
-
await deps.client.form.reply({ path: { sessionID: form.sessionID, formID: form.id }, body: { answer } })
|
|
224
|
-
// 按钮路径静默(visited_label 原生回显已表达结果);文字路径保留明文回执
|
|
225
|
-
if (!silent) {
|
|
226
|
-
void deps.safeDeliver(ctx, `✅ 已提交选择:${display}`).catch(() => {})
|
|
227
|
-
}
|
|
228
|
-
console.log(`[form-bridge] 表单已作答 user=${userId.slice(0, 8)}… form=${form.id} answer=${display}`)
|
|
229
|
-
} catch (error) {
|
|
230
|
-
const msg = error instanceof Error ? error.message : String(error)
|
|
231
|
-
if (msg.includes("AlreadySettled") || msg.includes("already")) {
|
|
232
|
-
void deps.safeDeliver(ctx, "该选择已在桌面端处理过,任务应已继续").catch(() => {})
|
|
233
|
-
} else {
|
|
234
|
-
void deps.safeDeliver(ctx, `⚠️ 提交失败:${msg.slice(0, 120)}`).catch(() => {})
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
})()
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
function pushForm(userId: string, ctx: MessageContext, form: FormInfo): void {
|
|
241
|
-
// 去重:同表单已在挂起中
|
|
242
|
-
if (pending.get(userId)?.form.id === form.id) return
|
|
243
|
-
// 单一交互槽:新表单取代旧槽(提示旧表单失效)
|
|
244
|
-
const prev = clear(userId)
|
|
245
|
-
if (prev) {
|
|
246
|
-
void deps.safeDeliver(ctx, "⚠️ 有新的选择请求,上一个表单已取消在 QQ 的作答(仍可回桌面处理)").catch(() => {})
|
|
247
|
-
}
|
|
248
|
-
const entry: PendingForm = { form, ctx, timer: null }
|
|
249
|
-
entry.timer = setTimeout(() => {
|
|
250
|
-
if (pending.get(userId)?.form.id !== form.id) return
|
|
251
|
-
clear(userId)
|
|
252
|
-
void deps.safeDeliver(ctx, "⏰ 选择请求超时(30 分钟未作答),任务可能已被取消;可回桌面重试").catch(() => {})
|
|
253
|
-
}, FORM_PROMPT_TTL_MS)
|
|
254
|
-
pending.set(userId, entry)
|
|
255
|
-
console.log(`[form-bridge] 表单已推送 user=${userId.slice(0, 8)}… form=${form.id} title=${form.title.slice(0, 40)}`)
|
|
256
|
-
void (async () => {
|
|
257
|
-
const keyboard = buildFormKeyboard(form, ctx.userId)
|
|
258
|
-
if (keyboard && deps.sendFormCard) {
|
|
259
|
-
const sent = await deps.sendFormCard(ctx, form, keyboard).catch(() => false)
|
|
260
|
-
if (sent) return
|
|
261
|
-
}
|
|
262
|
-
await deps.sendReply(ctx, renderFormPrompt(form)).catch((error) => {
|
|
263
|
-
console.error("[form-bridge] 表单推送失败:", error instanceof Error ? error.message : error)
|
|
264
|
-
})
|
|
265
|
-
})()
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
/** 有挂起表单则消费本条文本(解析成功→提交;失败→提示),返回 true;无挂起返回 false。 */
|
|
269
|
-
function tryResolveText(userId: string, text: string): boolean {
|
|
270
|
-
const entry = pending.get(userId)
|
|
271
|
-
if (!entry) return false
|
|
272
|
-
const answer = parseFormAnswer(entry.form, text)
|
|
273
|
-
if (!answer) {
|
|
274
|
-
const field = primaryField(entry.form)
|
|
275
|
-
const hint =
|
|
276
|
-
field?.type === "multiselect"
|
|
277
|
-
? '没看懂,请按选项字母回复(多选用逗号,如 "A,C")'
|
|
278
|
-
: field?.type === "boolean"
|
|
279
|
-
? "请回复 是 或 否"
|
|
280
|
-
: "没看懂,请按提示回复"
|
|
281
|
-
void deps.sendReply(entry.ctx, hint).catch(() => {})
|
|
282
|
-
return true
|
|
283
|
-
}
|
|
284
|
-
submit(userId, entry.form, entry.ctx, answer, text.trim())
|
|
285
|
-
return true
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
function handleButton(event: { user_openid?: string; group_member_openid?: string; data?: { resolved?: { button_data?: string } } }): boolean {
|
|
289
|
-
const userId = event.user_openid ?? event.group_member_openid
|
|
290
|
-
if (!userId) return false
|
|
291
|
-
const button = decodeFormButton(event.data?.resolved?.button_data)
|
|
292
|
-
if (!button) return false
|
|
293
|
-
const entry = pending.get(userId)
|
|
294
|
-
if (!entry || entry.form.id !== button.f) {
|
|
295
|
-
console.log(`[form-bridge] 拒识过期表单按钮 user=${userId.slice(0, 8)}… form=${button.f}`)
|
|
296
|
-
return true // 已消费(拒识),不再下放
|
|
297
|
-
}
|
|
298
|
-
const answer: Record<string, unknown> = { [button.k]: button.v }
|
|
299
|
-
submit(userId, entry.form, entry.ctx, answer, button.v, true) // 按钮路径静默(visited_label 原生回显)
|
|
300
|
-
return true
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
return { pushForm, tryResolveText, handleButton, hasPending: (u) => pending.has(u), getPending: (u) => pending.get(u) }
|
|
304
|
-
}
|
|
1
|
+
// @input: ../opencode/client (FormInfo/FormField/FormOption), ../qq/types (MessageContext)
|
|
2
|
+
// @output: renderFormPrompt, parseFormAnswer, createFormBridge, FORM_PROMPT_TTL_MS
|
|
3
|
+
// @pos: core - 表单桥接(L 项 2026-10-30):V2 Form(选择弹窗 A/B/C/D)的 QQ 同步与作答回传。
|
|
4
|
+
//
|
|
5
|
+
// 背景:昨晚"卡到今天"事故的真凶即此类弹窗(V2 Form:MCP input form/选择表单)。
|
|
6
|
+
// 2.1.3 即有完整 REST(GET /api/form 全局列表 / POST .../form/{id}/reply)+ SSE 事件
|
|
7
|
+
// (form.created/form.replied,探针实采)——纯外部 bot 可桥,无需插件无需升级。
|
|
8
|
+
// MVP 边界:单交互字段完整支持(选择/多选/布尔/自由文本);多字段表单提示回桌面。
|
|
9
|
+
import type { FormInfo, OpencodeClient } from "../opencode/client.js"
|
|
10
|
+
import type { MessageContext } from "../qq/types.js"
|
|
11
|
+
import type { InlineKeyboard, KeyboardButton } from "../qq/api.js"
|
|
12
|
+
import { redactSecrets } from "../opencode/history.js"
|
|
13
|
+
|
|
14
|
+
export const FORM_PROMPT_TTL_MS = 30 * 60 * 1000
|
|
15
|
+
const LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
16
|
+
const BUTTON_LABEL_MAX = 10
|
|
17
|
+
const BUTTONS_PER_ROW = 2
|
|
18
|
+
|
|
19
|
+
// 宽松字段视图:V2 字段类型可能扩展(external 等),运行时用宽类型读取可选属性,
|
|
20
|
+
// 未知类型走自由文本兜底而不是报错。
|
|
21
|
+
interface FieldLike {
|
|
22
|
+
key: string
|
|
23
|
+
type: string
|
|
24
|
+
title?: string
|
|
25
|
+
description?: string
|
|
26
|
+
required?: boolean
|
|
27
|
+
hidden?: boolean
|
|
28
|
+
options?: Array<{ value: string; label: string; description?: string }>
|
|
29
|
+
minimum?: number
|
|
30
|
+
maximum?: number
|
|
31
|
+
minItems?: number
|
|
32
|
+
maxItems?: number
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// 找第一个可交互字段(MVP:单字段表单完整支持)
|
|
36
|
+
export function primaryField(form: FormInfo): FieldLike | undefined {
|
|
37
|
+
return form.fields.find((f) => !(f as FieldLike).hidden)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 渲染表单为 QQ 文本(选项字母化 A/B/C/D;多选提示逗号分隔)。 */
|
|
41
|
+
export function renderFormPrompt(form: FormInfo): string {
|
|
42
|
+
const field = primaryField(form)
|
|
43
|
+
const lines = [`📝 需要你的选择:${redactSecrets(form.title)}`]
|
|
44
|
+
if (!field) {
|
|
45
|
+
lines.push("(空表单,请回桌面处理)")
|
|
46
|
+
return lines.join("\n")
|
|
47
|
+
}
|
|
48
|
+
const visible = form.fields.filter((f) => !(f as FieldLike).hidden)
|
|
49
|
+
if (visible.length > 1) {
|
|
50
|
+
lines.push("(该表单含多个输入项,请在桌面端完成)")
|
|
51
|
+
return lines.join("\n")
|
|
52
|
+
}
|
|
53
|
+
if (field.title) lines.push(redactSecrets(field.title))
|
|
54
|
+
if (field.description) lines.push(redactSecrets(field.description))
|
|
55
|
+
if ((field.type === "multiselect" || field.type === "string") && field.options?.length) {
|
|
56
|
+
field.options.slice(0, LETTERS.length).forEach((opt, i) => {
|
|
57
|
+
lines.push(`${LETTERS[i]}) ${redactSecrets(opt.label)}`)
|
|
58
|
+
})
|
|
59
|
+
lines.push(field.type === "multiselect" ? '回复字母(多选用逗号,如 "A,C")' : "回复字母/序号或选项文字")
|
|
60
|
+
} else if (field.type === "boolean") {
|
|
61
|
+
lines.push("回复 是 / 否")
|
|
62
|
+
} else {
|
|
63
|
+
lines.push("请直接回复内容")
|
|
64
|
+
}
|
|
65
|
+
lines.push("(30 分钟未答自动取消)")
|
|
66
|
+
return lines.join("\n")
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function tokenToOption(token: string, field: FieldLike): string | undefined {
|
|
70
|
+
const t = token.trim()
|
|
71
|
+
if (!t) return undefined
|
|
72
|
+
const opts = field.options ?? []
|
|
73
|
+
// 字母 A/B/C...
|
|
74
|
+
const letterIdx = LETTERS.indexOf(t.toUpperCase())
|
|
75
|
+
if (letterIdx >= 0 && letterIdx < opts.length) return opts[letterIdx].value
|
|
76
|
+
// 1-based 序号
|
|
77
|
+
const num = Number(t)
|
|
78
|
+
if (Number.isInteger(num) && num >= 1 && num <= opts.length) return opts[num - 1].value
|
|
79
|
+
// 精确匹配 value 或 label
|
|
80
|
+
const hit = opts.find((o) => o.value === t || o.label === t)
|
|
81
|
+
return hit?.value
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** 解析用户回复为 Form.Answer;无法解析返回 null(调用方发提示)。 */
|
|
85
|
+
export function parseFormAnswer(form: FormInfo, text: string): Record<string, unknown> | null {
|
|
86
|
+
const field = primaryField(form)
|
|
87
|
+
if (!field) return null
|
|
88
|
+
const t = text.trim()
|
|
89
|
+
if (!t) return null
|
|
90
|
+
|
|
91
|
+
if (field.type === "boolean") {
|
|
92
|
+
if (/^(是|yes|y|true|1|对)$/i.test(t)) return { [field.key]: true }
|
|
93
|
+
if (/^(否|no|n|false|0|不对)$/i.test(t)) return { [field.key]: false }
|
|
94
|
+
return null
|
|
95
|
+
}
|
|
96
|
+
if (field.type === "number" || field.type === "integer") {
|
|
97
|
+
const n = Number(t)
|
|
98
|
+
if (!Number.isFinite(n)) return null
|
|
99
|
+
if (field.type === "integer" && !Number.isInteger(n)) return null
|
|
100
|
+
if (typeof field.minimum === "number" && n < field.minimum) return null
|
|
101
|
+
if (typeof field.maximum === "number" && n > field.maximum) return null
|
|
102
|
+
return { [field.key]: field.type === "integer" ? Math.floor(n) : n }
|
|
103
|
+
}
|
|
104
|
+
if (field.type === "multiselect") {
|
|
105
|
+
const tokens = t.split(/[,,、\s]+/).filter(Boolean)
|
|
106
|
+
if (tokens.length === 0) return null
|
|
107
|
+
const values: string[] = []
|
|
108
|
+
for (const token of tokens) {
|
|
109
|
+
const v = tokenToOption(token, field)
|
|
110
|
+
if (v === undefined) return null
|
|
111
|
+
if (!values.includes(v)) values.push(v)
|
|
112
|
+
}
|
|
113
|
+
if (typeof field.minItems === "number" && values.length < field.minItems) return null
|
|
114
|
+
if (typeof field.maxItems === "number" && values.length > field.maxItems) return null
|
|
115
|
+
return { [field.key]: values }
|
|
116
|
+
}
|
|
117
|
+
if (field.type === "string" && field.options?.length) {
|
|
118
|
+
const v = tokenToOption(t, field)
|
|
119
|
+
return v === undefined ? null : { [field.key]: v }
|
|
120
|
+
}
|
|
121
|
+
// string 无选项 / 未知类型 = 自由文本兜底
|
|
122
|
+
return { [field.key]: t }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export interface PendingForm {
|
|
126
|
+
form: FormInfo
|
|
127
|
+
ctx: MessageContext
|
|
128
|
+
timer: ReturnType<typeof setTimeout> | null
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// ── 表单按钮(2026-10-30 弹窗验证前置:点选式作答)──
|
|
132
|
+
|
|
133
|
+
/** button_data:t 判别 + formID + 字段 key + 选项 value(明文 JSON,与审批同款 P0 格式) */
|
|
134
|
+
export interface FormButtonData {
|
|
135
|
+
t: "form"
|
|
136
|
+
f: string
|
|
137
|
+
k: string
|
|
138
|
+
v: string
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function encodeFormButton(data: FormButtonData): string {
|
|
142
|
+
return JSON.stringify(data)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function decodeFormButton(raw: string | undefined): FormButtonData | undefined {
|
|
146
|
+
if (!raw) return undefined
|
|
147
|
+
try {
|
|
148
|
+
const parsed = JSON.parse(raw) as Partial<FormButtonData>
|
|
149
|
+
if (parsed && typeof parsed === "object" && parsed.t === "form" && typeof parsed.f === "string" && typeof parsed.k === "string" && typeof parsed.v === "string") {
|
|
150
|
+
return parsed as FormButtonData
|
|
151
|
+
}
|
|
152
|
+
} catch {
|
|
153
|
+
// fall through
|
|
154
|
+
}
|
|
155
|
+
return undefined
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function clipButtonLabel(text: string): string {
|
|
159
|
+
const s = text.trim()
|
|
160
|
+
return s.length > BUTTON_LABEL_MAX ? s.slice(0, BUTTON_LABEL_MAX - 1) + "…" : s
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* 构建表单选项键盘:单可见字段 + 有 options 时可用(string=单选直点直交;
|
|
165
|
+
* multiselect=点一个先交单值数组,多值仍走文字)。多字段/无选项 → null(文字作答)。
|
|
166
|
+
*/
|
|
167
|
+
export function buildFormKeyboard(form: FormInfo, ownerOpenid: string): InlineKeyboard | null {
|
|
168
|
+
const visible = form.fields.filter((f) => !(f as FieldLike).hidden)
|
|
169
|
+
if (visible.length !== 1) return null
|
|
170
|
+
const field = visible[0] as FieldLike
|
|
171
|
+
const opts = field.options
|
|
172
|
+
if (!opts?.length) return null
|
|
173
|
+
if (field.type !== "string" && field.type !== "multiselect") return null
|
|
174
|
+
const buttons: KeyboardButton[] = opts.slice(0, 20).map((opt) => ({
|
|
175
|
+
id: `form-${form.id}-${opt.value}`.slice(0, 64),
|
|
176
|
+
// visited_label:点击后原生回显(按钮变已访问态、其余置灰),不再发明文确认消息
|
|
177
|
+
render_data: { label: clipButtonLabel(opt.label), visited_label: clipButtonLabel(`✓ ${opt.label}`), style: 1 },
|
|
178
|
+
action: {
|
|
179
|
+
type: 1,
|
|
180
|
+
permission: { type: 2, specify_user_ids: [ownerOpenid] },
|
|
181
|
+
data: encodeFormButton({ t: "form", f: form.id, k: field.key, v: opt.value }),
|
|
182
|
+
},
|
|
183
|
+
}))
|
|
184
|
+
const rows: Array<{ buttons: KeyboardButton[] }> = []
|
|
185
|
+
for (let i = 0; i < buttons.length; i += BUTTONS_PER_ROW) {
|
|
186
|
+
rows.push({ buttons: buttons.slice(i, i + BUTTONS_PER_ROW) })
|
|
187
|
+
}
|
|
188
|
+
return { content: { rows } }
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export interface FormBridgeDeps {
|
|
192
|
+
client: OpencodeClient
|
|
193
|
+
sendReply: (ctx: MessageContext, text: string) => Promise<void>
|
|
194
|
+
safeDeliver: (ctx: MessageContext, text: string) => Promise<void>
|
|
195
|
+
/** 按钮卡片发送(有键盘时优先;返回 false 自动降级文字) */
|
|
196
|
+
sendFormCard?: (ctx: MessageContext, form: FormInfo, keyboard: InlineKeyboard) => Promise<boolean>
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export interface FormBridge {
|
|
200
|
+
pushForm: (userId: string, ctx: MessageContext, form: FormInfo) => void
|
|
201
|
+
tryResolveText: (userId: string, text: string) => boolean
|
|
202
|
+
/** 按钮互动回调:匹配挂起表单则提交并返回 true;非本域返回 false */
|
|
203
|
+
handleButton: (event: { user_openid?: string; group_member_openid?: string; data?: { resolved?: { button_data?: string } } }) => boolean
|
|
204
|
+
hasPending: (userId: string) => boolean
|
|
205
|
+
getPending: (userId: string) => PendingForm | undefined
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export function createFormBridge(deps: FormBridgeDeps): FormBridge {
|
|
209
|
+
const pending = new Map<string, PendingForm>()
|
|
210
|
+
|
|
211
|
+
function clear(userId: string): PendingForm | undefined {
|
|
212
|
+
const entry = pending.get(userId)
|
|
213
|
+
if (!entry) return undefined
|
|
214
|
+
if (entry.timer) clearTimeout(entry.timer)
|
|
215
|
+
pending.delete(userId)
|
|
216
|
+
return entry
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function submit(userId: string, form: FormInfo, ctx: MessageContext, answer: Record<string, unknown>, display: string, silent = false): void {
|
|
220
|
+
clear(userId)
|
|
221
|
+
void (async () => {
|
|
222
|
+
try {
|
|
223
|
+
await deps.client.form.reply({ path: { sessionID: form.sessionID, formID: form.id }, body: { answer } })
|
|
224
|
+
// 按钮路径静默(visited_label 原生回显已表达结果);文字路径保留明文回执
|
|
225
|
+
if (!silent) {
|
|
226
|
+
void deps.safeDeliver(ctx, `✅ 已提交选择:${display}`).catch(() => {})
|
|
227
|
+
}
|
|
228
|
+
console.log(`[form-bridge] 表单已作答 user=${userId.slice(0, 8)}… form=${form.id} answer=${display}`)
|
|
229
|
+
} catch (error) {
|
|
230
|
+
const msg = error instanceof Error ? error.message : String(error)
|
|
231
|
+
if (msg.includes("AlreadySettled") || msg.includes("already")) {
|
|
232
|
+
void deps.safeDeliver(ctx, "该选择已在桌面端处理过,任务应已继续").catch(() => {})
|
|
233
|
+
} else {
|
|
234
|
+
void deps.safeDeliver(ctx, `⚠️ 提交失败:${msg.length > 120 ? `${msg.slice(0, 120)}…` : msg}`).catch(() => {})
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
})()
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function pushForm(userId: string, ctx: MessageContext, form: FormInfo): void {
|
|
241
|
+
// 去重:同表单已在挂起中
|
|
242
|
+
if (pending.get(userId)?.form.id === form.id) return
|
|
243
|
+
// 单一交互槽:新表单取代旧槽(提示旧表单失效)
|
|
244
|
+
const prev = clear(userId)
|
|
245
|
+
if (prev) {
|
|
246
|
+
void deps.safeDeliver(ctx, "⚠️ 有新的选择请求,上一个表单已取消在 QQ 的作答(仍可回桌面处理)").catch(() => {})
|
|
247
|
+
}
|
|
248
|
+
const entry: PendingForm = { form, ctx, timer: null }
|
|
249
|
+
entry.timer = setTimeout(() => {
|
|
250
|
+
if (pending.get(userId)?.form.id !== form.id) return
|
|
251
|
+
clear(userId)
|
|
252
|
+
void deps.safeDeliver(ctx, "⏰ 选择请求超时(30 分钟未作答),任务可能已被取消;可回桌面重试").catch(() => {})
|
|
253
|
+
}, FORM_PROMPT_TTL_MS)
|
|
254
|
+
pending.set(userId, entry)
|
|
255
|
+
console.log(`[form-bridge] 表单已推送 user=${userId.slice(0, 8)}… form=${form.id} title=${form.title.slice(0, 40)}`)
|
|
256
|
+
void (async () => {
|
|
257
|
+
const keyboard = buildFormKeyboard(form, ctx.userId)
|
|
258
|
+
if (keyboard && deps.sendFormCard) {
|
|
259
|
+
const sent = await deps.sendFormCard(ctx, form, keyboard).catch(() => false)
|
|
260
|
+
if (sent) return
|
|
261
|
+
}
|
|
262
|
+
await deps.sendReply(ctx, renderFormPrompt(form)).catch((error) => {
|
|
263
|
+
console.error("[form-bridge] 表单推送失败:", error instanceof Error ? error.message : error)
|
|
264
|
+
})
|
|
265
|
+
})()
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** 有挂起表单则消费本条文本(解析成功→提交;失败→提示),返回 true;无挂起返回 false。 */
|
|
269
|
+
function tryResolveText(userId: string, text: string): boolean {
|
|
270
|
+
const entry = pending.get(userId)
|
|
271
|
+
if (!entry) return false
|
|
272
|
+
const answer = parseFormAnswer(entry.form, text)
|
|
273
|
+
if (!answer) {
|
|
274
|
+
const field = primaryField(entry.form)
|
|
275
|
+
const hint =
|
|
276
|
+
field?.type === "multiselect"
|
|
277
|
+
? '没看懂,请按选项字母回复(多选用逗号,如 "A,C")'
|
|
278
|
+
: field?.type === "boolean"
|
|
279
|
+
? "请回复 是 或 否"
|
|
280
|
+
: "没看懂,请按提示回复"
|
|
281
|
+
void deps.sendReply(entry.ctx, hint).catch(() => {})
|
|
282
|
+
return true
|
|
283
|
+
}
|
|
284
|
+
submit(userId, entry.form, entry.ctx, answer, text.trim())
|
|
285
|
+
return true
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function handleButton(event: { user_openid?: string; group_member_openid?: string; data?: { resolved?: { button_data?: string } } }): boolean {
|
|
289
|
+
const userId = event.user_openid ?? event.group_member_openid
|
|
290
|
+
if (!userId) return false
|
|
291
|
+
const button = decodeFormButton(event.data?.resolved?.button_data)
|
|
292
|
+
if (!button) return false
|
|
293
|
+
const entry = pending.get(userId)
|
|
294
|
+
if (!entry || entry.form.id !== button.f) {
|
|
295
|
+
console.log(`[form-bridge] 拒识过期表单按钮 user=${userId.slice(0, 8)}… form=${button.f}`)
|
|
296
|
+
return true // 已消费(拒识),不再下放
|
|
297
|
+
}
|
|
298
|
+
const answer: Record<string, unknown> = { [button.k]: button.v }
|
|
299
|
+
submit(userId, entry.form, entry.ctx, answer, button.v, true) // 按钮路径静默(visited_label 原生回显)
|
|
300
|
+
return true
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
return { pushForm, tryResolveText, handleButton, hasPending: (u) => pending.has(u), getPending: (u) => pending.get(u) }
|
|
304
|
+
}
|