@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,1559 @@
1
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { basename, isAbsolute, join, resolve } from "node:path";
4
+ import * as PiSdk from "@earendil-works/pi-coding-agent";
5
+ import { Type } from "typebox";
6
+ import type { AgentSession, SessionInfo } from "@earendil-works/pi-coding-agent";
7
+ import {
8
+ createAgentSession,
9
+ DefaultResourceLoader,
10
+ getAgentDir,
11
+ SessionManager,
12
+ } from "@earendil-works/pi-coding-agent";
13
+ import type { FeishuBridgeRuntime, BridgeJobEvent } from "../../feishu/bridge-runtime.ts";
14
+ import { CHILD_SESSION_ENV, ensureRoot, loadConfig, readJson, STATE_PATH, writeJson } from "../../feishu/config.ts";
15
+ import { debugLog } from "../../feishu/debug.ts";
16
+ import { waitForPrompt } from "../../feishu/prompt-timeout.ts";
17
+ import type { ResumeScope, ResumeSessionPage } from "../../feishu/cards.ts";
18
+ import type { ReplyCardSink } from "../../feishu/reply-card.ts";
19
+ import { normalizeThinkingLevels, type ThinkingStatus } from "../../feishu/thinking.ts";
20
+ import type { FeishuState } from "../../feishu/types.ts";
21
+ import type { ConversationRuntime, ConversationStatus, ContextUsage, RuntimeModel, StopConversationResult, ConversationTimeouts } from "../../feishu/runtime.ts";
22
+ import type { FeishuUiNotifyPayload } from "../../feishu/ui-notify.ts";
23
+ import {
24
+ buildAskCard,
25
+ cancelAskBySession,
26
+ failAsk,
27
+ registerAsk,
28
+ setAskCardMessage,
29
+ type AskHistoryEntry,
30
+ type AskOutcome,
31
+ type AskQuestion,
32
+ } from "../../feishu/ask.ts";
33
+ import { ensureWorkspaceExists, resolveWorkspacePath } from "../../feishu/workspace.ts";
34
+ import {
35
+ formatApprovalOutcome,
36
+ formatSubmitOutcome,
37
+ type LearnApprovalResult,
38
+ type LearnApprovalSubmitResult,
39
+ } from "../../feishu/learn-approval.ts";
40
+
41
+ /**
42
+ * Pi Runtime 适配器:
43
+ * 把飞书公共层需要的会话能力映射到 Pi 的 AgentSession API。
44
+ * 第一阶段保持与原 ConversationManager 完全一致的行为。
45
+ */
46
+
47
+ type ActiveRun = {
48
+ session: AgentSession;
49
+ runId?: string;
50
+ stopped: boolean;
51
+ status?: ReplyCardSink;
52
+ /** 当前轮流式回调(由 promptWithImages 设置) */
53
+ onDelta?: (delta: string) => void;
54
+ /** 正在等 feishu_ask 作答:硬超时要顺延,不能把等待时间算成模型超时 */
55
+ pausedForAsk?: boolean;
56
+ /** 本轮已经答过的旧问题,附到下一张选择题卡顶部 */
57
+ askHistory: AskHistoryEntry[];
58
+ };
59
+
60
+ type ModelRuntimeAdapter = {
61
+ getModel(provider: string, id: string): any;
62
+ hasConfiguredAuth(model: any): boolean;
63
+ getAvailable(): Promise<any[]>;
64
+ sessionOptions: Record<string, unknown>;
65
+ };
66
+
67
+ const RESUME_PAGE_SIZE = 10;
68
+
69
+ /**
70
+ * 扩展命令派发后的启动观察窗口(ms):命令处理器内部调用 pi.sendUserMessage
71
+ * 触发模型轮次,挂上是异步的。在这个窗口内轮询“是否已经跑起来”,
72
+ * 跑起来就提前退出;只读命令(不触发模型)会等满这个窗口。
73
+ */
74
+ const COMMAND_STARTUP_WINDOW_MS = 1000;
75
+
76
+ /**
77
+ * 需要交回 Pi 做扩展命令派发的斜杠命令(不含前导斜杠)。
78
+ *
79
+ * 默认所有斜杠文本都透传给模型:用户在飞书里打 `/kb 查 xxx` 本意是「问一句」,
80
+ * 若被 Pi 当成 knowledge-flow 的 /kb 命令吃掉,只会跑全文检索,那句问题根本到不了模型。
81
+ *
82
+ * 这里的命令属于反例:它们明确是「执行一个流程」而不是「问一个问题」,
83
+ * 模型收到字面文本也做不了,必须交回 Pi 派发。
84
+ * 命令名必须与 `knowledge-flow` 里 `pi.registerCommand()` 的名字一致。
85
+ */
86
+ const DISPATCHED_SLASH_COMMANDS = ["learn", "deploy-test"] as const;
87
+
88
+ /** 判断本轮文本是否要派发(而不是透传给模型):只看首个空白前的命令名 */
89
+ function shouldDispatchSlashCommand(text: string): boolean {
90
+ const trimmed = text.trimStart();
91
+ if (!trimmed.startsWith("/")) return false;
92
+ const name = trimmed.slice(1).split(/\s+/)[0] || "";
93
+ return (DISPATCHED_SLASH_COMMANDS as readonly string[]).includes(name);
94
+ }
95
+
96
+ export class PiConversationRuntime implements ConversationRuntime {
97
+ private readonly sessions = new Map<string, Promise<AgentSession>>();
98
+ private readonly sessionFileStats = new Map<string, { mtimeMs: number; size: number }>();
99
+ private readonly queues = new Map<string, Promise<void>>();
100
+ private readonly activeRuns = new Map<string, ActiveRun>();
101
+ private modelRuntimePromise: Promise<ModelRuntimeAdapter> | undefined;
102
+ private defaultProvider: string | undefined;
103
+ private defaultModelId: string | undefined;
104
+ private state: FeishuState;
105
+ private readonly cwd: string;
106
+ private readonly bridge?: FeishuBridgeRuntime;
107
+ private readonly timeouts: ConversationTimeouts;
108
+ /**
109
+ * 正在被飞书驱动、且可能产生扩展 UI 输出的会话 key(后进先出)。
110
+ * 扩展的 notify 事件不带会话信息,只能路由到「最近一次飞书发起的轮次」。
111
+ */
112
+ private readonly activeTurnKeys: string[] = [];
113
+ /** 轮次期间收到的扩展 notify 文本;模型没产出答案时作为兜底输出 */
114
+ private readonly uiNotifyBuffers = new Map<string, string[]>();
115
+ /**
116
+ * 发送「选择题」卡片的能力,由适配器注入(需要 transport,Runtime 层不直接碰飞书连接)。
117
+ * 参数是当前会话 key 与卡片 JSON;返回卡片消息 ID(拿不到就不返回),
118
+ * 超时后要用它原地刷新同一张卡。
119
+ */
120
+ private askSender?: (key: string, card: object) => Promise<string | undefined>;
121
+ /** 原地刷新提问卡片的能力(patch 同一条消息),由适配器注入 */
122
+ private askCardUpdater?: (messageId: string, card: object) => Promise<void>;
123
+ /**
124
+ * 【只提交】「进化审批」的能力,由适配器注入(需要飞书连接与审批配置,Runtime 层不直接碰)。
125
+ * 传当前会话 key 与候选点正文,**立即**返回实例号,不等审批人。
126
+ */
127
+ private learnApprovalSubmitter?: (key: string, body: string) => Promise<LearnApprovalSubmitResult>;
128
+ /**
129
+ * 【只查询】按实例号查一次审批状态,由适配器注入。
130
+ * 与提交拆开的原因:审批人要多久才点没有上限,提交后不能把整轮对话挂在等待上;
131
+ * 超时/中断后靠这个能力拿同一个实例号续查,而不是重发一张单。
132
+ */
133
+ private learnApprovalQuerier?: (key: string, instanceCode: string) => Promise<LearnApprovalResult>;
134
+
135
+ /** 由适配器注入卡片发送器(飞书连接就绪后调用) */
136
+ setAskSender(sender: (key: string, card: object) => Promise<string | undefined>) {
137
+ this.askSender = sender;
138
+ }
139
+
140
+ /** 由适配器注入进化审批【提交器】(飞书连接就绪后调用):只建单,不等结果 */
141
+ setLearnApprovalSubmitter(
142
+ submitter: (key: string, body: string) => Promise<LearnApprovalSubmitResult>,
143
+ ) {
144
+ this.learnApprovalSubmitter = submitter;
145
+ }
146
+
147
+ /** 由适配器注入进化审批【查询器】(飞书连接就绪后调用):按实例号查一次状态 */
148
+ setLearnApprovalQuerier(querier: (key: string, instanceCode: string) => Promise<LearnApprovalResult>) {
149
+ this.learnApprovalQuerier = querier;
150
+ }
151
+
152
+ /** 由适配器注入卡片更新器:超时后把卡片刷成「已超时」用 */
153
+ setAskCardUpdater(updater: (messageId: string, card: object) => Promise<void>) {
154
+ this.askCardUpdater = updater;
155
+ }
156
+
157
+ constructor(
158
+ cwd: string,
159
+ bridge?: FeishuBridgeRuntime,
160
+ timeouts: ConversationTimeouts = {},
161
+ ) {
162
+ this.cwd = cwd;
163
+ this.bridge = bridge;
164
+ this.timeouts = timeouts;
165
+ ensureRoot();
166
+ this.state = readJson<FeishuState>(STATE_PATH, { sessions: {} });
167
+ this.state.sessions ||= {};
168
+ this.state.models ||= {};
169
+ this.state.workspaces ||= {};
170
+ this.loadSettingsDefault();
171
+ }
172
+
173
+ /**
174
+ * Read default model for fallback in getSelectedModel.
175
+ * 默认链与本地 `pi` 一致:项目 `<cwd>/.pi/settings.json` → agent 全局 settings.json。
176
+ */
177
+ private loadSettingsDefault() {
178
+ for (const settingsPath of [
179
+ join(this.cwd, ".pi", "settings.json"),
180
+ join(getAgentDir(), "settings.json"),
181
+ ]) {
182
+ try {
183
+ const settings = JSON.parse(readFileSync(settingsPath, "utf-8"));
184
+ if (settings.defaultProvider && settings.defaultModel) {
185
+ this.defaultProvider = settings.defaultProvider;
186
+ this.defaultModelId = settings.defaultModel;
187
+ return;
188
+ }
189
+ } catch {}
190
+ }
191
+ }
192
+
193
+ async prompt(key: string, userText: string, onReply: (text: string) => Promise<void>, onDelta?: (delta: string) => void) {
194
+ return this.promptWithImages(key, userText, [], onReply, undefined, onDelta);
195
+ }
196
+
197
+ async promptWithImages(
198
+ key: string,
199
+ userText: string,
200
+ images: Array<{ type: "image"; data: string; mimeType: string }>,
201
+ onReply: (text: string) => Promise<void>,
202
+ status?: ReplyCardSink,
203
+ onDelta?: (delta: string) => void,
204
+ ) {
205
+ // 生成中又收到新消息的处理策略(全局运行时配置 messageDelivery):
206
+ // queue(默认)= 只排队等上一轮跑完;interrupt = 同时掰掉上一轮,让它快速收敛后再跑本轮。
207
+ // 关键:interruptActiveRun 用 void 发起(不 await)。本轮必须同步完成队列占位,
208
+ // 否则两条消息可能同时开跑,撞上 Pi 的 "Agent is already processing"。
209
+ const interrupt = this.isInterruptDelivery();
210
+ if (interrupt) void this.interruptActiveRun(key);
211
+ const runTurn = async () => {
212
+ debugLog("feishu.prompt.start", { key, textLength: userText.length, imageCount: images.length });
213
+ // 斜杠命令透传留痕:桥接自身不认的命令(如 /kb 查、/req 新)连同 `/` 原样交给模型,
214
+ // 不交给 Pi 的扩展命令机制(见 runPromptWithTimeouts 里的 expandPromptTemplates: false);
215
+ // 日志里能看到即证明已进入本轮 prompt。
216
+ const forwarded = userText.trimStart();
217
+ if (forwarded.startsWith("/")) {
218
+ debugLog("feishu.command.forwarded", { key, command: forwarded.split(/\s+/)[0] });
219
+ }
220
+ const session = await this.ensureSessionFresh(key);
221
+ const run: ActiveRun = { session, runId: status?.runId, stopped: false, status, onDelta, askHistory: [] };
222
+ this.activeRuns.set(key, run);
223
+ this.bridge?.beginFeishuInput(session.sessionId);
224
+ this.enterFeishuTurn(key);
225
+ /**
226
+ * 派发前的消息条数。扩展命令可能完全不触发模型轮次(如 /req 状态),
227
+ * 那时会话里最后一条 assistant 是**上一轮**的陈旧内容,不能当本轮答案。
228
+ */
229
+ const baselineMessageCount = session.messages?.length ?? 0;
230
+ /** 本轮收到的扩展 notify 文本(如 /req 状态 的输出),模型无答案时兜底 */
231
+ let uiNotifyText = "";
232
+ // 流式走 session 级订阅(createSession 里)→ run.onDelta,避免漏事件
233
+ let unsub: (() => void) | undefined;
234
+ let deltaCount = 0;
235
+ let deltaChars = 0;
236
+ if (onDelta) {
237
+ const userOnDelta = onDelta;
238
+ run.onDelta = (delta: string) => {
239
+ deltaCount += 1;
240
+ deltaChars += delta.length;
241
+ userOnDelta(delta);
242
+ };
243
+ }
244
+ try {
245
+ try {
246
+ await this.runPromptWithTimeouts(session, userText, images, key, onReply, status);
247
+ // 先收 notify(只读命令在处理函数里同步发出),再等命令另行触发的模型轮次跑完
248
+ uiNotifyText = this.drainUiNotify(key);
249
+ await this.settleForwardedCommand(session, userText, key, baselineMessageCount);
250
+ } catch (error) {
251
+ if (run.stopped) {
252
+ debugLog("feishu.prompt.stopped", { key });
253
+ return;
254
+ }
255
+ throw error;
256
+ }
257
+ } finally {
258
+ try { unsub?.(); } catch {}
259
+ run.onDelta = undefined;
260
+ if (this.activeRuns.get(key) === run) this.activeRuns.delete(key);
261
+ this.bridge?.endFeishuInput(session.sessionId);
262
+ this.recordSessionFileStat(key, session.sessionFile);
263
+ this.exitFeishuTurn(key);
264
+ }
265
+ if (run.stopped) return;
266
+ // 会话没有新增消息 = 本轮没跑模型,上一轮的 assistant 文本必须丢弃;
267
+ // 此时只有扩展 notify 的输出可用(只读命令如 /req 状态 全靠它)
268
+ const grew = (session.messages?.length ?? 0) > baselineMessageCount;
269
+ const freshAnswer = grew ? extractLastAssistantText(session) : "";
270
+ const answer = freshAnswer || uiNotifyText;
271
+ debugLog("feishu.prompt.done", {
272
+ key,
273
+ answerLength: answer.length,
274
+ grew,
275
+ uiNotifyLength: uiNotifyText.length,
276
+ deltaCount,
277
+ deltaChars,
278
+ });
279
+ await onReply(answer || "No response.");
280
+ // onReply(ReplyCard.completeWithAnswer)已切到 done;此处仅兜底
281
+ await status?.finish("done");
282
+ };
283
+ // 两种模式都排队:interrupt 已经同步发起了中断,上一轮会很快收敛,所以「排队」不会真的等很久
284
+ const next = this.previousTurn(key).then(runTurn).catch(async (error) => {
285
+ const message = error instanceof Error ? error.message : String(error);
286
+ debugLog("feishu.prompt.error", { key, error: message });
287
+ // 错误也写进同一张卡;onReply 若已是 completeWithAnswer 会 no-op(status 非 running)
288
+ if (status && "ensureFinal" in status && typeof (status as any).ensureFinal === "function") {
289
+ (status as any).ensureFinal(`出错了:${message}`);
290
+ await status.finish("failed", message);
291
+ } else {
292
+ await status?.finish("failed", message);
293
+ await onReply(`Pi error: ${message}`);
294
+ }
295
+ });
296
+ this.queues.set(key, next);
297
+ await next;
298
+ }
299
+
300
+ /** 当前全局投递策略是否为「立即打断」(读不到配置时按 queue 处理) */
301
+ private isInterruptDelivery(): boolean {
302
+ try {
303
+ return loadConfig()?.messageDelivery === "interrupt";
304
+ } catch {
305
+ return false;
306
+ }
307
+ }
308
+
309
+ /**
310
+ * 掰掉当前正在跑的那一轮:先标 stopped(它的 catch 据此静默收尾)、结束它的卡片,
311
+ * 再 abort —— 本轮会等队列上一轮收敛,所以这里不需要再 waitForIdle。
312
+ * 全程不抛错(调用处用 void 发起)。
313
+ */
314
+ private async interruptActiveRun(key: string) {
315
+ const active = this.activeRuns.get(key);
316
+ if (!active) return;
317
+ debugLog("feishu.prompt.interrupted_by_new_message", { key, runId: active.runId });
318
+ active.stopped = true;
319
+ // 先取消挂着的选择题:session.abort() 不会解除 feishu_ask 的等待,
320
+ // 而选择题不自动超时,不取消的话那个 Promise 会一直挂着,暂停卡也一直停在「等你选择」
321
+ await this.cancelPendingAsk(key, "被新消息打断");
322
+ try {
323
+ await active.status?.stopImmediately("已被新消息打断");
324
+ } catch {}
325
+ try {
326
+ await active.session.abort();
327
+ } catch (error) {
328
+ debugLog("feishu.prompt.interrupt_abort_error", {
329
+ key,
330
+ error: error instanceof Error ? error.message : String(error),
331
+ });
332
+ }
333
+ }
334
+
335
+ /**
336
+ * 取消某会话里挂着的选择题,并把那张卡片刷成「提问已结束」。
337
+ * 返回被取消的条数(供日志/测试断言)。
338
+ */
339
+ private async cancelPendingAsk(key: string, reason: string): Promise<number> {
340
+ const canceled = cancelAskBySession(key);
341
+ if (!canceled.length) return 0;
342
+ debugLog("feishu.ask.canceled", { key, reason, count: canceled.length });
343
+ const updater = this.askCardUpdater;
344
+ if (updater) {
345
+ for (const record of canceled) {
346
+ if (!record.cardMessageId) continue;
347
+ try {
348
+ await updater(
349
+ record.cardMessageId,
350
+ buildAskCard(record.askId, record.questions, record.answers, "canceled"),
351
+ );
352
+ } catch (error) {
353
+ debugLog("feishu.ask.cancel_card_failed", {
354
+ askId: record.askId,
355
+ key,
356
+ error: error instanceof Error ? error.message : String(error),
357
+ });
358
+ }
359
+ }
360
+ }
361
+ return canceled.length;
362
+ }
363
+
364
+ /** 供 /status 使用 */
365
+ getStatus(key: string): ConversationStatus {
366
+ const active = this.activeRuns.get(key);
367
+ return {
368
+ cwd: this.getWorkspace(key),
369
+ hasActiveRun: Boolean(active),
370
+ activeStopped: Boolean(active?.stopped),
371
+ };
372
+ }
373
+
374
+ async getActualModel(key: string) {
375
+ const model = await this.getSelectedModel(key);
376
+ if (!model) return "默认模型";
377
+ return `${model.provider}/${model.id}`;
378
+ }
379
+
380
+ /** 当前 Pi 会话的思考强度和该模型可用的档位。 */
381
+ async getThinkingStatus(key: string): Promise<ThinkingStatus> {
382
+ const session = await this.getSession(key);
383
+ return this.getThinkingStatusForSession(session);
384
+ }
385
+
386
+ async getContextStatus(key: string): Promise<ContextUsage | null> {
387
+ try {
388
+ const session = await this.getSession(key);
389
+ const anySession = session as any;
390
+ const tokens = anySession.contextTokens ?? anySession.tokenCount ?? null;
391
+ const contextWindow = anySession.contextWindow ?? anySession.model?.contextWindow ?? null;
392
+ const percent = tokens != null && contextWindow ? (Number(tokens) / Number(contextWindow)) * 100 : null;
393
+ return { tokens: tokens != null ? Number(tokens) : null, contextWindow: contextWindow != null ? Number(contextWindow) : null, percent };
394
+ } catch {
395
+ return null;
396
+ }
397
+ }
398
+
399
+ async stopConversation(key: string, onReply: (text: string) => Promise<void>, runId?: string): Promise<StopConversationResult> {
400
+ const active = this.activeRuns.get(key);
401
+ if (!active) {
402
+ const message = "当前没有进行中的处理。";
403
+ await onReply(message);
404
+ return { status: "not_running", message };
405
+ }
406
+ if (runId && active.runId && active.runId !== runId) {
407
+ const message = "这张任务卡片已不是当前进行中的任务。";
408
+ await onReply(message);
409
+ debugLog("feishu.prompt.stop_stale", { key, runId, activeRunId: active.runId });
410
+ return { status: "stale", message };
411
+ }
412
+
413
+ active.stopped = true;
414
+ const body = active.status?.bodyText || "";
415
+ // 先取消选择题:否则 feishu_ask 的等待会一直挂着,本轮收不干净
416
+ await this.cancelPendingAsk(key, "用户点了停止");
417
+ await active.status?.stopImmediately("已停止");
418
+ // 清单在 stopImmediately 里已被标成「已中断」,这里取的是定格后的版本
419
+ const progress = active.status?.progressText || "";
420
+ try {
421
+ await active.session.abort();
422
+ debugLog("feishu.prompt.abort", { key });
423
+ const message = "已停止";
424
+ await onReply(message);
425
+ return { status: "stopped", message, body, progress };
426
+ } catch (error) {
427
+ active.stopped = false;
428
+ debugLog("feishu.prompt.abort_error", { key, error: error instanceof Error ? error.message : String(error) });
429
+ const message = "停止失败,请重试。";
430
+ await onReply(message);
431
+ return { status: "failed", message };
432
+ }
433
+ }
434
+
435
+ async newConversation(key: string, onReply: (text: string) => Promise<void>) {
436
+ const previous = this.previousTurn(key);
437
+ const next = previous.then(async () => {
438
+ const cached = this.sessions.get(key);
439
+ if (cached) {
440
+ try { (await cached).dispose(); } catch {}
441
+ }
442
+ this.sessions.delete(key);
443
+ this.sessionFileStats.delete(key);
444
+ delete this.state.sessions[key];
445
+ writeJson(STATE_PATH, this.state);
446
+ await onReply("已创建新会话。旧会话历史已保留,下一条消息会从新上下文开始。");
447
+ }).catch(async (error) => {
448
+ await onReply(`Pi error: ${error instanceof Error ? error.message : String(error)}`);
449
+ });
450
+ this.queues.set(key, next);
451
+ await next;
452
+ }
453
+
454
+ async listResumeSessions(key: string, scope: ResumeScope, page: number): Promise<ResumeSessionPage> {
455
+ const sessions = await this.getResumeSessions(key, scope);
456
+ const normalizedPage = Math.max(0, Math.floor(page));
457
+ const total = sessions.length;
458
+ const totalPages = Math.max(1, Math.ceil(total / RESUME_PAGE_SIZE));
459
+ const clampedPage = Math.min(normalizedPage, totalPages - 1);
460
+ const currentSessionPath = this.normalizeSessionPath(this.state.sessions[key]);
461
+ const start = clampedPage * RESUME_PAGE_SIZE;
462
+ const items = sessions.slice(start, start + RESUME_PAGE_SIZE).map((session) => {
463
+ const sessionPath = this.normalizeSessionPath(session.path) || session.path;
464
+ return {
465
+ path: session.path,
466
+ title: session.name?.trim() || summarizeFirstMessage(session.firstMessage),
467
+ subtitle: session.name?.trim()
468
+ ? summarizeFirstMessage(session.firstMessage)
469
+ : `消息数:${session.messageCount}`,
470
+ modifiedLabel: formatModifiedLabel(session.modified),
471
+ workspaceLabel: scope === "all" ? formatWorkspaceLabel(session.cwd) : undefined,
472
+ isCurrent: Boolean(currentSessionPath && sessionPath && currentSessionPath === sessionPath),
473
+ };
474
+ });
475
+
476
+ return {
477
+ key,
478
+ workspacePath: this.getWorkspace(key),
479
+ scope,
480
+ page: clampedPage,
481
+ total,
482
+ totalPages,
483
+ items,
484
+ };
485
+ }
486
+
487
+ async resumeConversation(key: string, sessionPathInput: string, onReply: (text: string) => Promise<void>) {
488
+ if (this.activeRuns.has(key)) {
489
+ await onReply("当前还有进行中的处理,请先发送 /stop,再切换历史会话。");
490
+ return;
491
+ }
492
+
493
+ const previous = this.previousTurn(key);
494
+ const next = previous.then(async () => {
495
+ const sessionPath = this.normalizeExistingSessionPath(sessionPathInput);
496
+ const sessionInfo = await this.findSessionInfo(sessionPath);
497
+ if (!sessionInfo) {
498
+ await onReply("这条历史会话不存在,可能已经被删除。请重新打开 /resume 选择。");
499
+ return;
500
+ }
501
+
502
+ const currentPath = this.normalizeSessionPath(this.state.sessions[key]);
503
+ if (currentPath === sessionPath) {
504
+ this.state.workspaces![key] = sessionInfo.cwd || this.getWorkspace(key);
505
+ writeJson(STATE_PATH, this.state);
506
+ this.recordSessionFileStat(key, sessionPath);
507
+ await onReply(`你已经在这个历史会话里了。\n当前工作区:${this.state.workspaces![key]}`);
508
+ return;
509
+ }
510
+
511
+ const cached = this.sessions.get(key);
512
+ if (cached) {
513
+ try { (await cached).dispose(); } catch {}
514
+ }
515
+
516
+ this.sessions.delete(key);
517
+ this.sessionFileStats.delete(key);
518
+ this.state.sessions[key] = sessionPath;
519
+ this.state.workspaces![key] = sessionInfo.cwd || this.cwd;
520
+ writeJson(STATE_PATH, this.state);
521
+ this.recordSessionFileStat(key, sessionPath);
522
+ await onReply([
523
+ `已切换到历史会话:${sessionInfo.name?.trim() || summarizeFirstMessage(sessionInfo.firstMessage)}`,
524
+ `工作区:${this.state.workspaces![key]}`,
525
+ "下一条消息会继续接着这个会话往下聊。",
526
+ ].join("\n"));
527
+ }).catch(async (error) => {
528
+ await onReply(`Pi error: ${error instanceof Error ? error.message : String(error)}`);
529
+ });
530
+ this.queues.set(key, next);
531
+ await next;
532
+ }
533
+
534
+ async selectModel(key: string, provider: string, modelId: string, onReply: (text: string) => Promise<void>) {
535
+ const previous = this.previousTurn(key);
536
+ const next = previous.then(async () => {
537
+ const modelRuntime = await this.getModelRuntime();
538
+ const model = modelRuntime.getModel(provider, modelId);
539
+ if (!model || !modelRuntime.hasConfiguredAuth(model)) {
540
+ await onReply(`这个模型当前不可用:${provider}/${modelId}。请发送 /model 重新选择。`);
541
+ return;
542
+ }
543
+
544
+ const existing = this.state.models?.[key];
545
+ this.state.models![key] = { provider, id: modelId, thinkingLevel: existing?.thinkingLevel };
546
+ writeJson(STATE_PATH, this.state);
547
+
548
+ const cached = this.sessions.get(key);
549
+ if (cached) {
550
+ try { (await cached).dispose(); } catch {}
551
+ }
552
+ this.sessions.delete(key);
553
+ this.sessionFileStats.delete(key);
554
+ await onReply(`已切换到 ${provider}/${modelId}。当前飞书会话后续都会使用这个模型。`);
555
+ }).catch(async (error) => {
556
+ await onReply(`Pi error: ${error instanceof Error ? error.message : String(error)}`);
557
+ });
558
+ this.queues.set(key, next);
559
+ await next;
560
+ }
561
+
562
+ async selectThinkingLevel(key: string, level: string, onReply: (text: string) => Promise<void>) {
563
+ if (this.activeRuns.has(key)) {
564
+ await onReply("当前正在生成回复,请等待完成后再调整思考强度。");
565
+ return;
566
+ }
567
+ const previous = this.previousTurn(key);
568
+ const next = previous.then(async () => {
569
+ const session = await this.getSession(key);
570
+ const status = this.getThinkingStatusForSession(session);
571
+ if (!status.available) {
572
+ await onReply("无法从 Pi 读取当前模型可用的 thinking levels,未做任何修改。请稍后重试。");
573
+ return;
574
+ }
575
+ if (!status.availableLevels.includes(level)) {
576
+ await onReply(`Pi 当前模型不支持 thinking level \`${level}\`。请重新发送 /thinking 选择。`);
577
+ return;
578
+ }
579
+
580
+ const sessionApi = session as any;
581
+ if (typeof sessionApi.setThinkingLevel !== "function") {
582
+ await onReply("当前 Pi 版本不支持从飞书调整思考强度。请升级 Pi 后重试。");
583
+ return;
584
+ }
585
+ sessionApi.setThinkingLevel(level);
586
+ const existing = this.state.models?.[key];
587
+ if (existing) {
588
+ this.state.models![key] = { ...existing, thinkingLevel: level };
589
+ writeJson(STATE_PATH, this.state);
590
+ }
591
+ const effective = this.getThinkingStatusForSession(session).currentLevel || level;
592
+ await onReply(`Thinking level set to: ${effective}`);
593
+ }).catch(async (error) => {
594
+ await onReply(`Pi error: ${error instanceof Error ? error.message : String(error)}`);
595
+ });
596
+ this.queues.set(key, next);
597
+ await next;
598
+ }
599
+
600
+ getWorkspace(key: string) {
601
+ return this.state.workspaces?.[key] || this.cwd;
602
+ }
603
+
604
+ async switchWorkspace(key: string, workspaceInput: string | undefined, onReply: (text: string) => Promise<void>) {
605
+ if (!workspaceInput) {
606
+ const current = this.getWorkspace(key);
607
+ await onReply([
608
+ `当前工作区:${current}`,
609
+ "用法:/workspace /绝对路径",
610
+ "也支持:/workspace ~/your/project",
611
+ ].join("\n"));
612
+ return;
613
+ }
614
+
615
+ const previous = this.previousTurn(key);
616
+ const next = previous.then(async () => {
617
+ const workspace = resolveWorkspacePath(workspaceInput);
618
+ const cached = this.sessions.get(key);
619
+ if (cached) {
620
+ try { (await cached).dispose(); } catch {}
621
+ }
622
+ this.sessions.delete(key);
623
+ this.sessionFileStats.delete(key);
624
+ delete this.state.sessions[key];
625
+ this.state.workspaces![key] = workspace;
626
+ writeJson(STATE_PATH, this.state);
627
+ await onReply(`已切换到工作区:${workspace}\n下一条消息会在这个目录里创建新的 Pi 会话。`);
628
+ }).catch(async (error) => {
629
+ await onReply(error instanceof Error ? error.message : `Pi error: ${String(error)}`);
630
+ });
631
+ this.queues.set(key, next);
632
+ await next;
633
+ }
634
+
635
+ async getAvailableModels(): Promise<RuntimeModel[]> {
636
+ const modelRuntime = await this.getModelRuntime();
637
+ const available = await modelRuntime.getAvailable();
638
+ return [...available]
639
+ .map(toRuntimeModel)
640
+ .sort((a, b) => {
641
+ const providerCmp = a.provider.localeCompare(b.provider);
642
+ if (providerCmp !== 0) return providerCmp;
643
+ return a.id.localeCompare(b.id);
644
+ });
645
+ }
646
+
647
+ async getSelectedModel(key: string): Promise<RuntimeModel | undefined> {
648
+ const native = await this.getSelectedNativeModel(key);
649
+ return native ? toRuntimeModel(native) : undefined;
650
+ }
651
+
652
+ /** 内部使用的原生 Pi 模型(不跨出本适配器)。 */
653
+ private async getSelectedNativeModel(key: string) {
654
+ const modelRuntime = await this.getModelRuntime();
655
+ const selected = this.state.models?.[key];
656
+ if (selected) {
657
+ const model = modelRuntime.getModel(selected.provider, selected.id);
658
+ if (model && modelRuntime.hasConfiguredAuth(model)) return model;
659
+ }
660
+ const cached = this.sessions.get(key);
661
+ if (cached) {
662
+ return (await cached).model;
663
+ }
664
+ // Check settings default model before falling back to first available
665
+ if (this.defaultProvider && this.defaultModelId) {
666
+ const defaultModel = modelRuntime.getModel(this.defaultProvider, this.defaultModelId);
667
+ if (defaultModel && modelRuntime.hasConfiguredAuth(defaultModel)) {
668
+ return defaultModel;
669
+ }
670
+ }
671
+ const available = await this.getAvailableModels();
672
+ const first = available[0];
673
+ return first ? modelRuntime.getModel(first.provider, first.id) : undefined;
674
+ }
675
+
676
+ private getModelRuntime() {
677
+ this.modelRuntimePromise ||= createModelRuntimeAdapter();
678
+ return this.modelRuntimePromise;
679
+ }
680
+
681
+ resetMemory() {
682
+ for (const session of this.sessions.values()) {
683
+ void session.then((s) => s.dispose()).catch(() => undefined);
684
+ }
685
+ this.sessions.clear();
686
+ this.sessionFileStats.clear();
687
+ this.queues.clear();
688
+ this.state = { sessions: {}, models: {}, workspaces: {} };
689
+ }
690
+
691
+ private recordSessionFileStat(key: string, sessionFile?: string) {
692
+ const filePath = sessionFile || this.state.sessions[key];
693
+ if (!filePath) {
694
+ this.sessionFileStats.delete(key);
695
+ return;
696
+ }
697
+ try {
698
+ if (existsSync(filePath)) {
699
+ const stat = statSync(filePath);
700
+ this.sessionFileStats.set(key, {
701
+ mtimeMs: stat.mtimeMs,
702
+ size: stat.size,
703
+ });
704
+ }
705
+ } catch {}
706
+ }
707
+
708
+ private async ensureSessionFresh(key: string): Promise<AgentSession> {
709
+ const cachedPromise = this.sessions.get(key);
710
+ if (!cachedPromise) {
711
+ return this.getSession(key);
712
+ }
713
+ const sessionFile = this.state.sessions[key];
714
+ const recorded = this.sessionFileStats.get(key);
715
+ if (sessionFile && existsSync(sessionFile)) {
716
+ try {
717
+ const currentStat = statSync(sessionFile);
718
+ const isModified = recorded
719
+ ? currentStat.mtimeMs > recorded.mtimeMs || currentStat.size !== recorded.size
720
+ : false;
721
+ if (isModified) {
722
+ debugLog("feishu.pi.session_hot_reload", {
723
+ key,
724
+ sessionFile,
725
+ recordedMtime: recorded?.mtimeMs,
726
+ currentMtime: currentStat.mtimeMs,
727
+ recordedSize: recorded?.size,
728
+ currentSize: currentStat.size,
729
+ });
730
+ try {
731
+ const oldSession = await cachedPromise;
732
+ oldSession.dispose();
733
+ } catch {}
734
+ this.sessions.delete(key);
735
+ const refreshed = this.createSession(key);
736
+ this.sessions.set(key, refreshed);
737
+ return refreshed;
738
+ }
739
+ if (!recorded) {
740
+ this.sessionFileStats.set(key, {
741
+ mtimeMs: currentStat.mtimeMs,
742
+ size: currentStat.size,
743
+ });
744
+ }
745
+ } catch {}
746
+ }
747
+ return cachedPromise;
748
+ }
749
+
750
+ private getSession(key: string): Promise<AgentSession> {
751
+ const cached = this.sessions.get(key);
752
+ if (cached) return cached;
753
+ const created = this.createSession(key);
754
+ this.sessions.set(key, created);
755
+ return created;
756
+ }
757
+
758
+ private getThinkingStatusForSession(session: AgentSession): ThinkingStatus {
759
+ const sessionApi = session as any;
760
+ const currentLevel = typeof sessionApi.thinkingLevel === "string" && sessionApi.thinkingLevel.trim()
761
+ ? sessionApi.thinkingLevel
762
+ : undefined;
763
+ if (typeof sessionApi.getAvailableThinkingLevels !== "function") {
764
+ return { currentLevel, availableLevels: [], available: false };
765
+ }
766
+ try {
767
+ return {
768
+ currentLevel,
769
+ availableLevels: normalizeThinkingLevels(sessionApi.getAvailableThinkingLevels()),
770
+ available: true,
771
+ };
772
+ } catch {
773
+ return { currentLevel, availableLevels: [], available: false };
774
+ }
775
+ }
776
+
777
+ private previousTurn(key: string) {
778
+ // Keep a conversation serial for as long as Pi needs. A bridge-side queue
779
+ // timeout can start a second turn while the first is still streaming.
780
+ return this.queues.get(key) || Promise.resolve();
781
+ }
782
+
783
+ private notifyMs() {
784
+ const sec = this.timeouts.promptNotifySec;
785
+ return typeof sec === "number" && Number.isFinite(sec) && sec > 0 ? sec * 1000 : 0;
786
+ }
787
+
788
+ private hardTimeoutMs() {
789
+ const sec = this.timeouts.promptTimeoutSec;
790
+ return typeof sec === "number" && Number.isFinite(sec) && sec > 0 ? sec * 1000 : 0;
791
+ }
792
+
793
+ /** 轮次开始:登记活跃 key,并清空上一轮残留的 notify 缓冲 */
794
+ private enterFeishuTurn(key: string) {
795
+ this.activeTurnKeys.push(key);
796
+ this.uiNotifyBuffers.set(key, []);
797
+ }
798
+
799
+ /** 轮次结束:注销 key 并丢弃未使用的 notify 缓冲 */
800
+ private exitFeishuTurn(key: string) {
801
+ const index = this.activeTurnKeys.lastIndexOf(key);
802
+ if (index >= 0) this.activeTurnKeys.splice(index, 1);
803
+ this.uiNotifyBuffers.delete(key);
804
+ }
805
+
806
+ /**
807
+ * 接收 Pi 侧扩展 emit 的 UI 通知,路由到「最近一次飞书发起的轮次」。
808
+ * 没有活跃轮次时(例如命令来自 Pi TUI)直接丢弃,避免误发到飞书会话。
809
+ */
810
+ pushUiNotify(payload: FeishuUiNotifyPayload | string) {
811
+ const key = this.activeTurnKeys[this.activeTurnKeys.length - 1];
812
+ if (!key) return;
813
+ const text = (typeof payload === "string" ? payload : String(payload?.text ?? "")).trim();
814
+ if (!text) return;
815
+ const buffer = this.uiNotifyBuffers.get(key) || [];
816
+ // 同一条文案在一次轮次里可能被重复 notify,去重避免刷屏
817
+ if (buffer.includes(text)) return;
818
+ buffer.push(text);
819
+ this.uiNotifyBuffers.set(key, buffer);
820
+ debugLog("feishu.ui.notify_received", { key, length: text.length });
821
+ }
822
+
823
+ /** 取走并清空某轮次累积的扩展 notify 文本 */
824
+ private drainUiNotify(key: string): string {
825
+ const buffer = this.uiNotifyBuffers.get(key);
826
+ if (!buffer?.length) return "";
827
+ this.uiNotifyBuffers.set(key, []);
828
+ return buffer.join("\n\n");
829
+ }
830
+
831
+ /**
832
+ * 发一张选择题卡片给「发起这次提问的会话」,并等用户点击。
833
+ * 全部答完 → 返回答案;**不设自动超时**,用户不点就一直等(被新消息/停止打断时才取消)。
834
+ *
835
+ * key 必须由调用方(工具闭包)显式传入:activeTurnKeys 是所有会话共用的栈顶,
836
+ * 私聊/群聊并发时会取到别的会话,导致卡片发错聊天(跨会话串台)。
837
+ */
838
+ private async askUser(sessionKey: string, questions: AskQuestion[]): Promise<AskOutcome> {
839
+ const key = sessionKey;
840
+ if (!key) throw new Error("当前没有活跃的飞书会话");
841
+ if (!this.askSender) throw new Error("飞书连接未就绪");
842
+
843
+ const sender = this.askSender;
844
+ const run = this.activeRuns.get(key);
845
+ const history = run?.askHistory ?? [];
846
+
847
+ // 进入临界区:先把正在流式的卡定格成「等你选择」,并告诉硬超时这里在等人
848
+ if (run) run.pausedForAsk = true;
849
+ await this.pauseCardForAsk(run);
850
+
851
+ let outcome: AskOutcome | undefined;
852
+ try {
853
+ outcome = await new Promise<AskOutcome>((resolve) => {
854
+ const record = registerAsk(key, questions, resolve);
855
+ const askCard = buildAskCard(record.askId, questions, record.answers, "pending", history);
856
+ // 每次都平铺新卡,绝不复用旧卡原地改写。
857
+ // 回归背景:本轮第一次提问作答后 resume 会开出一段新回复卡,此时若把第二次
858
+ // 提问写回第一张旧卡,新问题就停留在旧位置上、新回复卡又排在它下面 ——
859
+ // 用户看到的是「选择题卡被盖住 / 顺序颠倒」,还会误点新回复卡上的停止。
860
+ debugLog("feishu.ask.card_creating", {
861
+ askId: record.askId,
862
+ key,
863
+ historyCount: history.length,
864
+ });
865
+ const send = sender(key, askCard);
866
+ void send
867
+ .then((messageId) => {
868
+ // 回填卡片消息 ID,取消刷卡片时要用
869
+ if (!messageId) return;
870
+ setAskCardMessage(record.askId, messageId);
871
+ })
872
+ .catch((error) => {
873
+ debugLog("feishu.ask.send_failed", {
874
+ askId: record.askId,
875
+ key,
876
+ error: error instanceof Error ? error.message : String(error),
877
+ });
878
+ // 发送失败 ≠ 用户没选:走 failAsk,让模型知道这道题用户根本没看到
879
+ failAsk(record.askId);
880
+ });
881
+ });
882
+ } finally {
883
+ if (run) run.pausedForAsk = false;
884
+ // 记下本轮已答的旧问题,供本轮下一张选择题卡展示
885
+ if (run && outcome) {
886
+ for (const answer of outcome.answers) {
887
+ if (answer.chosen) run.askHistory.push({ question: answer.question, chosen: answer.chosen });
888
+ }
889
+ }
890
+ // 关键不变量:出临界区时绝不允许留下 paused 卡(详见 settleCardAfterAsk)
891
+ await this.settleCardAfterAsk(run, outcome);
892
+ }
893
+
894
+ debugLog("feishu.ask.settled", {
895
+ key,
896
+ timedOut: outcome.timedOut,
897
+ canceled: Boolean(outcome.canceled),
898
+ answered: outcome.answers.filter((answer) => answer.chosen).length,
899
+ total: outcome.answers.length,
900
+ });
901
+ return outcome;
902
+ }
903
+
904
+ /** 进入选择题等待:把流式卡定格成「等你选择」,失败不影响提问本身 */
905
+ private async pauseCardForAsk(run: ActiveRun | undefined): Promise<void> {
906
+ const card = run?.status;
907
+ if (!card) return;
908
+ try {
909
+ await card.pauseForAsk("等你选择");
910
+ } catch (error) {
911
+ debugLog("feishu.ask.pause_card_failed", {
912
+ error: error instanceof Error ? error.message : String(error),
913
+ });
914
+ }
915
+ }
916
+
917
+ /**
918
+ * 选择题临界区出口:无论哪条路径,都必须把 paused 消掉。
919
+ * - 正常作答 / 超时 → resume():把暂停卡翻成「已选择」,再开一段新卡继续写
920
+ * - 被取消(停止/新消息打断)→ 直接收尾成「已停止」:那一轮已经作废,不能再开新卡
921
+ */
922
+ private async settleCardAfterAsk(
923
+ run: ActiveRun | undefined,
924
+ outcome: AskOutcome | undefined,
925
+ ): Promise<void> {
926
+ const card = run?.status;
927
+ if (!card) return;
928
+ try {
929
+ // canceled 只有一个真正要停卡的来源:整轮被停止 / 被新消息打断
930
+ // (stopConversation / interruptActiveRun 都是先把 run.stopped 置 true 再取消提问)。
931
+ // 提问卡片发送失败走的是 sendFailed(不是 canceled):那种情况本轮还在继续,
932
+ // 把卡停在「已停止」会让最后的 completeWithAnswer 被终态守卫直接丢掉。
933
+ const stopped = Boolean(outcome?.canceled) && Boolean(run?.stopped);
934
+ if (!stopped) {
935
+ await card.resume();
936
+ return;
937
+ }
938
+ await card.finish("stopped", "提问已结束");
939
+ } catch (error) {
940
+ debugLog("feishu.ask.settle_card_failed", {
941
+ canceled: Boolean(outcome?.canceled),
942
+ error: error instanceof Error ? error.message : String(error),
943
+ });
944
+ } finally {
945
+ // 兜底:上面两步都没能把它拉出 paused 时,绝不允许把中间态留在卡片上
946
+ if (card.paused) {
947
+ try {
948
+ await card.finish("stopped", "已停止");
949
+ } catch {}
950
+ }
951
+ }
952
+ }
953
+
954
+ /**
955
+ * feishu_ask:把选择题渲染成飞书卡片按钮,用户点完再把结果交回模型。
956
+ * 作为 customTools 注入会话(桥接扩展不在会话里加载,所以不能靠 registerTool)。
957
+ * 工具按会话创建,闭包持有该会话的 key,保证卡片只发回提问所在的那个会话。
958
+ */
959
+ private buildAskTool(sessionKey: string) {
960
+ return {
961
+ name: "feishu_ask",
962
+ label: "Feishu Ask",
963
+ description:
964
+ "Ask the user to pick from options in the Feishu chat. Renders an interactive card with buttons and returns the user's choices. "
965
+ + "Use this instead of asking option questions as plain text (e.g. 'reply 1A 2A 3A') — typing letters back is a terrible experience.",
966
+ promptSnippet: "Ask the user multiple-choice questions as clickable Feishu card buttons (飞书的提问工具)。",
967
+ promptGuidelines: [
968
+ "Replying through Feishu and the user must choose between options: call feishu_ask, never list options as plain text.",
969
+ "Keep option labels short (<= 10 chars) and in business wording; every option's description MUST give its pros and cons in one line each (「好处:…;坏处:…」). Non-technical requests MUST be phrased in business language — no proto field / table / function names.",
970
+ "At most 4 questions per call; each question gets 2-4 options.",
971
+ "Ask everything you need in ONE call (up to 4 questions). Ask again later only when the next question truly depends on the previous answer.",
972
+ ],
973
+ parameters: Type.Object({
974
+ questions: Type.Array(
975
+ Type.Object({
976
+ header: Type.String({ description: "短标题,<= 16 字,如「货币范围」" }),
977
+ question: Type.String({
978
+ description:
979
+ "完整问题。业务类需求用业务语言(不写 proto 字段名 / 表名 / 函数名);"
980
+ + "技术口径题可保留技术名,但必须附一句业务影响",
981
+ }),
982
+ options: Type.Array(
983
+ Type.Object({
984
+ label: Type.String({ description: "按钮上的短标签(<= 10 字),用业务词,如「发奖赠送」" }),
985
+ description: Type.Optional(
986
+ Type.String({
987
+ description:
988
+ "这道选项的好处与坏处,各一句,形如「好处:…;坏处:…」;推荐项要注明「推荐」",
989
+ }),
990
+ ),
991
+ }),
992
+ { minItems: 2, maxItems: 4 },
993
+ ),
994
+ }),
995
+ { minItems: 1, maxItems: 4 },
996
+ ),
997
+ }),
998
+ execute: async (_toolCallId: string, params: unknown) => {
999
+ const questions = normalizeAskQuestions((params as { questions?: unknown })?.questions);
1000
+ if (!questions.length) {
1001
+ return askToolResult("Error: questions 需要 1-4 个问题,每个 2-4 个选项。");
1002
+ }
1003
+ try {
1004
+ return askToolResult(formatAskOutcome(await this.askUser(sessionKey, questions)));
1005
+ } catch (error) {
1006
+ const message = error instanceof Error ? error.message : String(error);
1007
+ return askToolResult(`Error: ${message},请改用纯文本向用户提问。`);
1008
+ }
1009
+ },
1010
+ };
1011
+ }
1012
+
1013
+ /**
1014
+ * 进化审批工具(两个):把「改文件」这件事变成一道必须过的审批。
1015
+ *
1016
+ * - `feishu_learn_approval_submit`:只建单,**立即返回实例号**,不等审批人。
1017
+ * - `feishu_learn_approval_status`:按实例号查一次状态,给「隔一会儿续查」用。
1018
+ *
1019
+ * 拆成两个的原因:审批人可能十分钟后才点,旧工具在一个 execute 里 await 轮询到超时,
1020
+ * 会把整轮对话卡死,且期间一旦打断(插话 / resume)就永远拿不到结论——实例其实建好了。
1021
+ * 与 feishu_ask 一样是**会话级注入**的:需要当前会话的 key 才能拿到发起人 open_id。
1022
+ * 本地「派」(无飞书桥接)不会注册本工具,因此 /learn 应用 在派里会退化提示。
1023
+ */
1024
+ private buildLearnApprovalTools(sessionKey: string) {
1025
+ return [
1026
+ {
1027
+ name: "feishu_learn_approval_submit",
1028
+ label: "Feishu Learn Approval Submit",
1029
+ description:
1030
+ "Submit a Feishu approval instance for an evolution (/learn) and return its instance code immediately. "
1031
+ + "It does NOT wait for the approver. Check the outcome later with feishu_learn_approval_status. "
1032
+ + "ONLY an APPROVED result may you modify any file.",
1033
+ promptSnippet: "Submit an evolution (/learn) approval request to a real Feishu approval form.",
1034
+ promptGuidelines: [
1035
+ "Before modifying ANY file for /learn 应用, call feishu_learn_approval_submit, then poll feishu_learn_approval_status with the instance code.",
1036
+ "Put the authorized candidate points verbatim into body so the approver knows exactly what will be changed.",
1037
+ "Never submit a second instance for the same approval: reuse the instance code you already got.",
1038
+ ],
1039
+ parameters: Type.Object({
1040
+ body: Type.String({
1041
+ description:
1042
+ "Approval content: the candidate points to be applied (id, target file, what will change). Be specific.",
1043
+ }),
1044
+ }),
1045
+ execute: async (_toolCallId: string, params: unknown) => {
1046
+ const body = String((params as { body?: unknown })?.body ?? "").trim();
1047
+ if (!body) return askToolResult("Error: body 不能为空,请填要落地的候选点内容。");
1048
+ if (!this.learnApprovalSubmitter) {
1049
+ return askToolResult(
1050
+ "Error: 当前环境没有接入飞书审批通道,无法为进化取授权。请在飞书会话里执行 /learn 应用 <编号>。",
1051
+ );
1052
+ }
1053
+ try {
1054
+ return askToolResult(formatSubmitOutcome(await this.learnApprovalSubmitter(sessionKey, body)));
1055
+ } catch (error) {
1056
+ const message = error instanceof Error ? error.message : String(error);
1057
+ return askToolResult(`Error: 提交进化审批失败:${message}。一个字都不要改,把原因告诉用户。`);
1058
+ }
1059
+ },
1060
+ },
1061
+ {
1062
+ name: "feishu_learn_approval_status",
1063
+ label: "Feishu Learn Approval Status",
1064
+ description:
1065
+ "Check one Feishu approval instance by its instance code. "
1066
+ + "Returns APPROVED / PENDING / REJECTED / CANCELED. ONLY APPROVED authorizes file changes; "
1067
+ + "a timeout or interruption is NOT a rejection — query the same instance code again instead of resubmitting.",
1068
+ promptSnippet: "Query the status of a submitted evolution (/learn) approval instance.",
1069
+ promptGuidelines: [
1070
+ "Never modify any file unless this tool returns APPROVED.",
1071
+ "Reuse the instance code from feishu_learn_approval_submit; do not create a second instance.",
1072
+ ],
1073
+ parameters: Type.Object({
1074
+ instanceCode: Type.String({
1075
+ description: "The approval instance code returned by feishu_learn_approval_submit.",
1076
+ }),
1077
+ }),
1078
+ execute: async (_toolCallId: string, params: unknown) => {
1079
+ const instanceCode = String((params as { instanceCode?: unknown })?.instanceCode ?? "").trim();
1080
+ if (!instanceCode) return askToolResult("Error: instanceCode 不能为空。");
1081
+ if (!this.learnApprovalQuerier) {
1082
+ return askToolResult(
1083
+ "Error: 当前环境没有接入飞书审批通道,无法查询审批状态。请在飞书会话里执行 /learn 应用 <编号>。",
1084
+ );
1085
+ }
1086
+ try {
1087
+ return askToolResult(
1088
+ formatApprovalOutcome(await this.learnApprovalQuerier(sessionKey, instanceCode)),
1089
+ );
1090
+ } catch (error) {
1091
+ const message = error instanceof Error ? error.message : String(error);
1092
+ // 查不到绝不放行:告诉模型按在途处理,拿同一实例号再查
1093
+ return askToolResult(
1094
+ `Error: 查询进化审批状态失败:${message}。一个字都不要改;`
1095
+ + `稍后用 feishu_learn_approval_status 传同一实例号 ${instanceCode} 续查(不要重复提交)。`,
1096
+ );
1097
+ }
1098
+ },
1099
+ },
1100
+ ];
1101
+ }
1102
+
1103
+ /**
1104
+ * 扩展命令(/req /kb /test 等)走 session.prompt 时只做「派发」:
1105
+ * prompt() 立即返回,真正的模型轮次由命令处理器内部的 pi.sendUserMessage 触发。
1106
+ * 不等这一轮跑完就拿答案,卡片只会显示 "No response."。
1107
+ *
1108
+ * 注:pi 会吞掉命令处理器抛的异常(只丢给 extensionRunner.emitError),
1109
+ * 所以这里不能靠 prompt() reject 判断失败。
1110
+ */
1111
+ private async settleForwardedCommand(
1112
+ session: AgentSession,
1113
+ userText: string,
1114
+ key: string,
1115
+ baselineMessageCount: number,
1116
+ ) {
1117
+ if (!userText.trimStart().startsWith("/")) return;
1118
+
1119
+ // 等轮次「启动」:消息条数增长或进入 streaming 都算
1120
+ const startedAt = Date.now();
1121
+ while (Date.now() - startedAt < COMMAND_STARTUP_WINDOW_MS) {
1122
+ if (!session.isIdle) break;
1123
+ if ((session.messages?.length ?? 0) > baselineMessageCount) break;
1124
+ await sleep(50);
1125
+ }
1126
+ if (session.isIdle) return;
1127
+
1128
+ const hardMs = this.hardTimeoutMs();
1129
+ debugLog("feishu.command.settle_wait", {
1130
+ key,
1131
+ hardMs,
1132
+ startupMs: Date.now() - startedAt,
1133
+ });
1134
+ const waitIdle = session.waitForIdle().catch(() => undefined);
1135
+ if (hardMs <= 0) {
1136
+ await waitIdle;
1137
+ return;
1138
+ }
1139
+ await Promise.race([waitIdle, sleep(hardMs)]);
1140
+ }
1141
+
1142
+ private async runPromptWithTimeouts(
1143
+ session: AgentSession,
1144
+ userText: string,
1145
+ images: Array<{ type: "image"; data: string; mimeType: string }>,
1146
+ key: string,
1147
+ onReply: (text: string) => Promise<void>,
1148
+ status?: ReplyCardSink,
1149
+ ) {
1150
+ const notifyMs = this.notifyMs();
1151
+ const hardMs = this.hardTimeoutMs();
1152
+ const hardSec = Math.round(hardMs / 1000);
1153
+ // 默认透传(expandPromptTemplates: false):斜杠文本原样进模型。
1154
+ // 例外:DISPATCHED_SLASH_COMMANDS(如 /learn、/deploy-test)明确是「执行流程」,交回 Pi 派发。
1155
+ const dispatch = shouldDispatchSlashCommand(userText);
1156
+ debugLog("feishu.prompt.dispatch_decision", { key, dispatch });
1157
+ await waitForPrompt(session.prompt(userText, {
1158
+ ...(images.length ? { images } : {}),
1159
+ expandPromptTemplates: dispatch,
1160
+ }), {
1161
+ notifyMs,
1162
+ hardMs,
1163
+ hardTimeoutMessage: `Pi 模型处理超时(超过 ${hardSec} 秒)仍未完成,已中止处理。可调大 config.json 中的 promptTimeoutSec。`,
1164
+ onStillRunning: () => {
1165
+ debugLog("feishu.prompt.notify_still_running", { key, elapsedMs: notifyMs });
1166
+ // A ReplyCard stays visibly "replying"; sending this as a final answer
1167
+ // would prematurely close the same card, so only non-card callers get
1168
+ // the legacy notice.
1169
+ if (status) return;
1170
+ void onReply("⏳ 仍在处理中,没有失败。请耐心等待,也可以点击「停止」中止。")
1171
+ .catch(() => undefined);
1172
+ },
1173
+ onHardTimeout: async () => {
1174
+ debugLog("feishu.prompt.hard_timeout", { key, elapsedMs: hardMs });
1175
+ try {
1176
+ await session.abort();
1177
+ } catch {}
1178
+ },
1179
+ // 正在等用户作答时硬超时顺延:把用户在选择题上花的时间算成「模型超时」会误杀整轮
1180
+ isPaused: () => Boolean(this.activeRuns.get(key)?.pausedForAsk),
1181
+ });
1182
+ }
1183
+
1184
+ private async createSession(key: string): Promise<AgentSession> {
1185
+ const workspaceCwd = this.getWorkspace(key);
1186
+ ensureWorkspaceExists(workspaceCwd);
1187
+ const existingFile = this.state.sessions[key];
1188
+ const selected = this.state.models?.[key];
1189
+ const modelRuntime = await this.getModelRuntime();
1190
+ const model = selected ? modelRuntime.getModel(selected.provider, selected.id) : undefined;
1191
+ const sessionManager = existingFile && existsSync(existingFile)
1192
+ ? SessionManager.open(existingFile, undefined, workspaceCwd)
1193
+ : SessionManager.create(workspaceCwd);
1194
+
1195
+ const loader = new DefaultResourceLoader({
1196
+ cwd: workspaceCwd,
1197
+ agentDir: getAgentDir(),
1198
+ systemPromptOverride: (base) => {
1199
+ const extra = "You are replying through Feishu/Lark. Keep answers concise and readable in chat. Do not use markdown tables. If you produced or saved an image file (screenshot, generated art, chart) and want the user to see it, put it on its own line as ![caption](/absolute/path/to/file.png) — the bridge uploads local images referenced this way and sends them as Feishu image messages (png/jpg/gif/webp/bmp, ≤10MB each, max 5 per reply). Relative paths resolve against the workspace cwd."
1200
+ // 平台身份与工具选择:本仓库注入的提问工具是 feishu_ask,
1201
+ // 不点名就会退回“回复 1A 2A”的纯文本选项
1202
+ + " Platform: Feishu (飞书). When the user has to choose between options, call the `feishu_ask` tool (renders clickable card buttons) — never type options as text like '回复 1A 2A'."
1203
+ + " `feishu_ask` is the ONLY option-asking tool in this session — never invent or call other ask tools, and never tell the user to reply with letters.";
1204
+ return base?.trim() ? `${base}\n\n${extra}` : extra;
1205
+ },
1206
+ });
1207
+
1208
+ const previousChildEnv = process.env[CHILD_SESSION_ENV];
1209
+ process.env[CHILD_SESSION_ENV] = "1";
1210
+ try {
1211
+ await loader.reload();
1212
+ } finally {
1213
+ if (previousChildEnv === undefined) delete process.env[CHILD_SESSION_ENV];
1214
+ else process.env[CHILD_SESSION_ENV] = previousChildEnv;
1215
+ }
1216
+
1217
+ const { session } = await createAgentSession({
1218
+ cwd: workspaceCwd,
1219
+ agentDir: getAgentDir(),
1220
+ ...modelRuntime.sessionOptions,
1221
+ model,
1222
+ sessionManager,
1223
+ resourceLoader: loader,
1224
+ // 选择题卡片工具只在飞书会话里有意义,故按会话注入而不是扩展注册
1225
+ customTools: [this.buildAskTool(key), ...this.buildLearnApprovalTools(key)],
1226
+ } as any);
1227
+
1228
+ // 诊断日志:确认自定义工具确实注入到了这个会话。
1229
+ // 用于定位「插话 / resume 之后工具从工具表消失」到底是桥接没注入,还是 pi 侧在中断轮次后不再暴露。
1230
+ debugLog("feishu.tools_injected", {
1231
+ key,
1232
+ sessionId: session.sessionId,
1233
+ tools: ["feishu_ask", "feishu_learn_approval_submit", "feishu_learn_approval_status"],
1234
+ });
1235
+
1236
+ await session.bindExtensions({});
1237
+ this.bridge?.attachSession(key, session.sessionId);
1238
+ // 会话级长期订阅:保证 text_delta 在 prompt 期间一定能收到
1239
+ session.subscribe((event: any) => {
1240
+ const run = this.activeRuns.get(key);
1241
+ run?.status?.updateFromEvent(event);
1242
+ const delta = extractAssistantTextDelta(event);
1243
+ if (delta && run && !run.stopped) {
1244
+ // 优先 onDelta(与 prompt 绑定);否则直接 append 到 status 卡
1245
+ if (run.onDelta) run.onDelta(delta);
1246
+ else if (run.status && typeof (run.status as any).append === "function") {
1247
+ (run.status as any).append(delta);
1248
+ }
1249
+ }
1250
+ if (event.type === "message_end") {
1251
+ handlePiMessageEnd(this.bridge, session.sessionId, key, event.message);
1252
+ }
1253
+ });
1254
+
1255
+ const desiredThinkingLevel = this.state.models?.[key]?.thinkingLevel;
1256
+ if (desiredThinkingLevel && typeof (session as any).setThinkingLevel === "function") {
1257
+ try {
1258
+ (session as any).setThinkingLevel(desiredThinkingLevel);
1259
+ } catch {}
1260
+ }
1261
+
1262
+ if (session.sessionFile && this.state.sessions[key] !== session.sessionFile) {
1263
+ this.state.sessions[key] = session.sessionFile;
1264
+ writeJson(STATE_PATH, this.state);
1265
+ }
1266
+ this.recordSessionFileStat(key, session.sessionFile);
1267
+ return session;
1268
+ }
1269
+
1270
+ private async getResumeSessions(key: string, scope: ResumeScope) {
1271
+ const base = scope === "all"
1272
+ ? await SessionManager.listAll()
1273
+ : await SessionManager.list(this.getWorkspace(key));
1274
+ return [...base].sort((a, b) => toTimeMs(b.modified) - toTimeMs(a.modified));
1275
+ }
1276
+
1277
+ private async findSessionInfo(sessionPath: string): Promise<SessionInfo | undefined> {
1278
+ const currentWorkspace = this.getWorkspaceFromSessionFile(sessionPath);
1279
+ const localSessions = currentWorkspace ? await SessionManager.list(currentWorkspace) : [];
1280
+ const normalizedTarget = this.normalizeSessionPath(sessionPath);
1281
+ const fromLocal = localSessions.find((item) => this.normalizeSessionPath(item.path) === normalizedTarget);
1282
+ if (fromLocal) return fromLocal;
1283
+ const allSessions = await SessionManager.listAll();
1284
+ return allSessions.find((item) => this.normalizeSessionPath(item.path) === normalizedTarget);
1285
+ }
1286
+
1287
+ private getWorkspaceFromSessionFile(sessionPath: string) {
1288
+ try {
1289
+ return SessionManager.open(sessionPath).getCwd();
1290
+ } catch {
1291
+ return undefined;
1292
+ }
1293
+ }
1294
+
1295
+ private normalizeExistingSessionPath(path: string) {
1296
+ if (!path || !existsSync(path)) {
1297
+ throw new Error("历史会话不存在,可能已经被删除。");
1298
+ }
1299
+ return realpathSync(path);
1300
+ }
1301
+
1302
+ private normalizeSessionPath(path: string | undefined) {
1303
+ if (!path) return undefined;
1304
+ try {
1305
+ return existsSync(path) ? realpathSync(path) : path;
1306
+ } catch {
1307
+ return path;
1308
+ }
1309
+ }
1310
+ }
1311
+
1312
+ /**
1313
+ * Pi changed its model-session API between releases. Keep the bridge usable
1314
+ * with both the AuthStorage/ModelRegistry API and the newer ModelRuntime API.
1315
+ */
1316
+ async function createModelRuntimeAdapter(): Promise<ModelRuntimeAdapter> {
1317
+ const sdk = PiSdk as any;
1318
+ if (typeof sdk.ModelRuntime?.create === "function") {
1319
+ const runtime = await sdk.ModelRuntime.create();
1320
+ return {
1321
+ getModel: (provider, id) => runtime.getModel(provider, id),
1322
+ hasConfiguredAuth: (model) => runtime.hasConfiguredAuth(model.provider),
1323
+ getAvailable: async () => [...await runtime.getAvailable()],
1324
+ sessionOptions: { modelRuntime: runtime },
1325
+ };
1326
+ }
1327
+
1328
+ if (typeof sdk.AuthStorage?.create === "function" && typeof sdk.ModelRegistry?.create === "function") {
1329
+ const authStorage = sdk.AuthStorage.create();
1330
+ const modelRegistry = sdk.ModelRegistry.create(authStorage);
1331
+ return {
1332
+ getModel: (provider, id) => modelRegistry.find(provider, id),
1333
+ hasConfiguredAuth: (model) => modelRegistry.hasConfiguredAuth(model),
1334
+ getAvailable: async () => [...await modelRegistry.getAvailable()],
1335
+ sessionOptions: { authStorage, modelRegistry },
1336
+ };
1337
+ }
1338
+
1339
+ throw new Error("当前 Pi 版本不支持创建飞书会话所需的模型运行时。");
1340
+ }
1341
+
1342
+ async function withTimeout<T>(promise: Promise<T>, timeoutMs: number, timeoutMessage: string): Promise<T> {
1343
+ let timer: NodeJS.Timeout | undefined;
1344
+ try {
1345
+ return await Promise.race([
1346
+ promise,
1347
+ new Promise<T>((_, reject) => {
1348
+ timer = setTimeout(() => reject(new Error(timeoutMessage)), timeoutMs);
1349
+ }),
1350
+ ]);
1351
+ } finally {
1352
+ if (timer) clearTimeout(timer);
1353
+ }
1354
+ }
1355
+
1356
+
1357
+ /** 从 Pi AgentSession 事件中提取 assistant 最终可见文本增量 */
1358
+ function extractAssistantTextDelta(event: any): string | undefined {
1359
+ if (!event || typeof event !== "object") return undefined;
1360
+ // 标准:message_update + assistantMessageEvent.text_delta
1361
+ if (event.type === "message_update") {
1362
+ const ame = event.assistantMessageEvent;
1363
+ if (ame?.type === "text_delta" && typeof ame.delta === "string" && ame.delta) {
1364
+ return ame.delta;
1365
+ }
1366
+ // 兼容:delta 挂在 event 上
1367
+ if (typeof event.delta === "string" && event.delta) return event.delta;
1368
+ }
1369
+ // 兼容:顶层 text_delta
1370
+ if (event.type === "text_delta" && typeof event.delta === "string" && event.delta) {
1371
+ return event.delta;
1372
+ }
1373
+ return undefined;
1374
+ }
1375
+
1376
+ function extractLastAssistantText(session: AgentSession): string {
1377
+ const messages = [...(session.messages || [])].reverse();
1378
+ for (const msg of messages as any[]) {
1379
+ if (msg.role !== "assistant") continue;
1380
+ const content = msg.content;
1381
+ if (typeof content === "string") return content.trim();
1382
+ if (Array.isArray(content)) {
1383
+ return content
1384
+ .map((p) => p?.type === "text" ? p.text : "")
1385
+ .join("")
1386
+ .trim();
1387
+ }
1388
+ }
1389
+ return "";
1390
+ }
1391
+
1392
+ /** 把 Pi 原生模型对象转换成平台无关的 RuntimeModel(禁止原生对象泄漏到飞书层)。 */
1393
+ function toRuntimeModel(model: any): RuntimeModel {
1394
+ const input = Array.isArray(model?.input) ? model.input : [];
1395
+ return {
1396
+ provider: String(model?.provider ?? ""),
1397
+ id: String(model?.id ?? ""),
1398
+ name: typeof model?.name === "string" ? model.name : undefined,
1399
+ supportsImage: input.includes("image"),
1400
+ };
1401
+ }
1402
+
1403
+ /**
1404
+ * 把 Pi 的 message_end 事件解析成平台无关的桥接事件(Pi 内部任务回传)。
1405
+ * 原 ConversationManager.handleMessageEnd 的等价逻辑。
1406
+ */
1407
+ export function handlePiMessageEnd(
1408
+ bridge: FeishuBridgeRuntime | undefined,
1409
+ sessionId: string | undefined,
1410
+ sessionKey: string | undefined,
1411
+ message: any,
1412
+ ) {
1413
+ if (!bridge || !sessionId || !message) return;
1414
+
1415
+ if (message.role === "toolResult" && message.toolName === "schedule_prompt") {
1416
+ const details = message.details || {};
1417
+ if (details.action !== "add") return;
1418
+ const rawJobs = Array.isArray(details.jobs) ? details.jobs : [];
1419
+ const jobs: Array<{ id: string; name?: string }> = [];
1420
+ for (const job of rawJobs) {
1421
+ if (!job?.id) continue;
1422
+ jobs.push({
1423
+ id: String(job.id),
1424
+ name: typeof job.name === "string" ? job.name : undefined,
1425
+ });
1426
+ }
1427
+ if (jobs.length) {
1428
+ bridge.handleJobEvent({ kind: "created", sessionId, sessionKey, jobs });
1429
+ }
1430
+ return;
1431
+ }
1432
+
1433
+ if (message.role === "custom" && message.customType === "scheduled_prompt") {
1434
+ const details = message.details || {};
1435
+ const jobId = typeof details.jobId === "string" ? details.jobId : "";
1436
+ if (!jobId) return;
1437
+
1438
+ if (details.mode === "subagent_done" && typeof details.output === "string") {
1439
+ bridge.handleJobEvent({
1440
+ kind: "done",
1441
+ sessionId,
1442
+ jobId,
1443
+ text: details.output,
1444
+ dedupeKey: `subagent_done:${jobId}:${message.id || details.output}`,
1445
+ });
1446
+ return;
1447
+ }
1448
+
1449
+ if (details.mode === "subagent_error" && typeof details.error === "string") {
1450
+ bridge.handleJobEvent({
1451
+ kind: "error",
1452
+ sessionId,
1453
+ jobId,
1454
+ error: details.error,
1455
+ dedupeKey: `subagent_error:${jobId}:${message.id || details.error}`,
1456
+ });
1457
+ return;
1458
+ }
1459
+
1460
+ bridge.handleJobEvent({ kind: "marker", sessionId, jobId });
1461
+ return;
1462
+ }
1463
+
1464
+ if (message.role === "assistant") {
1465
+ const text = extractMessageText(message);
1466
+ bridge.handleJobEvent({
1467
+ kind: "output",
1468
+ sessionId,
1469
+ text,
1470
+ messageId: message.id,
1471
+ timestamp: message.timestamp,
1472
+ });
1473
+ }
1474
+ }
1475
+
1476
+ function extractMessageText(message: any) {
1477
+ const content = message.content;
1478
+ if (typeof content === "string") return content.trim();
1479
+ if (!Array.isArray(content)) return "";
1480
+ return content
1481
+ .map((part) => part?.type === "text" ? part.text : "")
1482
+ .join("")
1483
+ .trim();
1484
+ }
1485
+
1486
+ function summarizeFirstMessage(text: string) {
1487
+ const normalized = (text || "").replace(/\s+/g, " ").trim();
1488
+ if (!normalized) return "未命名会话";
1489
+ return normalized.length > 36 ? `${normalized.slice(0, 35)}...` : normalized;
1490
+ }
1491
+
1492
+ function formatModifiedLabel(value: Date | string) {
1493
+ const date = value instanceof Date ? value : new Date(value);
1494
+ if (Number.isNaN(date.getTime())) return "未知";
1495
+ const yyyy = date.getFullYear();
1496
+ const mm = String(date.getMonth() + 1).padStart(2, "0");
1497
+ const dd = String(date.getDate()).padStart(2, "0");
1498
+ const hh = String(date.getHours()).padStart(2, "0");
1499
+ const min = String(date.getMinutes()).padStart(2, "0");
1500
+ return `${yyyy}-${mm}-${dd} ${hh}:${min}`;
1501
+ }
1502
+
1503
+ function formatWorkspaceLabel(cwd: string) {
1504
+ if (!cwd) return "(unknown)";
1505
+ return `${basename(cwd)} · ${cwd}`;
1506
+ }
1507
+
1508
+ function toTimeMs(value: Date | string) {
1509
+ const date = value instanceof Date ? value : new Date(value);
1510
+ return Number.isNaN(date.getTime()) ? 0 : date.getTime();
1511
+ }
1512
+
1513
+ /** 等待指定毫秒(用于扩展命令派发后的空闲轮询) */
1514
+ function sleep(ms: number): Promise<void> {
1515
+ return new Promise((resolve) => setTimeout(resolve, ms));
1516
+ }
1517
+
1518
+ /** 整理 feishu_ask 的入参:丢空项、label 去重、限幅到 1-4 问题 × 2-4 选项 */
1519
+ function normalizeAskQuestions(input: unknown): AskQuestion[] {
1520
+ if (!Array.isArray(input)) return [];
1521
+ const questions: AskQuestion[] = [];
1522
+ for (const raw of input.slice(0, 4)) {
1523
+ const item = raw as { header?: unknown; question?: unknown; options?: unknown };
1524
+ const question = String(item?.question ?? "").trim();
1525
+ if (!question) continue;
1526
+ const seen = new Set<string>();
1527
+ const options: { label: string; description?: string }[] = [];
1528
+ for (const rawOption of Array.isArray(item?.options) ? item.options.slice(0, 4) : []) {
1529
+ const option = rawOption as { label?: unknown; description?: unknown };
1530
+ const label = String(option?.label ?? "").trim();
1531
+ if (!label || seen.has(label)) continue;
1532
+ seen.add(label);
1533
+ const description = String(option?.description ?? "").trim();
1534
+ options.push(description ? { label, description } : { label });
1535
+ }
1536
+ if (options.length < 2) continue;
1537
+ const header = String(item?.header ?? "").trim();
1538
+ questions.push({ header: header || question.slice(0, 16), question, options });
1539
+ }
1540
+ return questions;
1541
+ }
1542
+
1543
+ /** 把用户选择整理成交给模型的文本 */
1544
+ function formatAskOutcome(outcome: AskOutcome): string {
1545
+ // 卡片没发出去时绝不能报「未选择」:模型会把那当成用户的决定,接着按默认值往下答
1546
+ if (outcome.sendFailed) {
1547
+ return "选择题卡片发送失败:用户没有收到这道题,请勿把未作答当成用户的决定。"
1548
+ + "要么重新调用 feishu_ask 再问一次,要么改用纯文本提问。";
1549
+ }
1550
+ const lines = outcome.answers.map(
1551
+ (answer, index) => `${index + 1}. [${answer.header}] ${answer.question} → ${answer.chosen ?? "(未选择)"}`,
1552
+ );
1553
+ const body = `用户的选择:\n${lines.join("\n")}`;
1554
+ return outcome.timedOut ? `${body}\n\n(等待点击超时,未作答项按「未选择」处理。)` : body;
1555
+ }
1556
+
1557
+ function askToolResult(text: string) {
1558
+ return { content: [{ type: "text" as const, text }], details: {} };
1559
+ }