@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.
Files changed (52) hide show
  1. package/.pi/extensions/feishu/index.ts +11 -0
  2. package/.pi/feishu/debug.pi.log +81 -0
  3. package/.pi/feishu/state.pi.json +12 -0
  4. package/README.md +210 -2
  5. package/package.json +57 -4
  6. package/src/adapters/pi/PiConversationRuntime.ts +1559 -0
  7. package/src/adapters/pi/index.ts +1169 -0
  8. package/src/adapters/pi/setup.ts +108 -0
  9. package/src/feishu/app-register.ts +50 -0
  10. package/src/feishu/ask.ts +388 -0
  11. package/src/feishu/attachment-processor.ts +198 -0
  12. package/src/feishu/attachments.ts +192 -0
  13. package/src/feishu/bridge-runtime.ts +129 -0
  14. package/src/feishu/bridge-store.ts +92 -0
  15. package/src/feishu/card-action-webhook.ts +141 -0
  16. package/src/feishu/card-actions.ts +241 -0
  17. package/src/feishu/card-builder.ts +277 -0
  18. package/src/feishu/cardkit-stream.ts +483 -0
  19. package/src/feishu/cards.ts +413 -0
  20. package/src/feishu/config.ts +427 -0
  21. package/src/feishu/daemon-spec.ts +43 -0
  22. package/src/feishu/debug.ts +51 -0
  23. package/src/feishu/dedupe-store.ts +150 -0
  24. package/src/feishu/delivery.ts +185 -0
  25. package/src/feishu/gateway-lock.ts +256 -0
  26. package/src/feishu/group-trigger.ts +128 -0
  27. package/src/feishu/image-send.ts +256 -0
  28. package/src/feishu/instance.ts +170 -0
  29. package/src/feishu/instances.ts +148 -0
  30. package/src/feishu/interactive-card.ts +236 -0
  31. package/src/feishu/learn-approval.ts +321 -0
  32. package/src/feishu/live-cards.ts +128 -0
  33. package/src/feishu/message-handler.ts +512 -0
  34. package/src/feishu/messages.ts +356 -0
  35. package/src/feishu/oversize-progress-card.ts +101 -0
  36. package/src/feishu/progress-channel.ts +154 -0
  37. package/src/feishu/progress-note.ts +371 -0
  38. package/src/feishu/prompt-timeout.ts +81 -0
  39. package/src/feishu/reply-card-options.ts +73 -0
  40. package/src/feishu/reply-card.ts +498 -0
  41. package/src/feishu/restart.ts +286 -0
  42. package/src/feishu/retry.ts +102 -0
  43. package/src/feishu/rich-text.ts +387 -0
  44. package/src/feishu/runtime-config.ts +286 -0
  45. package/src/feishu/runtime.ts +110 -0
  46. package/src/feishu/slash-commands.ts +239 -0
  47. package/src/feishu/thinking.ts +24 -0
  48. package/src/feishu/transport.ts +792 -0
  49. package/src/feishu/types.ts +183 -0
  50. package/src/feishu/ui-notify.ts +44 -0
  51. package/src/feishu/user-name.ts +121 -0
  52. package/src/feishu/workspace.ts +42 -0
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Agent Runtime 解耦层:
3
+ * 飞书公共代码只依赖本文件的 ConversationRuntime 接口与公共类型,
4
+ * 只服务 Pi 一个 Agent Runtime(本仓不做多 Agent 适配)。
5
+ * Pi 的具体实现位于 src/adapters/pi/ 下。
6
+ */
7
+ import type { FeishuImageInput } from "./attachments.ts";
8
+ import type { ResumeScope, ResumeSessionPage } from "./cards.ts";
9
+ import type { ReplyCardSink } from "./reply-card.ts";
10
+ import type { ThinkingStatus } from "./thinking.ts";
11
+
12
+ /** 平台无关的模型信息(由各 Runtime 转换而来,禁止原生 Model 对象泄漏到飞书层)。 */
13
+ export type RuntimeModel = {
14
+ provider: string;
15
+ id: string;
16
+ name?: string;
17
+ /** 该模型是否支持图片输入 */
18
+ supportsImage?: boolean;
19
+ };
20
+
21
+ /** 会话运行状态(/status 命令使用)。 */
22
+ export type ConversationStatus = {
23
+ cwd: string;
24
+ hasActiveRun: boolean;
25
+ activeStopped: boolean;
26
+ };
27
+
28
+ /** 上下文占用信息(/status 命令使用)。 */
29
+ export type ContextUsage = {
30
+ tokens: number | null;
31
+ contextWindow: number | null;
32
+ percent: number | null;
33
+ };
34
+
35
+ export type StopConversationResult =
36
+ | {
37
+ status: "stopped";
38
+ message: string;
39
+ body: string;
40
+ /** 停止时的过程清单;卡片回调要把同样的内容放回响应卡,否则清单会被刷没 */
41
+ progress?: string;
42
+ }
43
+ | { status: "not_running"; message: string }
44
+ | { status: "stale"; message: string }
45
+ | { status: "failed"; message: string };
46
+
47
+ export type ConversationTimeouts = {
48
+ /** Seconds before a long-running turn sends a non-fatal notice (0 disables). */
49
+ promptNotifySec?: number;
50
+ /** Hard prompt timeout in seconds; 0 waits indefinitely. */
51
+ promptTimeoutSec?: number;
52
+ };
53
+
54
+ /**
55
+ * 飞书消息处理器与卡片回调依赖的 Runtime 能力面。
56
+ * 一个飞书会话 key 对应一个 Runtime 内部会话;
57
+ * key 之外的内部状态(会话句柄、模型、工作区)由实现自行管理。
58
+ */
59
+ export interface ConversationRuntime {
60
+ prompt(
61
+ key: string,
62
+ userText: string,
63
+ onReply: (text: string) => Promise<void>,
64
+ onDelta?: (delta: string) => void,
65
+ ): Promise<void>;
66
+
67
+ promptWithImages(
68
+ key: string,
69
+ userText: string,
70
+ images: FeishuImageInput[],
71
+ onReply: (text: string) => Promise<void>,
72
+ status?: ReplyCardSink,
73
+ onDelta?: (delta: string) => void,
74
+ ): Promise<void>;
75
+
76
+ /** 供 /status 使用 */
77
+ getStatus(key: string): ConversationStatus;
78
+
79
+ getActualModel(key: string): Promise<string>;
80
+
81
+ getThinkingStatus(key: string): Promise<ThinkingStatus>;
82
+
83
+ getContextStatus(key: string): Promise<ContextUsage | null>;
84
+
85
+ stopConversation(key: string, onReply: (text: string) => Promise<void>, runId?: string): Promise<StopConversationResult>;
86
+
87
+ newConversation(key: string, onReply: (text: string) => Promise<void>): Promise<void>;
88
+
89
+ listResumeSessions(key: string, scope: ResumeScope, page: number): Promise<ResumeSessionPage>;
90
+
91
+ /**
92
+ * 切换到历史会话。sessionRef 是不透明引用(来自 listResumeSessions 的 item.path),
93
+ * 具体含义(Pi 会话文件路径)由实现解释。
94
+ */
95
+ resumeConversation(key: string, sessionRef: string, onReply: (text: string) => Promise<void>): Promise<void>;
96
+
97
+ selectModel(key: string, provider: string, modelId: string, onReply: (text: string) => Promise<void>): Promise<void>;
98
+
99
+ selectThinkingLevel(key: string, level: string, onReply: (text: string) => Promise<void>): Promise<void>;
100
+
101
+ getWorkspace(key: string): string;
102
+
103
+ switchWorkspace(key: string, workspaceInput: string | undefined, onReply: (text: string) => Promise<void>): Promise<void>;
104
+
105
+ getAvailableModels(): Promise<RuntimeModel[]>;
106
+
107
+ getSelectedModel(key: string): Promise<RuntimeModel | undefined>;
108
+
109
+ resetMemory(): void;
110
+ }
@@ -0,0 +1,239 @@
1
+ /**
2
+ * 飞书「斜杠指令」(Slash Command)注册。
3
+ *
4
+ * 作用:把桥接已支持的命令注册到飞书开放平台,用户在聊天输入框敲 `/`
5
+ * 即可看到指令提示面板(命令文本会留在输入框,可继续补参数再发送)。
6
+ *
7
+ * 官方接口:/open-apis/application/v7/app_slash_commands(需 tenant_access_token)
8
+ * 所需权限:application:app_slash_command:write(读列表用 read / write 均可)
9
+ *
10
+ * 设计要点:
11
+ * - 幂等:先查列表,缺的 POST,描述有变化才 PATCH,其余跳过。
12
+ * - 静默降级:权限缺失、应用未发布、平台报错时只写调试日志,绝不抛出,
13
+ * 以免影响扫码建应用 / 桥接启动主流程。
14
+ * - 客户端有缓存(注册约 5 分钟 + 客户端缓存约 3 分钟),失败后无需反复重试。
15
+ */
16
+ import { debugLog } from "./debug.ts";
17
+ import type { FeishuConfig } from "./types.ts";
18
+
19
+ /** 单条指令定义:command 不含前导斜杠 */
20
+ export type SlashCommandSpec = {
21
+ /** 指令名(不含 `/`),须与 parseBotCommand 识别的名字一致 */
22
+ command: string;
23
+ /** 中文描述(description.default_value 与 i18n.zh_cn) */
24
+ zh: string;
25
+ /** 英文描述(i18n.en_us) */
26
+ en: string;
27
+ };
28
+
29
+ /**
30
+ * 与 messages.ts 的 parseBotCommand / getCommandList 保持一致的指令清单。
31
+ * 注意:不传 icon(icon_key 取值受平台约束,传错会触发参数校验失败)。
32
+ */
33
+ export const FEISHU_SLASH_COMMANDS: SlashCommandSpec[] = [
34
+ { command: "new", zh: "新建会话", en: "Start a new conversation" },
35
+ { command: "resume", zh: "恢复历史会话", en: "Resume a previous conversation" },
36
+ { command: "model", zh: "切换模型", en: "Switch model" },
37
+ { command: "thinking", zh: "调整思考强度", en: "Adjust thinking level" },
38
+ { command: "workspace", zh: "切换工作区(后接绝对路径)", en: "Switch workspace (absolute path)" },
39
+ { command: "status", zh: "查看会话状态", en: "Show session status" },
40
+ { command: "stop", zh: "停止当前生成", en: "Stop the current reply" },
41
+ { command: "config", zh: "查看或修改运行时配置(仅私聊)", en: "View or update runtime config (private chat only)" },
42
+ { command: "commands", zh: "显示全部命令", en: "List all commands" },
43
+ { command: "restart", zh: "重启桥接进程并加载最新代码(保留会话上下文)", en: "Restart the bridge and reload code (session kept)" },
44
+ // interrupt 模式为 Pi 侧实现
45
+ { command: "delivery", zh: "设置「正在生成时又收到新消息」怎么处理(排队 / 立即打断,仅私聊)", en: "How to handle new messages while replying (queue / interrupt, DM only)" },
46
+ // --- 由 Pi 侧扩展(knowledge-flow)注册的命令 ---
47
+ // 面板的作用是「提示用户有哪些命令可用」:飞书斜杠指令点击后只是把命令文本
48
+ // 插进输入框(不会自动执行),用户补完参数再发送。所以这里保留全部命令,
49
+ // 与实际是否派发无关(派发策略见 PiConversationRuntime 的 DISPATCHED_SLASH_COMMANDS)。
50
+ // 注意:command 必须匹配 ^[a-z][a-z0-9_-]{0,31}$(实测 code 40000000),
51
+ // 所以 Pi 侧的中文命令名(如原先的 /学习)无法注册,统一改用英文名 /learn。
52
+ { command: "req", zh: "需求流程:/req [新 <名称>|开发|测试|bug|归档|状态] [需求ID]", en: "Requirement flow: /req [new|dev|test|bug|archive|status]" },
53
+ { command: "kb", zh: "知识库:/kb [查|梳理|新模块|新功能|同步|巡检]", en: "Knowledge base: /kb [find|outline|new-module|new-feature|sync|audit]" },
54
+ { command: "test", zh: "测试域:/test [新用例|缺口|同步|查|状态]", en: "Test domain: /test [new-case|gaps|sync|find|status]" },
55
+ { command: "learn", zh: "学习:把反馈落成 .pi/ 下的规范改动(无参数则复盘本会话)", en: "Learn: turn feedback into .pi spec changes (no args = review this session)" },
56
+ { command: "deploy-test", zh: "测试环境部署:/deploy-test [端名],端名如 rust_server / quasar / quasar_h5", en: "Deploy test env: /deploy-test [target]" },
57
+ ];
58
+
59
+ const API_PATH = "/open-apis/application/v7/app_slash_commands";
60
+ /** 单次同步最多翻页次数,防止异常分页导致死循环 */
61
+ const MAX_PAGES = 10;
62
+ const PAGE_SIZE = 100;
63
+
64
+ /** 同一进程内只自动同步一次,避免热重连时反复调接口 */
65
+ let autoSyncDone = false;
66
+
67
+ export type SyncSlashCommandsResult = {
68
+ ok: boolean;
69
+ created: string[];
70
+ updated: string[];
71
+ skipped: string[];
72
+ /** ok=false 时的可读原因(权限不足 / 应用未发布 / 网络错误等) */
73
+ reason?: string;
74
+ };
75
+
76
+ type ApiResponse = {
77
+ code?: number;
78
+ msg?: string;
79
+ data?: {
80
+ items?: Array<{
81
+ command_id?: string;
82
+ command?: string;
83
+ description?: CommandDescription;
84
+ }>;
85
+ page_token?: string;
86
+ has_more?: boolean;
87
+ };
88
+ };
89
+
90
+ type CommandDescription = {
91
+ default_value?: string;
92
+ i18n?: Record<string, string>;
93
+ };
94
+
95
+ /** 平台返回 code !== 0 时统一转成可读错误 */
96
+ function assertOk(res: ApiResponse, action: string) {
97
+ if (res && typeof res.code === "number" && res.code !== 0) {
98
+ throw new Error(`${action} failed: code=${res.code} msg=${res.msg || ""}`);
99
+ }
100
+ }
101
+
102
+ function buildDescription(spec: SlashCommandSpec, language: "zh" | "en"): CommandDescription {
103
+ return {
104
+ default_value: language === "en" ? spec.en : spec.zh,
105
+ i18n: { zh_cn: spec.zh, en_us: spec.en },
106
+ };
107
+ }
108
+
109
+ /** 已注册描述与目标描述是否一致(不一致才 PATCH) */
110
+ function descriptionMatches(existing: CommandDescription | undefined, target: CommandDescription) {
111
+ if (!existing) return false;
112
+ if ((existing.default_value || "") !== (target.default_value || "")) return false;
113
+ const existingI18n = existing.i18n || {};
114
+ const targetI18n = target.i18n || {};
115
+ return (existingI18n.zh_cn || "") === (targetI18n.zh_cn || "")
116
+ && (existingI18n.en_us || "") === (targetI18n.en_us || "");
117
+ }
118
+
119
+ /** 拉取当前应用已注册的全部指令,返回 command -> 记录 的映射 */
120
+ async function listExistingCommands(client: any): Promise<Map<string, { commandId: string; description?: CommandDescription }>> {
121
+ const found = new Map<string, { commandId: string; description?: CommandDescription }>();
122
+ let pageToken: string | undefined;
123
+
124
+ for (let page = 0; page < MAX_PAGES; page += 1) {
125
+ const params: Record<string, string> = { page_size: String(PAGE_SIZE) };
126
+ if (pageToken) params.page_token = pageToken;
127
+ const res: ApiResponse = await client.request({ url: API_PATH, method: "GET", params });
128
+ assertOk(res, "list slash commands");
129
+
130
+ for (const item of res?.data?.items || []) {
131
+ if (!item?.command) continue;
132
+ found.set(String(item.command), {
133
+ commandId: String(item.command_id || ""),
134
+ description: item.description,
135
+ });
136
+ }
137
+
138
+ pageToken = res?.data?.page_token;
139
+ if (!res?.data?.has_more || !pageToken) break;
140
+ }
141
+
142
+ return found;
143
+ }
144
+
145
+ /**
146
+ * 同步斜杠指令到飞书平台(幂等)。
147
+ * 调用方应当 fire-and-forget,并自行 catch;本函数内部也会兜住异常。
148
+ */
149
+ export async function syncSlashCommands(
150
+ client: any,
151
+ config: FeishuConfig,
152
+ options?: { commands?: SlashCommandSpec[] },
153
+ ): Promise<SyncSlashCommandsResult> {
154
+ const specs = options?.commands || FEISHU_SLASH_COMMANDS;
155
+ const language: "zh" | "en" = config?.language === "en" ? "en" : "zh";
156
+ const result: SyncSlashCommandsResult = { ok: false, created: [], updated: [], skipped: [] };
157
+
158
+ if (!client || typeof client.request !== "function") {
159
+ result.reason = "lark client unavailable";
160
+ debugLog("feishu.slash.skipped", { reason: result.reason });
161
+ return result;
162
+ }
163
+
164
+ try {
165
+ const existing = await listExistingCommands(client);
166
+ debugLog("feishu.slash.remote_list", { count: existing.size, commands: [...existing.keys()] });
167
+
168
+ for (const spec of specs) {
169
+ const target = buildDescription(spec, language);
170
+ const current = existing.get(spec.command);
171
+
172
+ if (!current) {
173
+ const res: ApiResponse = await client.request({
174
+ url: API_PATH,
175
+ method: "POST",
176
+ data: { command: spec.command, description: target },
177
+ });
178
+ assertOk(res, `create ${spec.command}`);
179
+ result.created.push(spec.command);
180
+ debugLog("feishu.slash.created", { command: spec.command });
181
+ continue;
182
+ }
183
+
184
+ if (!current.commandId) {
185
+ result.skipped.push(spec.command);
186
+ continue;
187
+ }
188
+
189
+ if (descriptionMatches(current.description, target)) {
190
+ result.skipped.push(spec.command);
191
+ continue;
192
+ }
193
+
194
+ const res: ApiResponse = await client.request({
195
+ url: `${API_PATH}/${current.commandId}`,
196
+ method: "PATCH",
197
+ data: { description: target },
198
+ });
199
+ assertOk(res, `update ${spec.command}`);
200
+ result.updated.push(spec.command);
201
+ debugLog("feishu.slash.updated", { command: spec.command, commandId: current.commandId });
202
+ }
203
+
204
+ result.ok = true;
205
+ debugLog("feishu.slash.synced", {
206
+ created: result.created,
207
+ updated: result.updated,
208
+ skipped: result.skipped,
209
+ });
210
+ return result;
211
+ } catch (error) {
212
+ const message = error instanceof Error ? error.message : String(error);
213
+ result.reason = message;
214
+ // 典型原因:应用未开通 application:app_slash_command:write,或应用未发布。
215
+ result.ok = false;
216
+ debugLog("feishu.slash.sync_failed", {
217
+ error: message,
218
+ hint: "需要在飞书开发者后台为应用开通 application:app_slash_command:write 权限并发布版本",
219
+ });
220
+ return result;
221
+ }
222
+ }
223
+
224
+ /**
225
+ * 桥接启动时调用一次:后台同步,不阻塞 WS 建连。
226
+ * 失败只记日志,可通过 /feishu debug 查看。
227
+ */
228
+ export function autoSyncSlashCommands(client: any, config: FeishuConfig) {
229
+ if (autoSyncDone) return;
230
+ autoSyncDone = true;
231
+ void syncSlashCommands(client, config).catch(() => {
232
+ // syncSlashCommands 内部已兜住异常,这里只是双保险
233
+ });
234
+ }
235
+
236
+ /** 单测/热重载场景下重置自动同步标记 */
237
+ export function resetSlashAutoSyncFlag() {
238
+ autoSyncDone = false;
239
+ }
@@ -0,0 +1,24 @@
1
+ export type ThinkingStatus = {
2
+ /** Runtime 当前会话返回的原始值;不做翻译或归一化。 */
3
+ currentLevel?: string;
4
+ /** Runtime 当前模型返回的原始可选值,顺序保持不变。 */
5
+ availableLevels: string[];
6
+ /** Runtime 是否提供了可用档位列表。没有就不能安全地猜测或展示。 */
7
+ available: boolean;
8
+ };
9
+
10
+ /**
11
+ * 只做结构清理:保留 Runtime 返回的每个非空字符串,不维护任何固定档位名单。
12
+ * 这样模型或 Runtime 新增档位时,飞书无需同步发布也不会漏掉它。
13
+ */
14
+ export function normalizeThinkingLevels(value: unknown): string[] {
15
+ if (!Array.isArray(value)) return [];
16
+ const seen = new Set<string>();
17
+ const levels: string[] = [];
18
+ for (const item of value) {
19
+ if (typeof item !== "string" || !item.trim() || seen.has(item)) continue;
20
+ seen.add(item);
21
+ levels.push(item);
22
+ }
23
+ return levels;
24
+ }