@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,413 @@
1
+ import { type ThinkingStatus } from "./thinking.ts";
2
+ import type { RuntimeModel } from "./runtime.ts";
3
+
4
+ export function modelLabel(model: RuntimeModel | undefined) {
5
+ if (!model) return "未选择";
6
+ return `${model.provider}/${model.id}`;
7
+ }
8
+
9
+ export type ResumeScope = "current" | "all";
10
+
11
+ export type ResumeSessionItem = {
12
+ path: string;
13
+ title: string;
14
+ subtitle: string;
15
+ modifiedLabel: string;
16
+ workspaceLabel?: string;
17
+ isCurrent: boolean;
18
+ };
19
+
20
+ export type ResumeSessionPage = {
21
+ key: string;
22
+ /** 当前飞书会话绑定的工作区;无论浏览哪个范围都用于说明筛选上下文。 */
23
+ workspacePath: string;
24
+ scope: ResumeScope;
25
+ page: number;
26
+ total: number;
27
+ totalPages: number;
28
+ items: ResumeSessionItem[];
29
+ };
30
+
31
+ export function buildModelCard(key: string, models: RuntimeModel[], currentModel: RuntimeModel | undefined) {
32
+ const current = modelLabel(currentModel);
33
+ const elements: any[] = [
34
+ {
35
+ tag: "markdown",
36
+ content: `当前模型:**${current}**\n点击下面的按钮即可切换当前飞书会话使用的模型。`,
37
+ },
38
+ ];
39
+
40
+ const rows: any[][] = [];
41
+ for (let i = 0; i < models.length; i += 2) {
42
+ rows.push(models.slice(i, i + 2));
43
+ }
44
+
45
+ for (const row of rows) {
46
+ elements.push({
47
+ tag: "action",
48
+ actions: row.map((model) => {
49
+ const isCurrent = currentModel?.provider === model.provider && currentModel?.id === model.id;
50
+ return {
51
+ tag: "button",
52
+ text: {
53
+ tag: "plain_text",
54
+ content: `${isCurrent ? "当前 " : ""}${model.provider}/${model.id}`,
55
+ },
56
+ type: isCurrent ? "primary" : "default",
57
+ value: {
58
+ action: "pi_feishu_select_model",
59
+ key,
60
+ provider: model.provider,
61
+ modelId: model.id,
62
+ },
63
+ };
64
+ }),
65
+ });
66
+ }
67
+
68
+ return {
69
+ config: sharedCardConfig(),
70
+ header: {
71
+ template: "blue",
72
+ title: { tag: "plain_text", content: "选择 Pi 模型" },
73
+ },
74
+ elements,
75
+ };
76
+ }
77
+
78
+ export function buildThinkingCard(key: string, currentModel: RuntimeModel | undefined, status: ThinkingStatus) {
79
+ const model = modelLabel(currentModel);
80
+ const elements: any[] = [
81
+ {
82
+ tag: "markdown",
83
+ content: !status.available
84
+ ? `当前模型:**${model}**\n无法读取这个模型可用的 thinking levels,因此未显示任何猜测的选项。`
85
+ : status.availableLevels.length === 0
86
+ ? `当前模型:**${model}**\n当前模型未返回可用的 thinking levels。`
87
+ : `当前模型:**${model}**\nCurrent: **${escapeMarkdown(status.currentLevel || "(unknown)")}**\n以下选项由当前会话直接返回。`,
88
+ },
89
+ ];
90
+
91
+ if (status.available) {
92
+ for (let i = 0; i < status.availableLevels.length; i += 3) {
93
+ const row = status.availableLevels.slice(i, i + 3);
94
+ elements.push({
95
+ tag: "action",
96
+ actions: row.map((level) => {
97
+ const isCurrent = level === status.currentLevel;
98
+ return {
99
+ tag: "button",
100
+ text: {
101
+ tag: "plain_text",
102
+ content: level,
103
+ },
104
+ type: isCurrent ? "primary" : "default",
105
+ value: {
106
+ action: "pi_feishu_select_thinking",
107
+ key,
108
+ level,
109
+ },
110
+ };
111
+ }),
112
+ });
113
+ }
114
+ }
115
+
116
+ return {
117
+ config: sharedCardConfig(),
118
+ header: {
119
+ template: "purple",
120
+ title: { tag: "plain_text", content: "调整思考强度" },
121
+ },
122
+ elements,
123
+ };
124
+ }
125
+
126
+ /**
127
+ * 「消息投递方式」卡片:正在生成回复时又收到新消息,是排队还是立即打断。
128
+ * 这是**全局**运行时配置(runtime-overrides.json),卡片只负责查看与切换。
129
+ */
130
+ export function buildDeliveryCard(current: "queue" | "interrupt" | undefined) {
131
+ const mode: "queue" | "interrupt" = current === "interrupt" ? "interrupt" : "queue";
132
+ const elements: any[] = [
133
+ {
134
+ tag: "markdown",
135
+ content: [
136
+ `当前设置:**${mode === "interrupt" ? "立即打断" : "排队"}**`,
137
+ "",
138
+ mode === "interrupt"
139
+ ? "生成中你发新消息 → 立刻掰掉上一轮,用新消息开新一轮(上一轮已生成的内容留在它自己那张卡上)。"
140
+ : "生成中你发新消息 → 排在上一轮后面,等它跑完再处理。(新消息的卡片会先出现但暂时空白)",
141
+ "",
142
+ "> 这是全局设置,对本地所有飞书会话生效;清除用 `/config clear messageDelivery`。",
143
+ ].join("\n"),
144
+ },
145
+ {
146
+ tag: "action",
147
+ actions: [
148
+ buildDeliveryButton("排队", "queue", mode === "queue"),
149
+ buildDeliveryButton("立即打断", "interrupt", mode === "interrupt"),
150
+ ],
151
+ },
152
+ ];
153
+
154
+ return {
155
+ config: sharedCardConfig(),
156
+ header: {
157
+ template: "orange",
158
+ title: { tag: "plain_text", content: "消息投递方式" },
159
+ },
160
+ elements,
161
+ };
162
+ }
163
+
164
+ function buildDeliveryButton(label: string, mode: "queue" | "interrupt", active: boolean) {
165
+ return {
166
+ tag: "button",
167
+ text: { tag: "plain_text", content: label },
168
+ type: active ? "primary" : "default",
169
+ value: {
170
+ action: "pi_feishu_select_delivery",
171
+ mode,
172
+ },
173
+ };
174
+ }
175
+
176
+ export function parseDeliveryActionValue(value: unknown): { mode: "queue" | "interrupt" } | undefined {
177
+ if (!value || typeof value !== "object") return undefined;
178
+ const raw = value as any;
179
+ if (raw.action !== "pi_feishu_select_delivery") return undefined;
180
+ if (raw.mode !== "queue" && raw.mode !== "interrupt") return undefined;
181
+ return { mode: raw.mode };
182
+ }
183
+
184
+ export function buildResumeCard(data: ResumeSessionPage) {
185
+ const elements: any[] = [
186
+ {
187
+ tag: "markdown",
188
+ content: [
189
+ `当前工作区:**${escapeMarkdown(data.workspacePath)}**`,
190
+ data.total
191
+ ? `第 **${data.page + 1} / ${data.totalPages}** 页,共 **${data.total}** 条历史会话。`
192
+ : "还没有可切换的历史会话。",
193
+ "点击某条会话后,当前飞书对话会继续接着这条 Pi 会话往下聊。",
194
+ ].join("\n"),
195
+ },
196
+ ];
197
+
198
+ elements.push({
199
+ tag: "action",
200
+ actions: [
201
+ buildResumeScopeButton(data.key, "current", data.scope === "current"),
202
+ buildResumeScopeButton(data.key, "all", data.scope === "all"),
203
+ ],
204
+ });
205
+
206
+ for (const item of data.items) {
207
+ const lines = [
208
+ `**${escapeMarkdown(item.title)}**${item.isCurrent ? " `当前使用中`" : ""}`,
209
+ escapeMarkdown(item.subtitle),
210
+ `更新时间:${escapeMarkdown(item.modifiedLabel)}`,
211
+ ];
212
+ if (item.workspaceLabel) lines.push(`工作区:${escapeMarkdown(item.workspaceLabel)}`);
213
+ elements.push({
214
+ tag: "markdown",
215
+ content: lines.join("\n"),
216
+ });
217
+ elements.push({
218
+ tag: "action",
219
+ actions: [{
220
+ tag: "button",
221
+ text: {
222
+ tag: "plain_text",
223
+ content: item.isCurrent ? "当前会话" : "切换到这条会话",
224
+ },
225
+ type: item.isCurrent ? "primary" : "default",
226
+ value: {
227
+ action: "pi_feishu_resume_select",
228
+ key: data.key,
229
+ scope: data.scope,
230
+ page: data.page,
231
+ sessionPath: item.path,
232
+ },
233
+ }],
234
+ });
235
+ }
236
+
237
+ elements.push({
238
+ tag: "action",
239
+ actions: [
240
+ {
241
+ tag: "button",
242
+ text: { tag: "plain_text", content: "上一页" },
243
+ type: "default",
244
+ disabled: data.page <= 0,
245
+ value: {
246
+ action: "pi_feishu_resume_page",
247
+ key: data.key,
248
+ scope: data.scope,
249
+ page: Math.max(0, data.page - 1),
250
+ },
251
+ },
252
+ {
253
+ tag: "button",
254
+ text: { tag: "plain_text", content: "下一页" },
255
+ type: "default",
256
+ disabled: data.page >= data.totalPages - 1,
257
+ value: {
258
+ action: "pi_feishu_resume_page",
259
+ key: data.key,
260
+ scope: data.scope,
261
+ page: Math.min(Math.max(0, data.totalPages - 1), data.page + 1),
262
+ },
263
+ },
264
+ ],
265
+ });
266
+
267
+ return {
268
+ config: sharedCardConfig(),
269
+ header: {
270
+ template: "turquoise",
271
+ title: { tag: "plain_text", content: "切换 Pi 历史会话" },
272
+ },
273
+ elements,
274
+ };
275
+ }
276
+
277
+ export function parseModelActionValue(value: unknown): { key: string; provider: string; modelId: string } | undefined {
278
+ if (!value || typeof value !== "object") return undefined;
279
+ const raw = value as any;
280
+ if (raw.action !== "pi_feishu_select_model") return undefined;
281
+ if (typeof raw.key !== "string" || typeof raw.provider !== "string" || typeof raw.modelId !== "string") return undefined;
282
+ return { key: raw.key, provider: raw.provider, modelId: raw.modelId };
283
+ }
284
+
285
+ export function parseThinkingActionValue(value: unknown): { key: string; level: string } | undefined {
286
+ if (!value || typeof value !== "object") return undefined;
287
+ const raw = value as any;
288
+ if (raw.action !== "pi_feishu_select_thinking") return undefined;
289
+ if (typeof raw.key !== "string" || typeof raw.level !== "string" || !raw.level.trim()) return undefined;
290
+ return { key: raw.key, level: raw.level };
291
+ }
292
+
293
+ export function parseResumePageActionValue(value: unknown): { key: string; scope: ResumeScope; page: number } | undefined {
294
+ if (!value || typeof value !== "object") return undefined;
295
+ const raw = value as any;
296
+ if (raw.action !== "pi_feishu_resume_page") return undefined;
297
+ if (typeof raw.key !== "string") return undefined;
298
+ if (raw.scope !== "current" && raw.scope !== "all") return undefined;
299
+ if (typeof raw.page !== "number" || !Number.isFinite(raw.page)) return undefined;
300
+ return { key: raw.key, scope: raw.scope, page: Math.max(0, Math.floor(raw.page)) };
301
+ }
302
+
303
+ export function parseResumeSelectActionValue(value: unknown): { key: string; scope: ResumeScope; page: number; sessionPath: string } | undefined {
304
+ if (!value || typeof value !== "object") return undefined;
305
+ const raw = value as any;
306
+ if (raw.action !== "pi_feishu_resume_select") return undefined;
307
+ if (typeof raw.key !== "string" || typeof raw.sessionPath !== "string") return undefined;
308
+ if (raw.scope !== "current" && raw.scope !== "all") return undefined;
309
+ if (typeof raw.page !== "number" || !Number.isFinite(raw.page)) return undefined;
310
+ return {
311
+ key: raw.key,
312
+ scope: raw.scope,
313
+ page: Math.max(0, Math.floor(raw.page)),
314
+ sessionPath: raw.sessionPath,
315
+ };
316
+ }
317
+
318
+ function buildResumeScopeButton(key: string, scope: ResumeScope, active: boolean) {
319
+ return {
320
+ tag: "button",
321
+ text: {
322
+ tag: "plain_text",
323
+ content: scope === "current" ? "当前工作区" : "全部会话",
324
+ },
325
+ type: active ? "primary" : "default",
326
+ value: {
327
+ action: "pi_feishu_resume_page",
328
+ key,
329
+ scope,
330
+ page: 0,
331
+ },
332
+ };
333
+ }
334
+
335
+ function escapeMarkdown(text: string) {
336
+ return text.replace(/[`*_~]/g, "\\$&");
337
+ }
338
+
339
+ function sharedCardConfig() {
340
+ return {
341
+ wide_screen_mode: true,
342
+ update_multi: true,
343
+ };
344
+ }
345
+
346
+ /**
347
+ * 重启回执卡。三态共用同一张卡(`transport.updateCard` 原地改写),
348
+ * 所以用户看到的是「重启中 → 已重启」,而不是两条互不相干的消息。
349
+ */
350
+ export type RestartCardState =
351
+ | { stage: "restarting"; commit?: string; at: number }
352
+ | { stage: "done"; commit?: string; elapsedMs?: number; newPid?: number; at: number }
353
+ | { stage: "failed"; error: string; at: number }
354
+ | { stage: "unknown"; at: number };
355
+
356
+ export function buildRestartCard(state: RestartCardState) {
357
+ const time = new Date(state.at).toLocaleTimeString("zh-CN", { hour12: false });
358
+ const commitOf = (value?: string) => (value ? `\n代码版本:\`${escapeMarkdown(value)}\`` : "");
359
+ if (state.stage === "restarting") {
360
+ return {
361
+ config: sharedCardConfig(),
362
+ header: { template: "blue", title: { tag: "plain_text", content: "🔄 正在重启桥接" } },
363
+ elements: [
364
+ {
365
+ tag: "markdown",
366
+ content: [
367
+ `开始时间:${time}`,
368
+ "正在重载最新代码。会话上下文会保留,重启后可以直接接着聊。",
369
+ "预计 2–4 秒;这段时间内发出的消息可能收不到,请等这张卡变成「已重启」再发。",
370
+ ].join("\n") + commitOf(state.commit),
371
+ },
372
+ ],
373
+ };
374
+ }
375
+ if (state.stage === "done") {
376
+ const seconds = typeof state.elapsedMs === "number" ? `${(state.elapsedMs / 1000).toFixed(1)}s` : "未知";
377
+ return {
378
+ config: sharedCardConfig(),
379
+ header: { template: "green", title: { tag: "plain_text", content: "✅ 桥接已重启" } },
380
+ elements: [
381
+ {
382
+ tag: "markdown",
383
+ content: [
384
+ `耗时:${seconds}${typeof state.newPid === "number" ? ` · pid ${state.newPid}` : ""}`,
385
+ "会话上下文已保留,继续发消息即可。",
386
+ ].join("\n") + commitOf(state.commit),
387
+ },
388
+ ],
389
+ };
390
+ }
391
+ if (state.stage === "failed") {
392
+ return {
393
+ config: sharedCardConfig(),
394
+ header: { template: "red", title: { tag: "plain_text", content: "❌ 桥接重启失败" } },
395
+ elements: [
396
+ {
397
+ tag: "markdown",
398
+ content: `${escapeMarkdown(state.error)}\n\n桥接当前可能已停止。请在 Pi 终端执行 \`/feishu start\` 重新拉起。`,
399
+ },
400
+ ],
401
+ };
402
+ }
403
+ return {
404
+ config: sharedCardConfig(),
405
+ header: { template: "orange", title: { tag: "plain_text", content: "✅ 桥接已重启(回执缺失)" } },
406
+ elements: [
407
+ {
408
+ tag: "markdown",
409
+ content: "重启 worker 未留下结果文件(可能中途被杀),但新进程已接管网关锁,可以正常发消息。",
410
+ },
411
+ ],
412
+ };
413
+ }