dsh-im-lark 0.1.6 → 0.1.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.en.md CHANGED
@@ -22,12 +22,12 @@ The two modes are mutually exclusive: the core is used only when "Use my super a
22
22
  - **Quoted replies**: answers quote the message that triggered them, in DMs and groups alike
23
23
  - **Processing feedback**: an incoming message gets a `Get` reaction first; `DONE` is added to the original message only after the answer is actually delivered, and the two stay side by side. Being queued is not completion (the core queues the message and runs the task asynchronously). In core mode the plugin follows the core's `completes` markers (stall notices, dispatch receipts and transfer confirmations never carry them; cancelled, failed, approval-rejected or token-limit-truncated rounds do not carry them either, because they have no normal answer; older cores do not send them at all). Standalone mode aligns reactions per turn, and reminder answers are marked at settlement time (when only some questions are answered the reminder is still waiting, so no `DONE`). On failure only `Get` remains — never a false "done". Each message is marked once. Feishu has no official "typing" API
24
24
  - **Card updates**: streaming answers update the same card in place; after platform limits (14 days, 5 QPS per card) a new card is sent
25
- - **Interactive cards**: in core mode, **single-question** single- and multi-select questions are answered in Feishu and the result is returned to the core; in standalone mode single questions are also sent as cards (single and multi select are both checkboxes, distinguished by copy, and must be submitted), everything else stays a text reminder. Multi-question and approval prompts are notice-only and must be answered in the Web UI (the core requires all questions in one submission, which card callbacks cannot do per question); both support an "other" input
25
+ - **Interactive cards**: in core mode, single- and multi-select questions are answered in Feishu and the result is returned to the core. **Several questions at once still use one card**: every question lives in the same form and one submit button answers them all (the core requires all answers in one submission); controls are namespaced by question index, questions without options take free text through an input, and a missing answer or a multi-ticked single-select points at the offending question and redraws the card. Standalone mode sends single questions as cards too. **Approvals** are never answered in IM — the card points at the Web UI; when questions exceed the card component or size limit the bridge sends a plain-text card with the questions, options and reply format, so the user can just reply in words. Both modes support an "other" input
26
26
  - **Groups**: only messages that @mention the bot are handled (only the @-scoped group permissions are requested); the whole group is never read
27
27
  - **Task reminders**: in standalone mode, a long turn (30 minutes by default) sends a reminder with elapsed time and conclusion when it ends; a failed or externally aborted turn is reported immediately with the original error. A stop pressed by the owner is not a failure
28
28
  - **Panel**: create an app with one scan on the Web plugin page, or enter App ID / App Secret manually; see connection state, toggle send/receive and core mode, change message behaviour; in standalone mode, adjust in-turn steering, session workspace, question/approval reminders and long-task reminders
29
29
 
30
- > Question cards (checkboxes + submit + "other" input) have been verified in a real Feishu tenant in both standalone and core mode: single and multi select are distinguished by card copy, and a submission returns the checked options plus the "other" input. Rejected answers give visible feedback in both modes: a card that can still be answered is **re-rendered whole** with the reason (Feishu form submissions are one-shot; a text-only hint would leave the card unclickable) so you can re-select and submit; a card that can no longer be answered becomes invalid and loses its checkboxes. `Get` / `DONE` reactions and card layout vary slightly with tenant settings; what you see is what the platform does.
30
+ > Question cards have been verified in a real Feishu tenant in both standalone and core mode, in **both shapes — one question and several questions inside one form**: single and multi select are distinguished by card copy, several questions are laid out as ①②③ with bold headings, and a submission returns the checked options plus the "other" input per question. Rejected answers give visible feedback in both modes: a card that can still be answered is **re-rendered whole** with the reason (Feishu form submissions are one-shot; a text-only hint would leave the card unclickable), previously checked and typed content is restored, and you can adjust and submit again; a card that can no longer be answered becomes invalid and loses its checkboxes. `Get` / `DONE` reactions and card layout vary slightly with tenant settings; what you see is what the platform does.
31
31
 
32
32
  ## Install
33
33
 
@@ -132,7 +132,7 @@ The recipient is always the "owner": in standalone mode the first person who DMs
132
132
  - Standalone: while a question or tool approval is waiting for the owner, the plugin sends a Feishu reminder (delay configurable): single questions with options are answered by tapping the card; multi-question, approval and free-form input still use text (reply with a number or the option text). Long-task completion reminders remain the core's job.
133
133
  - Standalone: received files only get a notice; their contents are not fed into the session. Images are attached as input.
134
134
  - In core mode `DONE` first translates the inbound `messageId` from the core into a platform message id; that table keeps only the latest 500 entries (bounded to avoid unbounded memory): after a plugin restart, or when a message is reported complete more than 500 inbound messages later, the id cannot be resolved and no `DONE` is added — this only affects the completion reaction, never answer delivery.
135
- - IM cards only carry single-question, option-based interactions; multi-question, approval and free-form input go back to the Web UI, avoiding cards that look clickable but can never be completed.
135
+ - IM cards carry a whole group of questions (protocol limit: 10) in one submission, so a prompt never splits into several cards and never leaves a card that looks clickable but can never be completed. Approvals still go back to the Web UI; beyond 200 components or 28 KB the delivery degrades to a plain-text card that still lists the questions and options.
136
136
 
137
137
  ## Limits (platform-determined, not implementation choices)
138
138
 
package/README.md CHANGED
@@ -23,18 +23,21 @@
23
23
  - **引用回复**:回答引用触发它的那条消息,单聊与群里都成立
24
24
  - **处理反馈**:收到消息先打 `Get`(收到)表情,**回答真正送达后**才在原消息追加 `DONE`,两个标记并排保留——入队不算完成(核心把消息入队后任务才异步跑);核心模式按核心的 `completes` 完成标记打(停滞、派发回执、转投确认等都不带;取消、失败、审批被拒、超出 token 上限而中断的回合也不带,因为它们没有正常答复;旧核心不打),独立模式按回合对齐,提醒作答在**结算**后当场打(多题只答一半时提醒还在等,不盖 `DONE`);失败只保留 `Get`,不留「已完成」的假信号;同一消息只补一次。飞书没有官方「正在输入」接口
25
25
  - **卡片更新**:流式回答原地更新同一张卡片;超过平台限制(14 天、单卡 5 QPS)后改发新卡
26
- - **交互卡片**:核心模式的**单问题**单选题与多选题在飞书里勾选后提交,结果交回核心;
27
- 独立模式的单题提问同样发卡片(单选/多选都是勾选器,靠文案区分,必须点提交),其余仍走
28
- 文字提醒。多问题与审批只发提示,请在 Web 端作答(核心要求一次提交全部问题,卡片回调
29
- 做不到分题提交);两者都支持「其他」输入
26
+ - **交互卡片**:核心模式的单选题与多选题在飞书里勾选后提交,结果交回核心。**一次问多个问题
27
+ 也只用一张卡**:所有题目收在同一张表单里,一个「提交」按钮一次答完(核心要求一次提交全部
28
+ 问题),控件按题号区分,无选项的题用输入框自由作答;少答或单选勾多项会指出是第几题并重画
29
+ 卡片。独立模式的单题提问同样发卡片。**审批**不代答,只提示去 Web 端处理;题目多到超过卡片
30
+ 组件/体积上限时改发纯文本卡片,把题目、选项与回复格式一并写出,可直接回复文字作答。两种模式都
31
+ 支持「其他」输入
30
32
  - **群聊**:只响应 @机器人 的消息(群聊权限只申请 @ 系列),不读全群
31
33
  - **任务提醒**:独立模式下,回合跑得久(默认超过 30 分钟)会在结束时发一条带耗时与结论的提醒;回合失败或被外部中止时立刻提醒并带上原始错误。主人自己按的停止不算失败
32
34
  - **面板**:Web 端插件页扫码一键创建应用,或手动填 App ID / App Secret;看连接状态、开关收发/核心接入、改消息行为;独立模式可调回合内插话、会话工作区、问题/审批提醒与长程任务提醒
33
35
 
34
- > 提问卡片(勾选器 + 提交 + 「其他」输入)在独立模式与核心模式都已于真实飞书租户验收:
35
- > 单选/多选靠卡片文案区分,提交后回传勾选项与「其他」输入。两种模式的作答被拒都有可见
36
- > 反馈:还能答的卡会**整卡重画**并写上原因(飞书的表单提交是一次性的,只发一句提示
37
- > 会让卡片点不动),可以重新勾选提交;已经不能再答的卡直接改成失效态、去掉勾选框。
36
+ > 提问卡片已在独立模式与核心模式的真实飞书租户验收,**单题与多题收进同一张表单**两种形态
37
+ > 都跑通了:单选/多选靠卡片文案区分,多题按 ①②③ 排开、题干加粗,提交后按题号回传勾选项
38
+ > 与「其他」输入。两种模式的作答被拒都有可见反馈:还能答的卡会**整卡重画**并写上原因
39
+ > (飞书的表单提交是一次性的,只发一句提示会让卡片点不动),已勾选与已填内容会回填,可以
40
+ > 改完再提交;已经不能再答的卡直接改成失效态、去掉勾选框。
38
41
  > `Get` / `DONE` 表情与卡片排版随租户配置略有差异,以实际表现为准。
39
42
 
40
43
  ## 安装
@@ -148,8 +151,9 @@ dsh plugin --profile web add file:/绝对路径/dsh-im-lark
148
151
  - 核心模式的 `DONE` 要先把握手的入站 `messageId` 翻成平台消息 id,这张表只留最近 500 条
149
152
  (有界,防常驻内存增长):插件重启后,或一条消息在 500 条之后才被核心报完成,
150
153
  就翻不到平台 id、不打 `DONE`——只影响完成表情,不影响答案送达。
151
- - IM 卡片只承载单问题、有选项的交互;多问题/审批/自由输入交回 Web 端,避免出现
152
- 「点了按钮但永远答不完」的卡。
154
+ - IM 卡片一次承载整组题目(协议上限 10 题):多题共用一张表单一次提交,既不会出现
155
+ 「点了按钮但永远答不完」的卡,也不会把一次提问拆成多张卡。审批仍交回 Web 端;超过
156
+ 200 组件或 28 KB 时降级为纯文本卡片,题目与选项照常发出。
153
157
 
154
158
  ## 限制(平台决定,不是实现取舍)
155
159
 
@@ -0,0 +1,30 @@
1
+ /**
2
+ * 桥的文本与错误辅助:卡片装不下时的降级文本、协议回执的错误截断与错误码。
3
+ *
4
+ * 独立成模块,让 `bridge.ts` 只留协议语义;这些函数不持有状态。
5
+ */
6
+ import { interactionText } from "./question-text.js";
7
+ /**
8
+ * 卡片装不下时退回的文本内容(由 outbound 渲染成 markdown 卡片)。
9
+ *
10
+ * 交互必须一起带上——降级后用户只能文字作答,不给题目和选项就没法答;
11
+ * 标题由 outbound 的卡片头渲染,正文不再重复 `#`。
12
+ */
13
+ export function renderFallbackText(delivery) {
14
+ const interaction = delivery.interaction === undefined
15
+ ? ''
16
+ : interactionText(delivery.interaction, { markdown: false });
17
+ return [delivery.body, delivery.detail ?? '', interaction]
18
+ .filter((part) => part !== '')
19
+ .join('\n\n');
20
+ }
21
+ /** 协议规定 `Receipt.error` 最多 500 字符;超长会让核心解析失败并按 uncertain 重投。 */
22
+ function truncateError(error) {
23
+ return error.length > 500 ? `${error.slice(0, 497)}...` : error;
24
+ }
25
+ export function failure(deliveryId, errorCode, error) {
26
+ return { deliveryId, status: 'failed', messagesSent: 0, errorCode, error: truncateError(error) };
27
+ }
28
+ export function errorText(error) {
29
+ return error instanceof Error ? error.message : String(error);
30
+ }
@@ -8,7 +8,9 @@
8
8
  * (核心侧对「先注册后确定账号」没有宽容度)。
9
9
  */
10
10
  import { DEFAULT_MAX_TEXT_CHARS } from "../shared/limits.js";
11
- import { InteractionStore, answerFromAction, renderAnsweredCard, renderDeliveryCard, renderRejectedCard, renderRetryCard, renderSupersededCard, cardFits } from "./cards.js";
11
+ import { InteractionStore, MAX_ANSWER_QUESTIONS, answerFromAction, isAnswerable, renderAnsweredCard, renderDeliveryCard, renderRejectedCard, renderRetryCard, renderSupersededCard, cardFits } from "./cards.js";
12
+ import { errorText, failure, renderFallbackText } from "./bridge-text.js";
13
+ import { extensionOf } from "./media.js";
12
14
  import { OutboundChannel } from "./outbound.js";
13
15
  import { PROTOCOL_V1 } from "./protocol.js";
14
16
  /** 能力声明:与方案设计 6.3 一致,测试里会用核心的 Schema 再校验一次。 */
@@ -20,7 +22,8 @@ const CAPABILITIES = {
20
22
  multiChoice: true,
21
23
  freeText: true,
22
24
  maxOptions: 20,
23
- maxQuestions: 1,
25
+ // 多题收进同一张表单一次提交,所以能答满协议上限(`maxQuestions` schema 封顶 10)。
26
+ maxQuestions: MAX_ANSWER_QUESTIONS,
24
27
  updateAfterAnswer: 'any',
25
28
  }),
26
29
  edit: Object.freeze({ scope: 'any', minIntervalMs: 2_000, maxLifetimeMs: 14 * 24 * 60 * 60 * 1000 }),
@@ -43,7 +46,7 @@ const REJECT_NOTES = {
43
46
  'wrong-bridge': '这张卡不属于当前接入的机器人,请在 Web 端作答。',
44
47
  'not-delivered': '这张卡没有真正发出去,请在 Web 端作答。',
45
48
  'not-allowed': '审批要在 Web 端处理,飞书里不代答。',
46
- 'invalid-answer': '没认出这次选择:单选题只能勾一项,勾选(或填「其他」)后点「提交」。',
49
+ 'invalid-answer': '没认出这次选择:单选题只能勾一项,选好后点「提交」。',
47
50
  };
48
51
  /** 这些原因意味着卡不能再答:改成失效态,别留一排还能点的勾选框。 */
49
52
  const TERMINAL_REJECTS = new Set(['unknown', 'expired', 'wrong-bridge', 'not-delivered']);
@@ -143,9 +146,11 @@ export function createLarkBridge(deps) {
143
146
  }));
144
147
  const card = renderDeliveryCard(delivery, { interactive: delivery.interaction !== undefined });
145
148
  const useCard = cardFits(card);
146
- // 交互卡装不下时明确降级并回失败码:只发纯文本再回「已送达」会让核心白等作答。
149
+ // 交互卡装不下时明确降级:内容照发,回执里带 error 说明;状态仍是 sent,避免核心重投。
147
150
  const interactionDropped = delivery.interaction !== undefined && !useCard;
148
- const fallbackNote = interactionDropped ? '\n\n(内容超过卡片上限,交互已降级为纯文本;请在 Web 端作答。)' : '';
151
+ const fallbackNote = interactionDropped
152
+ ? '\n\n(内容超过卡片上限,交互已降级为纯文本卡片;可直接回复文字作答,或到 Web 端处理。)'
153
+ : '';
149
154
  const replyTarget = delivery.inReplyTo === undefined ? undefined : inbound.get(delivery.inReplyTo);
150
155
  let receipt;
151
156
  try {
@@ -191,7 +196,7 @@ export function createLarkBridge(deps) {
191
196
  if (delivery.interaction !== undefined &&
192
197
  messageId !== undefined &&
193
198
  useCard &&
194
- delivery.interaction.questions.length === 1) {
199
+ isAnswerable(delivery.interaction)) {
195
200
  // 同一交付被重投时不要把它从「已作答」打回待作答。
196
201
  const previous = interactions.get(deliveryId);
197
202
  interactions.add({
@@ -214,9 +219,9 @@ export function createLarkBridge(deps) {
214
219
  ...(receipt.messageIds.length === 0 ? {} : { bridgeMessageIds: receipt.messageIds }),
215
220
  messagesSent: receipt.messagesSent,
216
221
  };
217
- // 内容已经送达,只是交互改在 Web 端作答;回成功避免核心重投或换路由。
222
+ // 内容已经送达,只是交互改在文字上作答;回成功避免核心重投或换路由。
218
223
  return interactionDropped
219
- ? { ...sent, error: '交互卡片超过平台上限,已降级为纯文本;请在 Web 端作答' }
224
+ ? { ...sent, error: '交互卡片超过平台上限,已降级为纯文本卡片;可在飞书回复文字作答,或到 Web 端处理' }
220
225
  : sent;
221
226
  }
222
227
  /**
@@ -279,14 +284,17 @@ export function createLarkBridge(deps) {
279
284
  * 提示等于把这张卡废掉;不能再答的直接改成失效态。都改写同一张卡,所以不会刷屏;
280
285
  * 只有卡不在手里(重启丢了记录、回调缺 id)才退化成一条文字提示,同卡同原因只发一次。
281
286
  */
282
- async function noteRejected(action, reason, deliveryId) {
287
+ async function noteRejected(action, reason, deliveryId, detail) {
283
288
  if (reason === 'settled')
284
289
  return; // 已经答过了,再提示只会吵。
285
- const note = REJECT_NOTES[reason];
290
+ // 具体原因(第几题没答、第几题多勾了)比通用文案有用,有就用它。
291
+ const note = detail !== undefined && detail !== '' ? detail : REJECT_NOTES[reason];
286
292
  const terminal = TERMINAL_REJECTS.has(reason);
287
293
  const record = deliveryId === undefined ? undefined : delivered.get(deliveryId);
288
294
  if (record !== undefined) {
289
- const card = terminal ? renderRejectedCard(record.delivery, note) : renderRetryCard(record.delivery, note);
295
+ const card = terminal
296
+ ? renderRejectedCard(record.delivery, note)
297
+ : renderRetryCard(record.delivery, note, action.formValues);
290
298
  try {
291
299
  await deps.api.patchCard({ messageId: record.messageId, card });
292
300
  if (terminal && deliveryId !== undefined)
@@ -308,9 +316,16 @@ export function createLarkBridge(deps) {
308
316
  }
309
317
  async function applyCardAction(action) {
310
318
  const deliveryId = typeof action.value.d === 'string' ? action.value.d : undefined;
311
- const result = answerFromAction(action.value, action.option, action.formValues, action.operatorOpenId, interactions, now());
319
+ // 审批卡不登记待作答(见 isAnswerable),回调到这里就没有记录;不先认出来会
320
+ // 被当成「已失效」并提示重启过,与实际原因(IM 不代答审批)相差很远。
321
+ const sentRecord = deliveryId === undefined ? undefined : delivered.get(deliveryId);
322
+ if (sentRecord?.delivery.interaction?.questions.some((question) => question.intent === 'approval') === true) {
323
+ await noteRejected(action, 'not-allowed', deliveryId);
324
+ return { accepted: false, reason: 'not-allowed', detail: '审批请在 Web 端处理' };
325
+ }
326
+ const result = answerFromAction(action.value, action.formValues, action.operatorOpenId, interactions, now());
312
327
  if ('reason' in result) {
313
- await noteRejected(action, result.reason, deliveryId);
328
+ await noteRejected(action, result.reason, deliveryId, result.detail);
314
329
  return { accepted: false, reason: result.reason, ...(result.detail === undefined ? {} : { detail: result.detail }) };
315
330
  }
316
331
  const accepted = await answer(result);
@@ -385,29 +400,3 @@ function remember(map, key, value, max) {
385
400
  map.delete(oldest.value);
386
401
  }
387
402
  }
388
- /** 协议规定 `Receipt.error` 最多 500 字符;超长会让核心解析失败并按 uncertain 重投。 */
389
- function truncateError(error) {
390
- return error.length > 500 ? `${error.slice(0, 497)}...` : error;
391
- }
392
- function failure(deliveryId, errorCode, error) {
393
- return { deliveryId, status: 'failed', messagesSent: 0, errorCode, error: truncateError(error) };
394
- }
395
- /** 卡片装不下时退回「标题 + 正文」:由 outbound 按文本分条。 */
396
- function renderFallbackText(delivery) {
397
- return [`# ${delivery.title}`, delivery.body, delivery.detail ?? ''].filter((part) => part !== '').join('\n\n');
398
- }
399
- function errorText(error) {
400
- return error instanceof Error ? error.message : String(error);
401
- }
402
- function extensionOf(mediaType) {
403
- switch (mediaType) {
404
- case 'image/jpeg':
405
- return 'jpg';
406
- case 'image/webp':
407
- return 'webp';
408
- case 'image/gif':
409
- return 'gif';
410
- default:
411
- return 'png';
412
- }
413
- }
@@ -11,7 +11,8 @@
11
11
  * 交互按钮把 `value` 收敛成短键对象(`{d,q,o}`):卡片体积敏感,且 `value`
12
12
  * 必须是对象(平台硬要求)。
13
13
  */
14
- import { CARD_BODY_BYTES_MAX } from "../shared/limits.js";
14
+ import { CARD_BODY_BYTES_MAX, CARD_COMPONENTS_MAX } from "../shared/limits.js";
15
+ import { interactionText, multiSelectSuffix, questionHeading } from "./question-text.js";
15
16
  export const CARD_SCHEMA = '2.0';
16
17
  /** 一张只含 Markdown 的卡片。 */
17
18
  export function renderMarkdownCard(markdown, options = {}) {
@@ -27,7 +28,27 @@ export function cardBytes(card) {
27
28
  return Buffer.byteLength(JSON.stringify(card), 'utf8');
28
29
  }
29
30
  export function cardFits(card) {
30
- return cardBytes(card) <= CARD_BODY_BYTES_MAX;
31
+ return cardBytes(card) <= CARD_BODY_BYTES_MAX && cardComponents(card) <= CARD_COMPONENTS_MAX;
32
+ }
33
+ /** 组件数:数所有带 `tag` 的对象(含 form 里的子控件),比平台口径略保守。 */
34
+ export function cardComponents(card) {
35
+ let count = 0;
36
+ const walk = (node) => {
37
+ if (Array.isArray(node)) {
38
+ for (const item of node)
39
+ walk(item);
40
+ return;
41
+ }
42
+ if (typeof node !== 'object' || node === null)
43
+ return;
44
+ const record = node;
45
+ if (typeof record.tag === 'string')
46
+ count += 1;
47
+ for (const value of Object.values(record))
48
+ walk(value);
49
+ };
50
+ walk(card);
51
+ return count;
31
52
  }
32
53
  /** 消息体:`content` 字段要的是 JSON 字符串,不是对象。 */
33
54
  export function cardContent(card) {
@@ -36,20 +57,37 @@ export function cardContent(card) {
36
57
  function optionText(option) {
37
58
  return { tag: 'lark_md', content: `**${option.label}**${option.description === undefined || option.description === '' ? '' : `\n${option.description}`}` };
38
59
  }
39
- function customInput() {
60
+ /** 勾选器名:`answer_<题号>_<选项号>`。多题共用一张 form,题号让 name 全卡唯一。 */
61
+ function checkerName(questionIndex, optionIndex) {
62
+ return `answer_${questionIndex}_${optionIndex}`;
63
+ }
64
+ /** 自由文本输入名:无选项的题、以及有选项时的「其他」都用它。 */
65
+ function inputName(questionIndex) {
66
+ return `custom_${questionIndex}`;
67
+ }
68
+ function customInput(name, placeholder = '其他答案(可选):填写后点提交', value) {
40
69
  return {
41
70
  tag: 'input',
42
- name: 'custom_input',
43
- placeholder: { tag: 'plain_text', content: '其他答案(可选):填写后点提交' },
71
+ name,
72
+ placeholder: { tag: 'plain_text', content: placeholder },
44
73
  width: 'fill',
74
+ // 重画时回填已填内容;`default_value` 是官方 input 字段(见 docs/protocol)。
75
+ ...(value === undefined ? {} : { default_value: value }),
45
76
  };
46
77
  }
47
- function submitButton(value) {
78
+ /** 表单值里的自由文本:空串、全空白、非字符串都当没填。 */
79
+ function trimText(raw) {
80
+ if (typeof raw !== 'string')
81
+ return undefined;
82
+ const text = raw.trim();
83
+ return text === '' ? undefined : text;
84
+ }
85
+ function submitButton(value, label = '提交') {
48
86
  return {
49
87
  tag: 'button',
50
88
  name: 'ask_submit',
51
89
  type: 'primary',
52
- text: { tag: 'plain_text', content: '提交' },
90
+ text: { tag: 'plain_text', content: label },
53
91
  form_action_type: 'submit',
54
92
  behaviors: [{ type: 'callback', value }],
55
93
  };
@@ -82,19 +120,16 @@ export function renderDeliveryCard(delivery, options = {}) {
82
120
  const interaction = options.interaction ?? delivery.interaction;
83
121
  if (options.interactive !== false && interaction !== undefined) {
84
122
  if (!isAnswerable(interaction)) {
85
- for (const question of interaction.questions) {
86
- elements.push({ tag: 'markdown', content: `**${question.header ?? '请选择'}**\n${question.question}`, text_size: 'normal' });
87
- }
88
- elements.push({
89
- tag: 'markdown',
90
- content: '_这条交互包含多个问题,或需要审批/自定义输入;请在 DeepSeek Harness Web 端作答,审批也在 Web 端处理。_',
91
- text_size: 'notation',
92
- });
123
+ // 不能在 IM 作答的交互也要把题目、选项与回复指引交代清楚:
124
+ // 光给题干,用户既看不到选项,也不知道该去哪、怎么回。
125
+ elements.push({ tag: 'markdown', content: interactionText(interaction, { markdown: true }), text_size: 'normal' });
93
126
  }
94
127
  else {
95
- for (const question of interaction.questions) {
96
- elements.push(...renderQuestion(delivery.id, question));
97
- }
128
+ elements.push({
129
+ tag: 'form',
130
+ name: 'ask_form',
131
+ elements: formElements(delivery.id, interaction.questions, options.formValues),
132
+ });
98
133
  }
99
134
  }
100
135
  return {
@@ -107,52 +142,66 @@ export function renderDeliveryCard(delivery, options = {}) {
107
142
  /**
108
143
  * 这套交互能不能在飞书卡片里答完。
109
144
  *
110
- * 核心要求一次提交全部问题;多问题时用户没法在一张卡上「先答一题、再答一题」,
111
- * 所以只对单问题、非审批、且有选项的交互渲染按钮;其余明确引导去 Web 端。
145
+ * 核心要求一次提交全部问题,所以多题必须收进**同一张 form** 一次提交(协议上限
146
+ * 10 题)。审批不代答;超出上限的交回 Web 端。无选项的题用输入框收自定义答案:
147
+ * 核心的桥路校验(`validateAnswer`)接受非空 custom。
112
148
  */
149
+ export const MAX_ANSWER_QUESTIONS = 10;
113
150
  export function isAnswerable(interaction) {
114
- if (interaction.questions.length !== 1)
151
+ const { questions } = interaction;
152
+ if (questions.length === 0 || questions.length > MAX_ANSWER_QUESTIONS)
115
153
  return false;
116
- const question = interaction.questions[0];
117
- return question.intent !== 'approval' && (question.options?.length ?? 0) > 0;
154
+ return questions.every((question) => question.intent !== 'approval');
118
155
  }
119
- /** 一个问题:题干 + 选项按钮;审批类只提示、不给按钮。 */
120
- function renderQuestion(deliveryId, question) {
121
- const label = question.header ?? '请选择';
122
- const elements = [
123
- { tag: 'markdown', content: `**${label}**\n${question.question}`, text_size: 'normal' },
156
+ /** 一道题在 form 里的部分:题干 + 详情 + 单双选说明 + 勾选器(或输入框)。 */
157
+ function questionFormPart(question, index, total, formValues) {
158
+ const custom = trimText(formValues?.[inputName(index)]);
159
+ const parts = [
160
+ {
161
+ tag: 'markdown',
162
+ content: `**${questionHeading(question, index, total)}**${multiSelectSuffix(question)}`,
163
+ text_size: 'normal',
164
+ },
124
165
  ];
125
- if (question.intent === 'approval') {
126
- elements.push({ tag: 'markdown', content: '_审批请在 DeepSeek Harness Web 端处理。_', text_size: 'notation' });
127
- return elements;
166
+ if (question.detail !== undefined && question.detail !== '') {
167
+ parts.push({ tag: 'markdown', content: question.detail, text_size: 'normal' });
128
168
  }
129
169
  const options = question.options ?? [];
130
- if (options.length === 0)
131
- return elements;
170
+ if (options.length === 0) {
171
+ parts.push({ tag: 'markdown', content: '直接在下方输入框作答,填好后点「提交」。', text_size: 'notation' });
172
+ parts.push(customInput(inputName(index), '在这里作答:填写后点提交', custom));
173
+ return parts;
174
+ }
132
175
  // 飞书卡片没有单选按钮组:单选和多选都用勾选器,靠文案说明区别,
133
- // 两者都必须点「提交」才生效(值走 form_value.answer_<下标> / custom_input)。
134
- elements.push({
176
+ // 两者都必须点「提交」才生效(值走 form_value.answer_<题号>_<选项号>)。
177
+ parts.push({
135
178
  tag: 'markdown',
136
179
  content: question.multiSelect === true
137
180
  ? '多选:可以勾选多项,选好后点「提交」。'
138
181
  : '单选:只能勾选一项,选好后点「提交」。',
139
182
  text_size: 'notation',
140
183
  });
141
- elements.push({
142
- tag: 'form',
143
- name: 'ask_form',
144
- elements: [
145
- ...options.map((option, index) => ({
146
- tag: 'checker',
147
- name: `answer_${index}`,
148
- checked: false,
149
- overall_checkable: false,
150
- text: optionText(option),
151
- })),
152
- customInput(),
153
- submitButton({ d: deliveryId, q: question.id }),
154
- ],
184
+ options.forEach((option, optionIndex) => {
185
+ parts.push({
186
+ tag: 'checker',
187
+ name: checkerName(index, optionIndex),
188
+ checked: formValues?.[checkerName(index, optionIndex)] === true,
189
+ overall_checkable: false,
190
+ text: optionText(option),
191
+ });
155
192
  });
193
+ parts.push(customInput(inputName(index), undefined, custom));
194
+ return parts;
195
+ }
196
+ /**
197
+ * 整个交互的 form:所有题目的控件收在同一张表单里,一个「提交」按钮整卡提交。
198
+ *
199
+ * form 容器只能放在卡片根部,所以题干也进 form;控件 `name` 全卡唯一,用题号区分。
200
+ */
201
+ function formElements(deliveryId, questions, formValues) {
202
+ const elements = [];
203
+ questions.forEach((question, index) => elements.push(...questionFormPart(question, index, questions.length, formValues)));
204
+ elements.push(submitButton({ d: deliveryId }, questions.length > 1 ? `提交 ${questions.length} 题答案` : '提交'));
156
205
  return elements;
157
206
  }
158
207
  /** 已作答的卡:保留正文与题干,附上选择结果,不再有按钮。 */
@@ -161,7 +210,10 @@ export function renderAnsweredCard(delivery, answers) {
161
210
  const body = card.body;
162
211
  const lines = answers.map((answer) => {
163
212
  const question = delivery.interaction?.questions.find((item) => item.id === answer.id);
164
- const chosen = answer.selected.length > 0 ? answer.selected.join('、') : answer.custom ?? '(自定义)';
213
+ // 勾选与「其他」可能同时存在(多选),两段都要展示,不能只留勾选。
214
+ const chosen = [answer.selected.join('、'), answer.custom]
215
+ .filter((part) => part !== undefined && part !== '')
216
+ .join(';') || '(未填写)';
165
217
  return `- ${question?.header ?? question?.question ?? answer.id}:${chosen}`;
166
218
  });
167
219
  body.elements.push({ tag: 'markdown', content: ['---', '', '**已作答**', ...lines].join('\n'), text_size: 'normal' });
@@ -181,8 +233,11 @@ export function renderSupersededCard(delivery) {
181
233
  * 回到可用状态(官方「表单提交后更新为已提交卡片」的同一套做法)。所以拒绝时不能只
182
234
  * 发一句提示,得把这张卡本身重画一遍。
183
235
  */
184
- export function renderRetryCard(delivery, note) {
185
- const card = renderDeliveryCard(delivery, { interactive: true });
236
+ export function renderRetryCard(delivery, note, formValues) {
237
+ const card = renderDeliveryCard(delivery, {
238
+ interactive: true,
239
+ ...(formValues === undefined ? {} : { formValues }),
240
+ });
186
241
  const body = card.body;
187
242
  body.elements.push({ tag: 'markdown', content: `_**${note}**_`, text_size: 'notation' });
188
243
  return card;
@@ -239,128 +294,62 @@ export class InteractionStore {
239
294
  }
240
295
  }
241
296
  /**
242
- * 把按钮回调翻译成协议里的作答。
297
+ * 把表单提交翻译成协议里的作答:一道题一个答项,**一次提交必须答完全部题目**。
243
298
  *
244
299
  * 约定:
245
- * - value 里的 `d`/`q`/`o` 是我们自己写的,短键省卡片体积;
246
- * - 多选的 `action.option` 可能是单个值、逗号串或数组,三种都认;
247
- * - 审批类一律 `not-allowed`(协议里 IM 不代答审批)。
300
+ * - value 里的 `d` 是交付 id(短键省卡片体积,且 value 必须是对象);
301
+ * - 勾选值在 `form_value.answer_<题号>_<选项号>`,自由文本在 `form_value.custom_<题号>`;
302
+ * - 单选有「其他」时以自由文本为准(勾选项忽略,与旧版一致);多选可与勾选并存;
303
+ * - 少答、单选勾多项都在这里拒绝并指出题号,桥把原因写回卡片让用户重填;
304
+ * - 审批类不会被登记为可作答(见 `isAnswerable`),真出现就跳过它。
248
305
  */
249
- export function answerFromAction(value, option, formValues, sender, store, now) {
306
+ export function answerFromAction(value, formValues, sender, store, now) {
250
307
  const deliveryId = typeof value.d === 'string' ? value.d : '';
251
- const questionId = typeof value.q === 'string' ? value.q : '';
252
- if (deliveryId === '' || questionId === '')
253
- return { reason: 'invalid', detail: '回调缺少交付或问题 id' };
308
+ if (deliveryId === '')
309
+ return { reason: 'invalid', detail: '这张卡的作答信息不完整,请在 Web 端重新作答。' };
254
310
  const pending = store.get(deliveryId);
255
311
  if (pending === undefined)
256
- return { reason: 'unknown', detail: '交付已不在内存里(可能已重启)' };
312
+ return { reason: 'unknown', detail: '这张卡已经失效(插件重启过),请在 Web 端重新作答。' };
257
313
  if (pending.answered)
258
314
  return { reason: 'settled', detail: '这条已经作答' };
259
315
  if (pending.expiresAt !== undefined && pending.expiresAt <= now)
260
316
  return { reason: 'expired' };
261
- const question = pending.questions.find((item) => item.id === questionId);
262
- if (question === undefined)
263
- return { reason: 'invalid', detail: '问题不在这次交付里' };
264
- if (question.intent === 'approval')
265
- return { reason: 'not-allowed', detail: '审批请在 Web 端处理' };
266
- const selected = resolveSelection(question, value, option, formValues);
267
- if (selected === undefined)
268
- return { reason: 'invalid-answer', detail: '无法从回调里认出选项' };
269
- if (question.multiSelect !== true && selected.selected.length > 1) {
270
- return { reason: 'invalid-answer', detail: '单选题只能勾选一项' };
271
- }
272
- return {
273
- deliveryId,
274
- sender,
275
- answers: [{
276
- id: question.id,
277
- selected: selected.selected,
278
- ...(selected.custom === undefined ? {} : { custom: selected.custom }),
279
- }],
280
- at: now,
281
- };
282
- }
283
- /** 把按钮 index / 多选值还原成选项文案。 */
284
- function resolveSelection(question, value, option, formValues) {
285
- const options = question.options ?? [];
286
- const fromIndices = (raw) => {
287
- const indices = toIndexList(raw);
288
- if (indices === undefined)
289
- return undefined;
290
- const labels = indices.map((index) => options[index]?.label).filter((label) => label !== undefined);
291
- return labels.length === 0 ? undefined : labels;
292
- };
293
- if (typeof value.o === 'number')
294
- return pick(fromIndices([value.o]));
295
- if (typeof value.o === 'string')
296
- return pick(fromIndices([value.o]));
297
- // 表单提交(勾选框 + 「其他」输入):answer_<下标> 为 true,custom_input 为自由文本。
298
- const custom = customOf(formValues);
299
- if (formValues !== undefined) {
300
- const checked = Object.entries(formValues)
301
- .filter(([key, value]) => /^answer_(\d+)$/u.test(key) && value === true)
302
- .map(([key]) => Number(key.slice('answer_'.length)))
303
- .filter((index) => options[index] !== undefined)
304
- .sort((left, right) => left - right);
305
- if (checked.length > 0 || custom !== undefined) {
306
- if (question.multiSelect !== true && custom !== undefined)
307
- return { selected: [], custom };
308
- return { selected: checked.map((index) => options[index].label), ...(custom === undefined ? {} : { custom }) };
309
- }
310
- }
311
- const fromForm = formValues?.answer;
312
- if (fromForm !== undefined) {
313
- const labels = fromIndices(fromForm);
314
- if (labels !== undefined)
315
- return pick(labels);
316
- }
317
- // 多选:数组优先;字符串可能是 "0,2"、"0%2C2" 或单个值。
318
- const multi = fromIndices(option);
319
- if (multi !== undefined)
320
- return pick(multi);
321
- // 有些客户端直接把选项文案回传,认文案兜底。
322
- const labels = toStringList(option).filter((text) => options.some((item) => item.label === text));
323
- return pick(labels.length === 0 ? undefined : labels);
324
- }
325
- function pick(selected) {
326
- return selected === undefined ? undefined : { selected };
327
- }
328
- /** 表单里「其他」输入:空串当没填。 */
329
- function customOf(formValues) {
330
- const raw = formValues?.custom_input;
331
- if (typeof raw !== 'string')
332
- return undefined;
333
- const text = raw.trim();
334
- return text === '' ? undefined : text;
335
- }
336
- function toIndexList(raw) {
337
- const items = Array.isArray(raw) ? raw : [raw];
338
- const indices = [];
339
- for (const item of items) {
340
- if (typeof item === 'number') {
341
- if (!Number.isInteger(item) || item < 0)
342
- return undefined;
343
- indices.push(item);
344
- continue;
317
+ if (formValues === undefined)
318
+ return { reason: 'invalid-answer', detail: '没收到表单内容,请重新提交;或到 Web 端作答。' };
319
+ const answers = [];
320
+ const missing = [];
321
+ const singleOverflows = [];
322
+ pending.questions.forEach((question, index) => {
323
+ if (question.intent === 'approval')
324
+ return;
325
+ const options = question.options ?? [];
326
+ const checked = options
327
+ .map((option, optionIndex) => (formValues[checkerName(index, optionIndex)] === true ? option.label : undefined))
328
+ .filter((label) => label !== undefined);
329
+ const custom = trimText(formValues[inputName(index)]);
330
+ // 单选的「其他」是替代项:填了就只交 custom,勾选不再参与校验。
331
+ const customOnly = question.multiSelect !== true && custom !== undefined;
332
+ if (!customOnly && options.length > 0 && question.multiSelect !== true && checked.length > 1) {
333
+ singleOverflows.push(index + 1);
345
334
  }
346
- if (typeof item !== 'string')
347
- continue;
348
- for (const text of item.split(',')) {
349
- const trimmed = text.trim();
350
- if (trimmed === '')
351
- continue;
352
- const parsed = Number(trimmed);
353
- if (!Number.isInteger(parsed) || parsed < 0)
354
- return undefined;
355
- indices.push(parsed);
335
+ if (checked.length === 0 && custom === undefined) {
336
+ missing.push(index + 1);
337
+ return;
356
338
  }
339
+ answers.push({
340
+ id: question.id,
341
+ selected: customOnly ? [] : checked,
342
+ ...(custom === undefined ? {} : { custom }),
343
+ });
344
+ });
345
+ if (singleOverflows.length > 0) {
346
+ return {
347
+ reason: 'invalid-answer',
348
+ detail: `第 ${singleOverflows.join('、')} 题是单选题,只能勾选一项`,
349
+ };
357
350
  }
358
- return indices.length === 0 ? undefined : indices;
359
- }
360
- function toStringList(raw) {
361
- if (Array.isArray(raw))
362
- return raw.filter((item) => typeof item === 'string');
363
- if (typeof raw === 'string')
364
- return raw.split(',').map((item) => item.trim());
365
- return [];
351
+ if (missing.length > 0) {
352
+ return { reason: 'invalid-answer', detail: `第 ${missing.join('、')} 题还没有作答;勾选或填写后点「提交」` };
353
+ }
354
+ return { deliveryId, sender, answers, at: now };
366
355
  }
@@ -10,6 +10,7 @@
10
10
  */
11
11
  import { MAX_FILE_BYTES, MAX_FILES_BYTES, MAX_IMAGE_BYTES, OWNER_FILES_MAX, OWNER_IMAGES_MAX } from "../shared/limits.js";
12
12
  import { parseCardAction, parseMessageEvent } from "./inbound.js";
13
+ import { extensionOf } from "./media.js";
13
14
  import { addReaction, REACTION_ACK } from "./reactions.js";
14
15
  import { SeenStore } from "./state/seen.js";
15
16
  const TEXT_MAX = 20_000;
@@ -309,15 +310,3 @@ function mediaTypeOfName(name) {
309
310
  return 'text/plain';
310
311
  return undefined;
311
312
  }
312
- function extensionOf(mediaType) {
313
- switch (mediaType) {
314
- case 'image/jpeg':
315
- return 'jpg';
316
- case 'image/webp':
317
- return 'webp';
318
- case 'image/gif':
319
- return 'gif';
320
- default:
321
- return 'png';
322
- }
323
- }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * 媒体类型 → 文件后缀。
3
+ *
4
+ * 入站(下载图片时给临时名)与出站(核心只给 base64 与 mediaType 时补文件名)都要用,
5
+ * 放在一处,改一处两边同时生效。
6
+ */
7
+ /** 插件认得的四种图片类型;未知类型按 png 兜底(平台只接受这四种)。 */
8
+ export function extensionOf(mediaType) {
9
+ switch (mediaType) {
10
+ case 'image/jpeg':
11
+ return 'jpg';
12
+ case 'image/webp':
13
+ return 'webp';
14
+ case 'image/gif':
15
+ return 'gif';
16
+ default:
17
+ return 'png';
18
+ }
19
+ }
@@ -0,0 +1,70 @@
1
+ const CIRCLED_NUMBERS = '①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳';
2
+ /** 多题时题目用圆圈序号、选项用纯数字:两层都是「1.」时分不清在给哪一层回复。 */
3
+ export function questionMarker(index, total) {
4
+ if (total <= 1)
5
+ return '';
6
+ return `${CIRCLED_NUMBERS[index] ?? `${index + 1}.`} `;
7
+ }
8
+ /** 题目标题:有标题用「标题:题干」,没有就只用题干。 */
9
+ export function questionTitle(question) {
10
+ return question.header === undefined || question.header === ''
11
+ ? question.question
12
+ : `${question.header}:${question.question}`;
13
+ }
14
+ /**
15
+ * 题目抬头的主体:序号 + 标题,不加粗也不带多选标注——卡片侧自己包 `**`,
16
+ * 标注留在加粗之外(与核心 `interactionMarkdown` 的形态一致)。
17
+ */
18
+ export function questionHeading(question, index, total) {
19
+ return `${questionMarker(index, total)}${questionTitle(question)}`;
20
+ }
21
+ /** 多选题的标注;单选题返回空串。 */
22
+ export function multiSelectSuffix(question) {
23
+ return question.multiSelect === true ? '(可多选)' : '';
24
+ }
25
+ /** 单题的回复指引;与核心 `interactionMarkdown` 的结尾保持一致。 */
26
+ function guidance(interaction) {
27
+ const { questions } = interaction;
28
+ if (questions.some((question) => question.intent === 'approval')) {
29
+ return '这条交互包含审批,请在 DeepSeek Harness Web 端作答,审批也在 Web 端处理。';
30
+ }
31
+ if (questions.length > 1) {
32
+ return '按题目顺序分行(或用「;」「。」分隔)回复,每段对应一题,可写序号或选项;段数对不上时整段文字作为每题的答案。';
33
+ }
34
+ const question = questions[0];
35
+ if (question !== undefined && (question.options ?? []).length === 0) {
36
+ return '直接回复文字作答。';
37
+ }
38
+ return '回复序号选择(多选用逗号分隔),或直接回复文字作答。';
39
+ }
40
+ /**
41
+ * 交互的文字形态:题目、选项与结尾的回复指引。
42
+ *
43
+ * `markdown` 控制加粗标记:卡片里的 markdown 组件认 `**`;降级文本按纯文本
44
+ * 形态给出(不加粗),避免在纯文本内容里出现星号。
45
+ */
46
+ export function interactionText(interaction, options) {
47
+ const { questions } = interaction;
48
+ if (questions.length === 0)
49
+ return '';
50
+ const bold = (text) => (options.markdown ? `**${text}**` : text);
51
+ const lines = [];
52
+ questions.forEach((question, index) => {
53
+ if (index > 0)
54
+ lines.push('---', '');
55
+ lines.push(`${bold(questionHeading(question, index, questions.length))}${multiSelectSuffix(question)}`);
56
+ if (question.detail !== undefined && question.detail !== '')
57
+ lines.push('', question.detail);
58
+ const questionOptions = question.options ?? [];
59
+ if (questionOptions.length > 0) {
60
+ lines.push('');
61
+ questionOptions.forEach((option, at) => {
62
+ const description = option.description;
63
+ lines.push(`${at + 1}. ${description === undefined || description === '' ? option.label : `${option.label} — ${description}`}`);
64
+ });
65
+ }
66
+ lines.push('');
67
+ });
68
+ lines.push(guidance(interaction));
69
+ return lines.join('\n');
70
+ }
@@ -7,6 +7,8 @@
7
7
  */
8
8
  /** 卡片请求体上限 30 KB;按 UTF-8 字节计,留出 JSON 转义与组件开销。 */
9
9
  export const CARD_BODY_BYTES_MAX = 28 * 1024;
10
+ /** 卡片组件数上限 200(数所有带 `tag` 的对象,比平台口径略保守)。 */
11
+ export const CARD_COMPONENTS_MAX = 200;
10
12
  /** 文本消息请求体上限 150 KB;我们远达不到,仍按它兜一道。 */
11
13
  export const TEXT_BODY_BYTES_MAX = 140 * 1024;
12
14
  /**
@@ -5,7 +5,7 @@
5
5
  * 发布时三处同步——package.json、锁文件(`npm version --no-git-tag-version`)、
6
6
  * 这里。
7
7
  */
8
- export const PLUGIN_VERSION = '0.1.6';
8
+ export const PLUGIN_VERSION = '0.1.7';
9
9
  /** 传输层实现版本:协议客户端行为变化时递增,与插件版本解耦。 */
10
10
  export const CHANNEL_VERSION = '1';
11
11
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-im-lark",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "type": "module",
5
5
  "description": "把飞书(Lark)接入 DeepSeek Harness 的 IM 桥插件",
6
6
  "license": "MIT",