@suwenguang/pi-feishu-bridge 0.0.0-stage → 0.6.2
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/.pi/extensions/feishu/index.ts +11 -0
- package/.pi/feishu/debug.pi.log +81 -0
- package/.pi/feishu/state.pi.json +12 -0
- package/README.md +210 -2
- package/package.json +57 -4
- package/src/adapters/pi/PiConversationRuntime.ts +1559 -0
- package/src/adapters/pi/index.ts +1169 -0
- package/src/adapters/pi/setup.ts +108 -0
- package/src/feishu/app-register.ts +50 -0
- package/src/feishu/ask.ts +388 -0
- package/src/feishu/attachment-processor.ts +198 -0
- package/src/feishu/attachments.ts +192 -0
- package/src/feishu/bridge-runtime.ts +129 -0
- package/src/feishu/bridge-store.ts +92 -0
- package/src/feishu/card-action-webhook.ts +141 -0
- package/src/feishu/card-actions.ts +241 -0
- package/src/feishu/card-builder.ts +277 -0
- package/src/feishu/cardkit-stream.ts +483 -0
- package/src/feishu/cards.ts +413 -0
- package/src/feishu/config.ts +427 -0
- package/src/feishu/daemon-spec.ts +43 -0
- package/src/feishu/debug.ts +51 -0
- package/src/feishu/dedupe-store.ts +150 -0
- package/src/feishu/delivery.ts +185 -0
- package/src/feishu/gateway-lock.ts +256 -0
- package/src/feishu/group-trigger.ts +128 -0
- package/src/feishu/image-send.ts +256 -0
- package/src/feishu/instance.ts +170 -0
- package/src/feishu/instances.ts +148 -0
- package/src/feishu/interactive-card.ts +236 -0
- package/src/feishu/learn-approval.ts +321 -0
- package/src/feishu/live-cards.ts +128 -0
- package/src/feishu/message-handler.ts +512 -0
- package/src/feishu/messages.ts +356 -0
- package/src/feishu/oversize-progress-card.ts +101 -0
- package/src/feishu/progress-channel.ts +154 -0
- package/src/feishu/progress-note.ts +371 -0
- package/src/feishu/prompt-timeout.ts +81 -0
- package/src/feishu/reply-card-options.ts +73 -0
- package/src/feishu/reply-card.ts +498 -0
- package/src/feishu/restart.ts +286 -0
- package/src/feishu/retry.ts +102 -0
- package/src/feishu/rich-text.ts +387 -0
- package/src/feishu/runtime-config.ts +286 -0
- package/src/feishu/runtime.ts +110 -0
- package/src/feishu/slash-commands.ts +239 -0
- package/src/feishu/thinking.ts +24 -0
- package/src/feishu/transport.ts +792 -0
- package/src/feishu/types.ts +183 -0
- package/src/feishu/ui-notify.ts +44 -0
- package/src/feishu/user-name.ts +121 -0
- package/src/feishu/workspace.ts +42 -0
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { mkdirSync } from "node:fs";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
import { CONFIG_PI_PATH, DEFAULT_CONFIG, ensureRoot, mask, writeJson } from "../../feishu/config.ts";
|
|
5
|
+
import { registerFeishuApp } from "../../feishu/app-register.ts";
|
|
6
|
+
import type { Domain, FeishuConfig, GroupPolicy } from "../../feishu/types.ts";
|
|
7
|
+
|
|
8
|
+
export async function uiSelect<T extends string>(ctx: ExtensionCommandContext, title: string, options: Array<{ value: T; label: string }>, initialValue?: T): Promise<T> {
|
|
9
|
+
const ui: any = ctx.ui;
|
|
10
|
+
if (typeof ui.select !== "function") {
|
|
11
|
+
throw new Error("Current UI does not support select prompts.");
|
|
12
|
+
}
|
|
13
|
+
const labels = options.map((o) => o.label);
|
|
14
|
+
const initialLabel = options.find((o) => o.value === initialValue)?.label;
|
|
15
|
+
const selectedLabel = await ui.select(title, labels, initialLabel ? { initialValue: initialLabel } : undefined);
|
|
16
|
+
const matched = options.find((o) => o.label === selectedLabel);
|
|
17
|
+
if (!matched) {
|
|
18
|
+
throw new Error("Selection cancelled.");
|
|
19
|
+
}
|
|
20
|
+
return matched.value;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function uiInput(ctx: ExtensionCommandContext, title: string, defaultValue = ""): Promise<string> {
|
|
24
|
+
const ui: any = ctx.ui;
|
|
25
|
+
if (typeof ui.input === "function") return String(await ui.input(title, defaultValue) || "");
|
|
26
|
+
if (typeof ui.prompt === "function") return String(await ui.prompt(title, defaultValue) || "");
|
|
27
|
+
throw new Error("Current UI does not support input prompts.");
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function uiConfirm(ctx: ExtensionCommandContext, title: string, initial = true): Promise<boolean> {
|
|
31
|
+
const ui: any = ctx.ui;
|
|
32
|
+
if (typeof ui.confirm === "function") return Boolean(await ui.confirm(title, "", { initialValue: initial }));
|
|
33
|
+
return initial;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function runSetup(ctx: ExtensionCommandContext, options: { configPath?: string; dir?: string } = {}) {
|
|
37
|
+
const configPath = options.configPath || CONFIG_PI_PATH;
|
|
38
|
+
// 当前实例(没有显式目录)沿用 ensureRoot():包含旧全局数据的搬迁。
|
|
39
|
+
// 指定了别的实例目录时只建目录 —— 不能拿当前实例的 ensureRoot 去动别的目录。
|
|
40
|
+
if (!options.dir || options.dir === dirname(CONFIG_PI_PATH)) {
|
|
41
|
+
ensureRoot();
|
|
42
|
+
} else {
|
|
43
|
+
mkdirSync(options.dir, { recursive: true });
|
|
44
|
+
}
|
|
45
|
+
const mode = await uiSelect(ctx,
|
|
46
|
+
"配置方式 / Setup method",
|
|
47
|
+
[
|
|
48
|
+
{ value: "auto", label: "扫码自动创建飞书助手 / Create by QR code" },
|
|
49
|
+
{ value: "manual", label: "手动填写已有应用 / Configure existing app" },
|
|
50
|
+
],
|
|
51
|
+
"auto",
|
|
52
|
+
);
|
|
53
|
+
|
|
54
|
+
let appId = "";
|
|
55
|
+
let appSecret = "";
|
|
56
|
+
let domain: Domain = "feishu";
|
|
57
|
+
|
|
58
|
+
if (mode === "auto") {
|
|
59
|
+
const created = await registerFeishuApp({
|
|
60
|
+
onNotify: (text) => ctx.ui.notify(text, "info"),
|
|
61
|
+
});
|
|
62
|
+
appId = created.appId;
|
|
63
|
+
appSecret = created.appSecret;
|
|
64
|
+
domain = created.domain;
|
|
65
|
+
} else {
|
|
66
|
+
domain = await uiSelect(ctx,
|
|
67
|
+
"应用区域 / App region",
|
|
68
|
+
[
|
|
69
|
+
{ value: "feishu", label: "Feishu 中国 / Feishu China" },
|
|
70
|
+
{ value: "lark", label: "Lark 国际 / Lark Global" },
|
|
71
|
+
],
|
|
72
|
+
"feishu",
|
|
73
|
+
);
|
|
74
|
+
appId = (await uiInput(ctx, "App ID / 应用 ID")).trim();
|
|
75
|
+
appSecret = (await uiInput(ctx, "App Secret / 应用密钥")).trim();
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const groupPolicy = await uiSelect<GroupPolicy>(ctx,
|
|
79
|
+
"群聊策略 / Group policy",
|
|
80
|
+
[
|
|
81
|
+
{ value: "open", label: "open:不需要 @,群/话题消息自动回复 / auto reply without @ in groups/topics" },
|
|
82
|
+
{ value: "mention", label: "mention:只有 @ 机器人才回复 / reply only when mentioned" },
|
|
83
|
+
],
|
|
84
|
+
"open",
|
|
85
|
+
);
|
|
86
|
+
|
|
87
|
+
const config: FeishuConfig = {
|
|
88
|
+
appId,
|
|
89
|
+
appSecret,
|
|
90
|
+
domain,
|
|
91
|
+
groupPolicy,
|
|
92
|
+
language: "zh",
|
|
93
|
+
reactEmoji: DEFAULT_CONFIG.reactEmoji,
|
|
94
|
+
autoStart: true,
|
|
95
|
+
};
|
|
96
|
+
// 实例目录跟着工作区走,直接写目标实例的配置(不存在覆盖别的工作区的问题)。
|
|
97
|
+
writeJson(configPath, config);
|
|
98
|
+
|
|
99
|
+
ctx.ui.notify(
|
|
100
|
+
`飞书配置已保存 / Feishu config saved\nPath: ${configPath}\nApp ID: ${mask(appId)}\n群聊策略 / Group policy: ${groupPolicy}`,
|
|
101
|
+
"info",
|
|
102
|
+
);
|
|
103
|
+
|
|
104
|
+
if (await uiConfirm(ctx, "现在启动飞书连接? / Start Feishu now?", true)) {
|
|
105
|
+
return config;
|
|
106
|
+
}
|
|
107
|
+
return undefined;
|
|
108
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 扫码注册飞书/Lark 机器人应用。
|
|
3
|
+
* 二维码打印到终端;提示信息通过 onNotify 回调交给调用方(Pi 用 TUI 通知)。
|
|
4
|
+
*/
|
|
5
|
+
import qrcode from "qrcode-terminal";
|
|
6
|
+
import type { Domain } from "./types.ts";
|
|
7
|
+
|
|
8
|
+
export type RegisteredFeishuApp = {
|
|
9
|
+
appId: string;
|
|
10
|
+
appSecret: string;
|
|
11
|
+
domain: Domain;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export async function registerFeishuApp(options?: { onNotify?: (text: string) => void }): Promise<RegisteredFeishuApp> {
|
|
15
|
+
const lark = await import("@larksuiteoapi/node-sdk");
|
|
16
|
+
const notify = options?.onNotify ?? ((text: string) => console.log(text));
|
|
17
|
+
notify("正在准备飞书授权二维码... / Preparing Feishu authorization QR code...");
|
|
18
|
+
|
|
19
|
+
const result = await lark.registerApp({
|
|
20
|
+
source: "pi-feishu-extension",
|
|
21
|
+
// 增量申请「斜杠指令」权限:扫码确认页会在此基础上叠加,平台基础权限不受影响。
|
|
22
|
+
// 若平台未开放额外配置灰度,该参数会被忽略并回退到默认流程。
|
|
23
|
+
addons: {
|
|
24
|
+
scopes: {
|
|
25
|
+
tenant: ["application:app_slash_command:write"],
|
|
26
|
+
},
|
|
27
|
+
},
|
|
28
|
+
onQRCodeReady(info: { url: string; expireIn: number }) {
|
|
29
|
+
qrcode.generate(info.url, { small: true }, (qr) => {
|
|
30
|
+
console.log("\n飞书/Lark 授权二维码 / Feishu/Lark authorization QR code");
|
|
31
|
+
console.log(qr);
|
|
32
|
+
console.log(info.url);
|
|
33
|
+
console.log(`二维码 ${info.expireIn} 秒后过期 / QR code expires in ${info.expireIn} seconds.`);
|
|
34
|
+
});
|
|
35
|
+
notify("请在终端扫描二维码,或打开终端中显示的链接。 / Scan the QR code in terminal, or open the link printed there.");
|
|
36
|
+
},
|
|
37
|
+
onStatusChange(info: any) {
|
|
38
|
+
if (info?.status === "domain_switched") {
|
|
39
|
+
notify("检测到 Lark 租户,正在切换区域。 / Detected Lark tenant; switching domain.");
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
const domain: Domain = result?.user_info?.tenant_brand === "lark" ? "lark" : "feishu";
|
|
45
|
+
return {
|
|
46
|
+
appId: result.client_id,
|
|
47
|
+
appSecret: result.client_secret,
|
|
48
|
+
domain,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 飞书「选择题」卡片:把模型要问用户的选项渲染成按钮,点一下即作答。
|
|
3
|
+
*
|
|
4
|
+
* 背景:模型在飞书里问「1A 2A 3A 这种格式回我」体验很差。桥接提供 feishu_ask 工具,
|
|
5
|
+
* 模型调用后这里渲染一张交互卡片,按钮回调走 card.action.trigger,
|
|
6
|
+
* 全部答完后把结果作为工具返回值交回模型。
|
|
7
|
+
*
|
|
8
|
+
* 待答状态放模块级单例:工具实例(会话内)与卡片回调(daemon 主会话)在同一个
|
|
9
|
+
* Node 进程、同一份模块图里,因此可以直接共享。
|
|
10
|
+
*/
|
|
11
|
+
import { debugLog } from "./debug.ts";
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* 选项:label 要短(按钮上显示,用业务词),description 写这道选项的好处与坏处
|
|
15
|
+
* (各一句,卡片正文显示)。非技术类需求一律业务语言,不带 proto 字段名 / 表名 / 函数名。
|
|
16
|
+
*/
|
|
17
|
+
export type AskOption = {
|
|
18
|
+
label: string;
|
|
19
|
+
description?: string;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export type AskQuestion = {
|
|
23
|
+
/** 短标题,如「货币范围」 */
|
|
24
|
+
header: string;
|
|
25
|
+
/** 完整问题 */
|
|
26
|
+
question: string;
|
|
27
|
+
/** 2-4 个选项 */
|
|
28
|
+
options: AskOption[];
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export type AskAnswer = {
|
|
32
|
+
header: string;
|
|
33
|
+
question: string;
|
|
34
|
+
/** 用户选了哪个 label;undefined = 未作答 */
|
|
35
|
+
chosen?: string;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
export type AskOutcome = {
|
|
39
|
+
answers: AskAnswer[];
|
|
40
|
+
/** true = 等超时了,answers 里可能有未作答项 */
|
|
41
|
+
timedOut: boolean;
|
|
42
|
+
/**
|
|
43
|
+
* true = 本次提问被主动取消(停止按钮 / 新一轮打断)。
|
|
44
|
+
* 此时整轮已经作废,调用方不能再去「开新段继续写」。
|
|
45
|
+
*/
|
|
46
|
+
canceled?: boolean;
|
|
47
|
+
/**
|
|
48
|
+
* true = 选择题卡片根本没发出去(飞书接口报错/读超时)。
|
|
49
|
+
* 绝不能当成「用户没选」:用户根本没看到这道题。
|
|
50
|
+
*/
|
|
51
|
+
sendFailed?: boolean;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
/** 图上已经答完的旧问题,附到下一张选择题卡顶部,别让答过的内容凭空消失 */
|
|
55
|
+
export type AskHistoryEntry = {
|
|
56
|
+
question: string;
|
|
57
|
+
chosen?: string;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
type AskRecord = {
|
|
61
|
+
askId: string;
|
|
62
|
+
key: string;
|
|
63
|
+
questions: AskQuestion[];
|
|
64
|
+
answers: (string | undefined)[];
|
|
65
|
+
resolve: (outcome: AskOutcome) => void;
|
|
66
|
+
/** 提问卡片的消息 ID;取消后原地刷新同一张卡时用 */
|
|
67
|
+
cardMessageId?: string;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
/** 提问的终态:答完 / 超时 / 被取消 */
|
|
71
|
+
export type AskSettleStatus = "done" | "timeout" | "canceled";
|
|
72
|
+
|
|
73
|
+
/** 已结算的提问记录,用于给「迟到的点击」一个明确答复 */
|
|
74
|
+
type SettledAsk = { record: AskRecord; status: AskSettleStatus };
|
|
75
|
+
|
|
76
|
+
// 选择题**不设自动超时**:卡片一直停在「等待选择」,直到用户点选 / 自由输入,
|
|
77
|
+
// 或被主动取消(停止按钮、被新消息打断、卡片发送失败)。
|
|
78
|
+
// 用户没作答时绝不替他定默认值——宁可整轮停在那里等他点。
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 已结算记录的保留时长。
|
|
82
|
+
* 结算后用户往往还会再点几下,这段时间内必须还能回答他「这个提问已经结束了」,
|
|
83
|
+
* 否则卡片上的按钮看起来能用、点下去却毫无反应(僵尸卡片)。
|
|
84
|
+
*/
|
|
85
|
+
const SETTLED_TTL_MS = 30 * 60 * 1000;
|
|
86
|
+
/** 按钮上文字的最大长度(飞书 plain_text 有长度限制) */
|
|
87
|
+
const BUTTON_LABEL_MAX = 20;
|
|
88
|
+
/** 自由输入答案的最大长度,防止误粘贴超长文本把卡片撞坏 */
|
|
89
|
+
const CUSTOM_ANSWER_MAX = 200;
|
|
90
|
+
|
|
91
|
+
const pendingAsks = new Map<string, AskRecord>();
|
|
92
|
+
const settledAsks = new Map<string, SettledAsk>();
|
|
93
|
+
|
|
94
|
+
/** 登记一次已结算的提问,并安排过期回收(定时器不拖住进程退出) */
|
|
95
|
+
function rememberSettled(record: AskRecord, status: AskSettleStatus) {
|
|
96
|
+
settledAsks.set(record.askId, { record, status });
|
|
97
|
+
const timer = setTimeout(() => settledAsks.delete(record.askId), SETTLED_TTL_MS);
|
|
98
|
+
timer.unref?.();
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** 表单容器里输入框的 name;回调的 form_value 用它取值,必须与渲染时一致 */
|
|
102
|
+
export function askInputName(questionIndex: number) {
|
|
103
|
+
return `ask_input_${questionIndex}`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 答案不在选项里 = 用户自己敲的(自由输入) */
|
|
107
|
+
function isCustomAnswer(question: AskQuestion, chosen: string) {
|
|
108
|
+
return !question.options.some((option) => option.label === chosen);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** 按子问题字母序号(A/B/C…),与卡片正文里列的编号一致 */
|
|
112
|
+
function optionLetter(index: number) {
|
|
113
|
+
return String.fromCharCode(65 + index);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function truncateLabel(label: string) {
|
|
117
|
+
const text = label.trim();
|
|
118
|
+
return text.length > BUTTON_LABEL_MAX ? `${text.slice(0, BUTTON_LABEL_MAX - 1)}…` : text;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** 一张选择题卡上最多展示几条已答记录(编号仍按真实序号,不跳号) */
|
|
122
|
+
const HISTORY_MAX = 4;
|
|
123
|
+
|
|
124
|
+
export function buildAskCard(
|
|
125
|
+
askId: string,
|
|
126
|
+
questions: AskQuestion[],
|
|
127
|
+
answers: (string | undefined)[],
|
|
128
|
+
status: "pending" | "done" | "timeout" | "canceled" = "pending",
|
|
129
|
+
history: AskHistoryEntry[] = [],
|
|
130
|
+
) {
|
|
131
|
+
const elements: any[] = [];
|
|
132
|
+
|
|
133
|
+
// 同一轮里第 2 次提问会复用同一张卡:已答的旧问题单独成块列在上面,
|
|
134
|
+
// 新问题接着旧编号往下编(否则第 2 题又写成「1.」,看起来像顺序错乱)
|
|
135
|
+
if (history.length) {
|
|
136
|
+
const shown = history.slice(-HISTORY_MAX);
|
|
137
|
+
const offset = history.length - shown.length;
|
|
138
|
+
const lines = shown.map(
|
|
139
|
+
(entry, index) => `${offset + index + 1}. ${entry.question} → ${entry.chosen ?? "(未选)"}`,
|
|
140
|
+
);
|
|
141
|
+
elements.push({ tag: "markdown", content: `**已答:**\n${lines.join("\n")}` });
|
|
142
|
+
elements.push({ tag: "hr" });
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
questions.forEach((question, questionIndex) => {
|
|
146
|
+
const chosen = answers[questionIndex];
|
|
147
|
+
// 展示编号接着已答记录往下数;按钮回调用的是 questionIndex(0 基),与展示无关
|
|
148
|
+
const displayNumber = history.length + questionIndex + 1;
|
|
149
|
+
const lines: string[] = [`**${displayNumber}. ${question.question}**`];
|
|
150
|
+
question.options.forEach((option, optionIndex) => {
|
|
151
|
+
const desc = option.description ? ` — ${option.description}` : "";
|
|
152
|
+
const mark = chosen === option.label ? " ✅" : "";
|
|
153
|
+
lines.push(`${optionLetter(optionIndex)}. ${option.label}${desc}${mark}`);
|
|
154
|
+
});
|
|
155
|
+
// 自由输入的答案不在选项列表里,单独标一行,否则用户看不出自己答了什么
|
|
156
|
+
if (chosen && isCustomAnswer(question, chosen)) {
|
|
157
|
+
lines.push(`✏️ 你的输入:${chosen}`);
|
|
158
|
+
}
|
|
159
|
+
elements.push({ tag: "markdown", content: lines.join("\n") });
|
|
160
|
+
|
|
161
|
+
// 已经答过的问题不再给按钮和输入框,避免重复提交
|
|
162
|
+
if (chosen) return;
|
|
163
|
+
elements.push({
|
|
164
|
+
tag: "action",
|
|
165
|
+
actions: question.options.slice(0, 4).map((option) => ({
|
|
166
|
+
tag: "button",
|
|
167
|
+
text: { tag: "plain_text", content: truncateLabel(`${optionLetter(question.options.indexOf(option))}. ${option.label}`) },
|
|
168
|
+
type: "default",
|
|
169
|
+
value: {
|
|
170
|
+
action: "pi_feishu_ask_answer",
|
|
171
|
+
askId,
|
|
172
|
+
questionIndex,
|
|
173
|
+
label: option.label,
|
|
174
|
+
},
|
|
175
|
+
})),
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
// 自由输入:表单容器 + 输入框 + 提交按钮。
|
|
179
|
+
// 飞书规定表单内交互组件必须带全局唯一的 name,且容器内至少要有一个 submit 按钮;
|
|
180
|
+
// 提交回调的 action.tag 仍是 button,值在 action.form_value 里。
|
|
181
|
+
elements.push({
|
|
182
|
+
tag: "form",
|
|
183
|
+
name: `ask_form_${questionIndex}`,
|
|
184
|
+
elements: [
|
|
185
|
+
{
|
|
186
|
+
tag: "input",
|
|
187
|
+
name: askInputName(questionIndex),
|
|
188
|
+
placeholder: { tag: "plain_text", content: "选项都不合适?在这里自己输入,再点「提交输入」" },
|
|
189
|
+
},
|
|
190
|
+
{
|
|
191
|
+
tag: "button",
|
|
192
|
+
// 飞书要求 form 容器内的**每个**交互组件都带 name(含提交按钮),
|
|
193
|
+
// 缺了会整张卡片被拒:230099 / 200530 "the interactive element in the form container must have a name"
|
|
194
|
+
name: `ask_submit_${questionIndex}`,
|
|
195
|
+
text: { tag: "plain_text", content: "提交输入" },
|
|
196
|
+
type: "primary",
|
|
197
|
+
action_type: "form_submit",
|
|
198
|
+
value: {
|
|
199
|
+
action: "pi_feishu_ask_input",
|
|
200
|
+
askId,
|
|
201
|
+
questionIndex,
|
|
202
|
+
},
|
|
203
|
+
},
|
|
204
|
+
],
|
|
205
|
+
});
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
const answeredCount = answers.filter(Boolean).length;
|
|
209
|
+
const footer = status === "done"
|
|
210
|
+
? `✅ 已全部作答(${answeredCount}/${questions.length})`
|
|
211
|
+
: status === "timeout"
|
|
212
|
+
? `⌛ 等待超时,已作答 ${answeredCount}/${questions.length}`
|
|
213
|
+
: status === "canceled"
|
|
214
|
+
? `⚠️ 提问已结束,已作答 ${answeredCount}/${questions.length}`
|
|
215
|
+
: `等待选择(${answeredCount}/${questions.length})`;
|
|
216
|
+
elements.push({ tag: "markdown", content: footer });
|
|
217
|
+
|
|
218
|
+
return {
|
|
219
|
+
config: { wide_screen_mode: true, update_multi: true },
|
|
220
|
+
header: {
|
|
221
|
+
template: status === "done" ? "green" : status === "pending" ? "turquoise" : "grey",
|
|
222
|
+
title: {
|
|
223
|
+
tag: "plain_text",
|
|
224
|
+
content: status === "done"
|
|
225
|
+
? "已选择"
|
|
226
|
+
: status === "timeout"
|
|
227
|
+
? "选择超时"
|
|
228
|
+
: status === "canceled"
|
|
229
|
+
? "已结束"
|
|
230
|
+
: "请选择",
|
|
231
|
+
},
|
|
232
|
+
},
|
|
233
|
+
elements,
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* 登记一次提问,返回 askId。
|
|
239
|
+
*
|
|
240
|
+
* 这里**不挂任何定时器**:提问只有三种收场方式——全部答完、被主动取消、卡片发送失败。
|
|
241
|
+
* 没有「等太久自动按未作答结算」这条路:用户还没点,模型就不许往下走。
|
|
242
|
+
*/
|
|
243
|
+
export function registerAsk(
|
|
244
|
+
key: string,
|
|
245
|
+
questions: AskQuestion[],
|
|
246
|
+
resolve: (outcome: AskOutcome) => void,
|
|
247
|
+
): AskRecord {
|
|
248
|
+
const askId = `ask_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
|
|
249
|
+
const record: AskRecord = {
|
|
250
|
+
askId,
|
|
251
|
+
key,
|
|
252
|
+
questions,
|
|
253
|
+
answers: questions.map(() => undefined),
|
|
254
|
+
resolve,
|
|
255
|
+
};
|
|
256
|
+
pendingAsks.set(askId, record);
|
|
257
|
+
return record;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export function getAsk(askId: string): AskRecord | undefined {
|
|
261
|
+
return pendingAsks.get(askId);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** 由发送方回填卡片消息 ID,超时刷新卡片时需要它 */
|
|
265
|
+
export function setAskCardMessage(askId: string, messageId: string) {
|
|
266
|
+
const record = pendingAsks.get(askId);
|
|
267
|
+
if (record) record.cardMessageId = messageId;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export type AskAnswerResult = {
|
|
271
|
+
found: boolean;
|
|
272
|
+
/** 本次是否让该问题从「未答」变成「已答」 */
|
|
273
|
+
accepted: boolean;
|
|
274
|
+
allAnswered: boolean;
|
|
275
|
+
/** true = 该提问已结算(答完 / 超时 / 取消),本次点击不生效 */
|
|
276
|
+
settled?: boolean;
|
|
277
|
+
/** 已结算时的终态 */
|
|
278
|
+
settledStatus?: AskSettleStatus;
|
|
279
|
+
record?: AskRecord;
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
/** 记录一次按钮点击;返回是否已全部答完 */
|
|
283
|
+
export function answerAsk(
|
|
284
|
+
askId: string,
|
|
285
|
+
questionIndex: number,
|
|
286
|
+
label: string,
|
|
287
|
+
allowCustom = false,
|
|
288
|
+
): AskAnswerResult {
|
|
289
|
+
const record = pendingAsks.get(askId);
|
|
290
|
+
if (!record) {
|
|
291
|
+
// 没有待答记录有两种可能:这个 askId 从来不存在(伪造回调),或者它已经结算了。
|
|
292
|
+
// 后者必须回一个明确的终态,否则调用方只能静默丢弃,用户看到的是「点了没反应」。
|
|
293
|
+
const settled = settledAsks.get(askId);
|
|
294
|
+
if (!settled) return { found: false, accepted: false, allAnswered: false };
|
|
295
|
+
return {
|
|
296
|
+
found: true,
|
|
297
|
+
accepted: false,
|
|
298
|
+
allAnswered: false,
|
|
299
|
+
settled: true,
|
|
300
|
+
settledStatus: settled.status,
|
|
301
|
+
record: settled.record,
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
const question = record.questions[questionIndex];
|
|
305
|
+
if (!question) return { found: true, accepted: false, allAnswered: false, record };
|
|
306
|
+
// 自由输入的文本不在选项里,只有调用方声明「来自输入框」时才放行;
|
|
307
|
+
// 其余情况仍要求命中选项,防止伪造回调值。
|
|
308
|
+
const value = allowCustom ? label.trim().slice(0, CUSTOM_ANSWER_MAX) : label;
|
|
309
|
+
if (!value) return { found: true, accepted: false, allAnswered: false, record };
|
|
310
|
+
if (!allowCustom && !question.options.some((option) => option.label === value)) {
|
|
311
|
+
return { found: true, accepted: false, allAnswered: false, record };
|
|
312
|
+
}
|
|
313
|
+
const accepted = !record.answers[questionIndex];
|
|
314
|
+
record.answers[questionIndex] = value;
|
|
315
|
+
const allAnswered = record.answers.every(Boolean);
|
|
316
|
+
if (allAnswered) {
|
|
317
|
+
pendingAsks.delete(askId);
|
|
318
|
+
rememberSettled(record, "done");
|
|
319
|
+
debugLog("feishu.ask.answered", { askId, key: record.key, label: value, custom: allowCustom, allAnswered: true });
|
|
320
|
+
record.resolve(toOutcome(record));
|
|
321
|
+
} else {
|
|
322
|
+
debugLog("feishu.ask.partial", {
|
|
323
|
+
askId,
|
|
324
|
+
key: record.key,
|
|
325
|
+
questionIndex,
|
|
326
|
+
label: value,
|
|
327
|
+
custom: allowCustom,
|
|
328
|
+
answered: record.answers.filter(Boolean).length,
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
return { found: true, accepted, allAnswered, record };
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** 主动结束一次提问(例如整轮被停止);未作答项保持 undefined */
|
|
335
|
+
export function cancelAsk(askId: string, timedOut = false) {
|
|
336
|
+
const record = pendingAsks.get(askId);
|
|
337
|
+
if (!record) return;
|
|
338
|
+
pendingAsks.delete(askId);
|
|
339
|
+
rememberSettled(record, timedOut ? "timeout" : "canceled");
|
|
340
|
+
record.resolve(toOutcome(record, timedOut ? { timedOut: true } : { canceled: true }));
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* 提问卡片发送失败。
|
|
345
|
+
*
|
|
346
|
+
* 与 cancelAsk 的区别很重要:cancelAsk 是「用户没来得及答」,这里是「用户压根没收到」。
|
|
347
|
+
* 不分开的话模型会把「未选择」当成用户的决定,接着按默认值往下答(表现为「秒超时」)。
|
|
348
|
+
*/
|
|
349
|
+
export function failAsk(askId: string) {
|
|
350
|
+
const record = pendingAsks.get(askId);
|
|
351
|
+
if (!record) return;
|
|
352
|
+
pendingAsks.delete(askId);
|
|
353
|
+
rememberSettled(record, "canceled");
|
|
354
|
+
record.resolve(toOutcome(record, { sendFailed: true }));
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* 取消某个会话里所有待答提问(停止按钮 / 被新消息打断)。
|
|
359
|
+
* 返回被取消的记录(含 cardMessageId),调用方拿它把卡片刷成「提问已结束」。
|
|
360
|
+
*
|
|
361
|
+
* 为什么要主动取消:`session.abort()` 不会解除 `feishu_ask` 的等待,而选择题又不再自动超时,
|
|
362
|
+
* 不主动取消那个 Promise 就会一直挂着,整轮永远收不干净。
|
|
363
|
+
*/
|
|
364
|
+
export function cancelAskBySession(key: string, timedOut = false): AskRecord[] {
|
|
365
|
+
const canceled: AskRecord[] = [];
|
|
366
|
+
for (const [askId, record] of [...pendingAsks]) {
|
|
367
|
+
if (record.key !== key) continue;
|
|
368
|
+
cancelAsk(askId, timedOut);
|
|
369
|
+
canceled.push(record);
|
|
370
|
+
}
|
|
371
|
+
return canceled;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function toOutcome(
|
|
375
|
+
record: AskRecord,
|
|
376
|
+
flags: { timedOut?: boolean; canceled?: boolean; sendFailed?: boolean } = {},
|
|
377
|
+
): AskOutcome {
|
|
378
|
+
return {
|
|
379
|
+
timedOut: Boolean(flags.timedOut),
|
|
380
|
+
...(flags.canceled ? { canceled: true } : {}),
|
|
381
|
+
...(flags.sendFailed ? { sendFailed: true } : {}),
|
|
382
|
+
answers: record.questions.map((question, index) => ({
|
|
383
|
+
header: question.header,
|
|
384
|
+
question: question.question,
|
|
385
|
+
chosen: record.answers[index],
|
|
386
|
+
})),
|
|
387
|
+
};
|
|
388
|
+
}
|