@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,1169 @@
1
+ import { existsSync, mkdirSync, openSync, readFileSync, rmSync, statSync } from "node:fs";
2
+ import { spawn, spawnSync, type ChildProcess } from "node:child_process";
3
+ import { join } from "node:path";
4
+ import type { Readable } from "node:stream";
5
+ import { fileURLToPath } from "node:url";
6
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
7
+ import { Type } from "typebox";
8
+ import { BRIDGE_PI_PATH, CHILD_SESSION_ENV, CONFIG_PI_PATH, DAEMON_LOG_PATH, DEBUG_PI_LOG_PATH, DEDUPE_PI_PATH, ensureRoot, loadConfig, mask, removePath, PI_SOURCE, setRuntimeSource, STATE_PI_PATH, writeJson } from "../../feishu/config.ts";
9
+ import { debugLog } from "../../feishu/debug.ts";
10
+ import { FEISHU_UI_NOTIFY_EVENT, setFeishuUiNotifySink, type FeishuUiNotifyPayload } from "../../feishu/ui-notify.ts";
11
+ import { FeishuBridgeRuntime } from "../../feishu/bridge-runtime.ts";
12
+ import { FeishuBridgeStore } from "../../feishu/bridge-store.ts";
13
+ import { FeishuDelivery } from "../../feishu/delivery.ts";
14
+ import { acquireGatewayLock, gatewayLockPath, readAllGatewayOwnerPids, readGatewayOwner, type GatewayLockHandle, type GatewayOwner } from "../../feishu/gateway-lock.ts";
15
+ import { isForeignWorkspace, readOwnerWorkspace, resolveInstanceDir, writeOwnerWorkspace } from "../../feishu/instance.ts";
16
+ import {
17
+ DEFAULT_INSTANCE_NAME,
18
+ instanceDirForName,
19
+ instanceConfigPath,
20
+ instanceNameFromDir,
21
+ isValidInstanceName,
22
+ listInstances,
23
+ readInstanceConfig,
24
+ } from "../../feishu/instances.ts";
25
+ import { FeishuMessageHandler } from "../../feishu/message-handler.ts";
26
+ import { runSetup, uiConfirm } from "./setup.ts";
27
+ import {
28
+ RUNTIME_CONFIG_KEYS,
29
+ clearRuntimeOverrides,
30
+ formatRuntimeConfig,
31
+ getRuntimeOverrides,
32
+ setRuntimeConfig,
33
+ } from "../../feishu/runtime-config.ts";
34
+ import { BotUnavailableError, FeishuTransport } from "../../feishu/transport.ts";
35
+ import { withBackoffRetry } from "../../feishu/retry.ts";
36
+ import type { FeishuConfig, FeishuStatus } from "../../feishu/types.ts";
37
+ import { createCardActionHandler } from "../../feishu/card-actions.ts";
38
+ import { LearnApprovalClient } from "../../feishu/learn-approval.ts";
39
+ import { resolveCardTarget } from "../../feishu/reply-card.ts";
40
+ import { installExitFlush } from "../../feishu/live-cards.ts";
41
+ import { daemonCommand, daemonSpec } from "../../feishu/daemon-spec.ts";
42
+ import { ackRestartIfPending, requestRestart, type RestartTrigger } from "../../feishu/restart.ts";
43
+ import { PiConversationRuntime, handlePiMessageEnd } from "./PiConversationRuntime.ts";
44
+
45
+ /**
46
+ * Pi Runtime 适配器的扩展入口(薄 PI bootstrap):
47
+ * 只保留 Pi 相关的启动/命令/daemon/工具注册逻辑,
48
+ * 其余飞书逻辑全部在 src/feishu 公共层。
49
+ *
50
+ * @param options.extensionPath 当前扩展入口文件路径(daemon 用 -e 重新加载它)。
51
+ */
52
+ export default function createPiFeishuExtension(pi: ExtensionAPI, options?: { extensionPath?: string }) {
53
+ const extensionEntry = options?.extensionPath || fileURLToPath(import.meta.url);
54
+ // 启动重试的退避序列:4 次重试、累计约 15s。刻意压在网关锁 stale 阈值(30s)以内,
55
+ // 这样重试期间不需要额外心跳也不会被别的实例抢走锁。
56
+ const START_RETRY_DELAYS_MS = [1000, 2000, 4000, 8000];
57
+ // Pi 进程使用 Pi 自己的配置/状态/记录文件(默认即 Pi,显式声明便于维护)
58
+ setRuntimeSource(PI_SOURCE);
59
+ if (process.env[CHILD_SESSION_ENV] === "1") {
60
+ return;
61
+ }
62
+
63
+ // 进程被 kill(重启桥接)时,把在册的「回复中」卡片翻成「已停止」并写明原因。
64
+ // 少了这一步,飞书侧会永久停在「正在回复…」(2026-10-14 事故)。
65
+ installExitFlush();
66
+
67
+ // 模型可读写白名单配置(热更新 + 落盘)
68
+ registerFeishuConfigTools(pi);
69
+
70
+ // 注意:不要在这里调用 hideFeishuConfigTools(pi)。getActiveTools()/setActiveTools()
71
+ // 是会话级 API,在扩展加载期(session_start 之前)调用会抛错,导致后续
72
+ // /feishu 命令注册等逻辑全部不执行。隐藏逻辑统一放在 session_start 里。
73
+
74
+ let transport: FeishuTransport | undefined;
75
+ let gatewayLock: GatewayLockHandle | undefined;
76
+ const bridgeStore = new FeishuBridgeStore();
77
+ const delivery = new FeishuDelivery(() => transport);
78
+ const bridge = new FeishuBridgeRuntime(bridgeStore, delivery);
79
+ const initialConfig = loadConfig();
80
+ const conversations = new PiConversationRuntime(process.cwd(), bridge, {
81
+ promptNotifySec: initialConfig?.promptNotifySec,
82
+ promptTimeoutSec: initialConfig?.promptTimeoutSec,
83
+ });
84
+ const messageHandler = new FeishuMessageHandler(conversations, () => transport, bridgeStore, {
85
+ /**
86
+ * 飞书里 `/restart`:换一份新代码继续跑,会话上下文不丢。
87
+ *
88
+ * 只在 daemon 里允许 —— TUI 里重启桥接是 `/feishu restart`,那条路径完全在进程内,
89
+ * 走这里反而会把用户的交互式会话一起杀掉。
90
+ */
91
+ restart: async (request) => {
92
+ const activeTransport = transport;
93
+ if (!activeTransport) return { ok: false, error: "飞书连接未就绪,无法重启。" };
94
+ if (process.env.PI_FEISHU_DAEMON !== "1") {
95
+ return { ok: false, error: "当前 Pi 不是桥接 daemon。在 Pi 终端里请用 `/feishu restart`。" };
96
+ }
97
+ const trigger: RestartTrigger = request.trigger;
98
+ const result = await requestRestart({
99
+ transport: activeTransport,
100
+ trigger,
101
+ extensionPath: extensionEntry,
102
+ cwd: process.cwd(),
103
+ hasActiveRun: request.hasActiveRun,
104
+ force: request.force,
105
+ });
106
+ if (!result.ok) return result;
107
+ // 卡片已发出、worker 已在等我们死:留 1.2s 让消息落库,然后**发 SIGTERM 给自己**而不是
108
+ // 直接 process.exit —— 只有信号路径会经过 installExitFlush(),把别的会话在跑的「回复中」
109
+ // 卡片统一收尾;直接 exit 会让那些卡永久停在「正在回复…」(2026-10-14 事故同因)。
110
+ // launcher 一起收,否则 `bash -lc 'tail -f /dev/null | exec pi …'` 的壳会残留。
111
+ setTimeout(() => {
112
+ terminateLauncherParent();
113
+ process.kill(process.pid, "SIGTERM");
114
+ }, 1200);
115
+ return result;
116
+ },
117
+ });
118
+
119
+ // 扩展 UI 输出回传:knowledge-flow 等 Pi 扩展的 ctx.ui.notify 走这里回到飞书会话。
120
+ // 以进程级 sink 为准:每个飞书会话各自的 DefaultResourceLoader 有独立的 pi.events 总线,
121
+ // 而 notify 发生在会话内的扩展实例上(详见 ui-notify.ts 的说明)。
122
+ setFeishuUiNotifySink((payload) => conversations.pushUiNotify(payload));
123
+ // 选择题卡片发送器:模型调 feishu_ask 时,把卡片发到该会话。
124
+ // 走 resolveCardTarget:普通会话平铺(避免与回答卡归成同一个回复簇、把先到的卡挤掉),
125
+ // 话题群/回复链必须 reply(create 会另开一个话题)。
126
+ conversations.setAskSender(async (key, card) => {
127
+ const activeTransport = transport;
128
+ if (!activeTransport) throw new Error("飞书连接未启动");
129
+ const route = bridgeStore.getRoute(key);
130
+ if (!route) throw new Error("找不到该会话的路由");
131
+ const target = resolveCardTarget(route);
132
+ // 返回卡片消息 ID:超时后要拿它 patch 同一张卡
133
+ if ("chatId" in target && target.chatId) return activeTransport.createCard(target.chatId, card);
134
+ if (!route.lastMessageId) throw new Error("找不到该会话最近的消息");
135
+ return activeTransport.replyCard(route.lastMessageId, card);
136
+ });
137
+ // 超时后把提问卡片原地刷成「已超时」,避免留一张还能点、点了没反应的僵尸卡
138
+ conversations.setAskCardUpdater(async (messageId, card) => {
139
+ const activeTransport = transport;
140
+ if (!activeTransport) throw new Error("飞书连接未启动");
141
+ await activeTransport.updateCard(messageId, card);
142
+ });
143
+ // 进化审批:把 /learn 的落地变成一道必须过的飞书审批。
144
+ // 审批单的审批人、表单结构在飞书审批定义里;这里只负责拿配置与发起人。
145
+ // 提交与查询拆开:提交只建单、立即返回实例号,绝不在一次工具调用里等审批人。
146
+ const buildLearnApprovalClient = (): LearnApprovalClient => {
147
+ const activeTransport = transport;
148
+ if (!activeTransport) throw new Error("飞书连接未启动,无法发起审批");
149
+ const approval = loadConfig()?.learnApproval;
150
+ if (!approval) {
151
+ throw new Error(
152
+ "未配置进化审批:请在飞书审批后台建一个带「多行文本」控件的审批,"
153
+ + `再把它的 approval_code 写进 ${CONFIG_PI_PATH} 的 learnApproval.approvalCode`,
154
+ );
155
+ }
156
+ return new LearnApprovalClient({
157
+ api: { request: (args) => activeTransport.requestApi(args) },
158
+ config: approval,
159
+ log: (event, data) => debugLog(event, (data ?? {}) as Record<string, unknown>),
160
+ });
161
+ };
162
+
163
+ // 【提交】只建单:发起人取自该会话最近一条消息的发送者(审批单里要显示是谁要进化)
164
+ conversations.setLearnApprovalSubmitter(async (key, body) => {
165
+ const client = buildLearnApprovalClient();
166
+ const senderOpenId = bridgeStore.getRoute(key)?.senderOpenId;
167
+ if (!senderOpenId) throw new Error("拿不到该会话的发送人 open_id,无法发起审批");
168
+ return client.create({ body, applicantOpenId: senderOpenId });
169
+ });
170
+
171
+ // 【查询】按实例号查一次状态:给「超时 / 被打断后用同一张单续查」用,不重发
172
+ conversations.setLearnApprovalQuerier(async (_key, instanceCode) => {
173
+ return buildLearnApprovalClient().query(instanceCode);
174
+ });
175
+ // 事件总线仅作为同总线场景(扩展与桥接在同一 loader 下)的补充
176
+ try {
177
+ (pi as any).events?.on?.(FEISHU_UI_NOTIFY_EVENT, (payload: FeishuUiNotifyPayload) => {
178
+ conversations.pushUiNotify(payload);
179
+ });
180
+ } catch (error) {
181
+ debugLog("feishu.ui.notify_bridge_failed", {
182
+ error: error instanceof Error ? error.message : String(error),
183
+ });
184
+ }
185
+
186
+ const STATUS_KEY = "feishu-connection";
187
+ const STATUS_REFRESH_MS = 2_000;
188
+ let uiRef: { setStatus?: (key: string, text: string | undefined) => void } | undefined;
189
+ let lastStatusText: string | undefined;
190
+ /** 裸开保护:本目录不是全局配置所属工作区时,记下 owner 的 cwd(用于状态栏与启动提示)。 */
191
+ let foreignWorkspaceOwner: string | undefined;
192
+ let statusRefreshTimer: NodeJS.Timeout | undefined;
193
+ const buildTag = process.env.FEISHU_EXT_DEV === "1" ? " [DEV]" : "";
194
+
195
+ function setStatusText(text: string | undefined) {
196
+ if (lastStatusText === text) return;
197
+ lastStatusText = text;
198
+ uiRef?.setStatus?.(STATUS_KEY, text);
199
+ }
200
+
201
+ function updateStatus(status: FeishuStatus) {
202
+ const cfg = loadConfig();
203
+ const brand = cfg?.domain === "lark" ? "Lark" : "Feishu";
204
+ setStatusText(statusText(brand, status));
205
+ }
206
+
207
+ function currentGatewayOwner() {
208
+ return readGatewayOwner(loadConfig()?.appId);
209
+ }
210
+
211
+ function withBuildTag(text: string) {
212
+ return `${text}${buildTag}`;
213
+ }
214
+
215
+ function statusText(brand: "Feishu" | "Lark", status: FeishuStatus) {
216
+ const labels: Record<FeishuStatus, string> = {
217
+ "not configured": "未配置 / Not configured",
218
+ connecting: "连接中 / Connecting",
219
+ connected: "已连接 / Connected",
220
+ disconnected: "已断开 / Disconnected",
221
+ owned: "连接被占用 / In use by another process",
222
+ "bot unavailable": "机器人不可用 / Bot unavailable",
223
+ };
224
+ return withBuildTag(`${brand}: ${labels[status]}`);
225
+ }
226
+
227
+ /** 单实例一行状态:本进程连接优先,其次网关锁(= detached daemon 的心跳)。 */
228
+ function instanceStateBrief(dir: string, cfg: ReturnType<typeof readInstanceConfig>) {
229
+ if (!cfg) return { icon: "○", text: "未配置" };
230
+ if (dir === currentInstanceDir() && transport?.isRunning()) return { icon: "●", text: "已连接(进程内)" };
231
+ const owner = readGatewayOwner(cfg.appId);
232
+ if (!owner) return { icon: "○", text: "未运行" };
233
+ if (owner.status === "connected") return { icon: "●", text: `已连接(daemon ${owner.pid})` };
234
+ if (owner.status === "starting") return { icon: "◐", text: `启动中(daemon ${owner.pid})` };
235
+ return { icon: "◌", text: `${owner.status}(daemon ${owner.pid})` };
236
+ }
237
+
238
+ /** 多实例时状态栏改成一行概览;只有一个实例时返回 undefined(沿用单实例文案)。 */
239
+ function multiInstanceStatusText() {
240
+ const instances = listInstances(process.cwd()).filter((instance) => instance.configured);
241
+ if (instances.length < 2) return undefined;
242
+ const current = currentInstanceDir();
243
+ const segments = instances.map((instance) => {
244
+ const name = instanceNameFromDir(process.cwd(), instance.dir) || instance.name;
245
+ const { icon, text } = instanceStateBrief(instance.dir, readInstanceConfig(instance.dir));
246
+ return `${icon} ${name}${instance.dir === current ? "*" : ""} ${text}`;
247
+ });
248
+ const prefix = foreignWorkspaceOwner ? `(属 ${foreignWorkspaceOwner}) ` : "";
249
+ return withBuildTag(`${prefix}Feishu: ${segments.join(" | ")}`);
250
+ }
251
+
252
+ function refreshStatusFromState() {
253
+ const multi = multiInstanceStatusText();
254
+ if (multi) {
255
+ setStatusText(multi);
256
+ return;
257
+ }
258
+ const cfg = loadConfig();
259
+ const brand = cfg?.domain === "lark" ? "Lark" : "Feishu";
260
+ if (!cfg) {
261
+ setStatusText(statusText(brand, "not configured"));
262
+ return;
263
+ }
264
+ // 裸开保护:不沿用锁 owner 的 connected(那是另一个工作区的连接),
265
+ // 固定显示归属方,避免误判「本工作区已连上机器人」。
266
+ if (foreignWorkspaceOwner) {
267
+ setStatusText(`${brand}: 连接属于其他工作区 / Owned by ${foreignWorkspaceOwner}`);
268
+ return;
269
+ }
270
+ if (transport?.isRunning()) {
271
+ setStatusText(statusText(brand, "connected"));
272
+ return;
273
+ }
274
+ const owner = currentGatewayOwner();
275
+ if (owner?.status === "connected") {
276
+ setStatusText(statusText(brand, "connected"));
277
+ } else if (owner?.status === "starting") {
278
+ setStatusText(statusText(brand, "connecting"));
279
+ } else if (owner) {
280
+ setStatusText(statusText(brand, "disconnected"));
281
+ } else {
282
+ setStatusText(statusText(brand, "disconnected"));
283
+ }
284
+ }
285
+
286
+ function startStatusRefresh() {
287
+ if (statusRefreshTimer) return;
288
+ refreshStatusFromState();
289
+ statusRefreshTimer = setInterval(refreshStatusFromState, STATUS_REFRESH_MS);
290
+ statusRefreshTimer.unref?.();
291
+ }
292
+
293
+ function stopStatusRefresh() {
294
+ if (!statusRefreshTimer) return;
295
+ clearInterval(statusRefreshTimer);
296
+ statusRefreshTimer = undefined;
297
+ }
298
+
299
+ function clearStatus() {
300
+ stopStatusRefresh();
301
+ lastStatusText = undefined;
302
+ uiRef?.setStatus?.(STATUS_KEY, undefined);
303
+ }
304
+
305
+ pi.on("message_end", async (event, ctx) => {
306
+ handlePiMessageEnd(bridge, ctx.sessionManager.getSessionId(), undefined, event.message);
307
+ });
308
+
309
+ async function start(config?: FeishuConfig, options: { takeover?: boolean } = {}) {
310
+ if (transport?.isRunning()) {
311
+ updateStatus("connected");
312
+ return "already";
313
+ }
314
+ const cfg = config || loadConfig();
315
+ if (!cfg) {
316
+ updateStatus("not configured");
317
+ throw new Error(`Missing config. Run /feishu setup first. 配置不存在,请先运行 /feishu setup。`);
318
+ }
319
+ updateStatus("connecting");
320
+ const lockResult = await acquireGatewayLock(process.cwd(), Boolean(options.takeover), cfg.appId);
321
+ if (lockResult.status === "busy") {
322
+ updateStatus("owned");
323
+ return { status: "owned" as const, owner: lockResult.owner };
324
+ }
325
+ // 拿锁成功 = 本目录正式成为这份实例的属主工作区(写进 owner-workspace.json)。
326
+ // 这份记录让「裸开保护」在锁空闲时也能分辨归属:否则本工作区 daemon 一停,
327
+ // 别的目录裸开就会把连接接过去(锁里没有 owner 可对比)。
328
+ writeOwnerWorkspace(process.cwd());
329
+ gatewayLock = lockResult.handle;
330
+ gatewayLock.setOnLost(async () => {
331
+ await transport?.stop();
332
+ transport = undefined;
333
+ gatewayLock = undefined;
334
+ updateStatus(loadConfig() ? "owned" : "not configured");
335
+ if (process.env.PI_FEISHU_DAEMON === "1") {
336
+ terminateLauncherParent();
337
+ process.exit(0);
338
+ }
339
+ });
340
+ transport = new FeishuTransport(cfg, (msg) => messageHandler.handle(msg), createCardActionHandler(conversations, () => transport));
341
+ const startedTransport = transport;
342
+ try {
343
+ // 启动期一次性初始化最容易撞上瞬时断连(ECONNRESET / socket hang up):
344
+ // 之前这里一次失败就 release 锁并 throw,daemon 随 process.exit(1) 消失、不重试。
345
+ // 现在按 1s→2s→4s→8s 退避重试(累计约 15s,远小于 30s 的锁 stale 阈值),
346
+ // 凭证类错误(403 / 999xxxxx)不是「可重试」,仍然立即失败退出。
347
+ await withBackoffRetry(() => startedTransport.start(), {
348
+ delaysMs: START_RETRY_DELAYS_MS,
349
+ onRetry: (error, attempt, delayMs) => {
350
+ const msg = error instanceof Error ? error.message : String(error);
351
+ console.error(`[feishu] 启动失败(${msg}),${delayMs}ms 后第 ${attempt} 次重试`);
352
+ updateStatus("connecting");
353
+ },
354
+ });
355
+ gatewayLock.startHeartbeat();
356
+ await gatewayLock.update("connected");
357
+ updateStatus("connected");
358
+ // 刚接过网关锁 = 很可能是一次 /restart 的结果:把上一张「重启中」卡片改成终态。
359
+ // 失败不影响连接(回执只是体验),所以不 await 抛错。
360
+ void ackRestartIfPending(startedTransport).catch(() => undefined);
361
+ return "started";
362
+ } catch (error) {
363
+ updateStatus(error instanceof BotUnavailableError ? "bot unavailable" : "disconnected");
364
+ await gatewayLock.release();
365
+ gatewayLock = undefined;
366
+ transport = undefined;
367
+ throw error;
368
+ }
369
+ }
370
+
371
+ async function stop() {
372
+ await transport?.stop();
373
+ transport = undefined;
374
+ await gatewayLock?.release();
375
+ gatewayLock = undefined;
376
+ updateStatus(loadConfig() ? "disconnected" : "not configured");
377
+ }
378
+
379
+ function formatOwner(owner: GatewayOwner | undefined) {
380
+ if (!owner) return "none";
381
+ return `pid=${owner.pid}, status=${owner.status}, startedAt=${owner.startedAt}, heartbeatAt=${owner.heartbeatAt}, cwd=${owner.cwd}`;
382
+ }
383
+
384
+ function notifyDaemonStartResult(ctx: any, result: Awaited<ReturnType<typeof startDaemon>>) {
385
+ if (result.status === "busy") {
386
+ ctx.ui.notify(withBuildTag(`飞书连接已在后台运行。\n${formatOwner(result.owner)}`), "info");
387
+ return;
388
+ }
389
+ const where = "dir" in result && result.dir ? `\n实例目录: ${result.dir}` : "";
390
+ const log = "logPath" in result && result.logPath ? result.logPath : DAEMON_LOG_PATH;
391
+ ctx.ui.notify(withBuildTag(`飞书连接已启动。\nGateway pid=${result.pid}${where}\nLog: ${log}`), "info");
392
+ }
393
+
394
+ // daemon 启动形状来自 feishu/daemon-spec.ts:/restart 的 worker 必须用完全相同的
395
+ // 参数拉起新进程,否则 looksLikeFeishuDaemon() 认不出它(见该文件注释)。
396
+ function daemonSpecForEntry() {
397
+ return daemonSpec(extensionEntry);
398
+ }
399
+
400
+ function daemonCommandForEntry() {
401
+ return daemonCommand(daemonSpecForEntry());
402
+ }
403
+
404
+ // ---------- 多实例(一个工作区多个机器人) ----------
405
+ //
406
+ // 架构基线不变:一个实例目录 = 一个自建应用 = 一个 daemon(见 feishu/instances.ts 顶部说明)。
407
+ // 这里只把「启动/停止」从只认当前实例目录,扩到能指定任意实例目录。
408
+
409
+ /** 当前进程绑定的实例目录(TUI 未设 FEISHU_DATA_DIR 时 = `<工作区>/.pi/feishu`)。 */
410
+ function currentInstanceDir() {
411
+ return resolveInstanceDir();
412
+ }
413
+
414
+ /**
415
+ * 实例名 → 实例目录。
416
+ * 未给名字 / `default` → 当前实例目录;名字非法 → `undefined`。
417
+ */
418
+ function dirForInstanceName(name?: string): string | undefined {
419
+ const trimmed = (name || "").trim();
420
+ if (!trimmed || trimmed === DEFAULT_INSTANCE_NAME) return currentInstanceDir();
421
+ if (!isValidInstanceName(trimmed)) return undefined;
422
+ return instanceDirForName(process.cwd(), trimmed);
423
+ }
424
+
425
+ function instanceDaemonLogPath(dir: string) {
426
+ return dir === currentInstanceDir() ? DAEMON_LOG_PATH : join(dir, "daemon.log");
427
+ }
428
+
429
+ async function startDaemon(takeover = false, dir: string = currentInstanceDir()) {
430
+ return withDaemonSpawnLock(async () => {
431
+ const cfg = readInstanceConfig(dir);
432
+ if (!cfg) {
433
+ throw new Error(
434
+ `实例目录缺少配置:${dir}\n先用 /feishu bots add <名字> 新建一个机器人,或 /feishu setup 配当前实例。`,
435
+ );
436
+ }
437
+ const sameAsCurrent = dir === currentInstanceDir();
438
+ let owner = readGatewayOwner(cfg.appId);
439
+ if (owner && owner.pid !== process.pid && !takeover) {
440
+ return { status: "busy" as const, owner };
441
+ }
442
+
443
+ // 本进程自己就是这个实例的持有者(daemon 里跑 /feishu start)时,先停掉自己的连接。
444
+ if (sameAsCurrent && (owner?.pid === process.pid || transport?.isRunning())) {
445
+ await stop();
446
+ } else if (owner && takeover) {
447
+ try { process.kill(owner.pid, "SIGTERM"); } catch {}
448
+ await sleep(800);
449
+ }
450
+
451
+ // Re-check while holding the spawn lock. Another TUI may have started it
452
+ // while this process was waiting for the lock.
453
+ owner = readGatewayOwner(cfg.appId);
454
+ if (owner && owner.pid !== process.pid && !takeover) {
455
+ return { status: "busy" as const, owner };
456
+ }
457
+
458
+ reapDetachedDaemonProcesses({ keepPids: [process.pid], extensionPath: extensionEntry });
459
+ // 当前实例沿用 ensureRoot()(含旧全局数据搬迁);其它实例只建目录。
460
+ if (sameAsCurrent) ensureRoot();
461
+ else mkdirSync(dir, { recursive: true });
462
+ const logPath = instanceDaemonLogPath(dir);
463
+ const logFd = openSync(logPath, "a");
464
+ // FEISHU_DATA_DIR 是 daemon 认实例的唯一依据:必须显式传,不能靠继承(TUI 自己可能没设)。
465
+ const childEnv = { ...process.env, PI_FEISHU_DAEMON: "1", FEISHU_DATA_DIR: dir };
466
+ let child: ChildProcess;
467
+ if (process.platform === "win32") {
468
+ // Windows 上 spawn("bash", ...) 可能解析到 WSL 的 bash.exe(而非 Git Bash),
469
+ // 导致 daemon 在 WSL 环境里启动、路径和凭据全部错乱后立即退出。
470
+ // 因此 Windows 直接用 node 拉起 Pi CLI 入口,绕开 bash 管道。
471
+ const npmPrefix = process.env.APPDATA
472
+ ? `${process.env.APPDATA}\\npm`
473
+ : `${process.env.USERPROFILE}\\AppData\\Roaming\\npm`;
474
+ const piCliEntry = process.env.PI_CLI_ENTRY
475
+ || `${npmPrefix}\\node_modules\\@earendil-works\\pi-coding-agent\\dist\\cli.js`;
476
+ const { args } = daemonSpecForEntry();
477
+ child = spawn("node", [piCliEntry, ...args], {
478
+ detached: true,
479
+ cwd: process.cwd(),
480
+ env: childEnv,
481
+ stdio: ["pipe", logFd, logFd],
482
+ });
483
+ // 保持 stdin 打开,等价于 Linux 侧 `tail -f /dev/null |` 的作用,
484
+ // 否则 pi --mode rpc 会在 stdin EOF 后退出。
485
+ if (child.stdin) (child.stdin as unknown as Readable).resume();
486
+ } else {
487
+ child = spawn("bash", ["-lc", daemonCommandForEntry()], {
488
+ detached: true,
489
+ cwd: process.cwd(),
490
+ env: childEnv,
491
+ stdio: ["ignore", logFd, logFd],
492
+ });
493
+ }
494
+ child.unref();
495
+
496
+ await sleep(1500);
497
+ return {
498
+ status: "started" as const,
499
+ pid: child.pid,
500
+ owner: readGatewayOwner(cfg.appId),
501
+ dir,
502
+ logPath,
503
+ };
504
+ });
505
+ }
506
+
507
+ async function stopDaemon(dir: string = currentInstanceDir()) {
508
+ const owner = readGatewayOwner(readInstanceConfig(dir)?.appId);
509
+ if (!owner) {
510
+ reapDetachedDaemonProcesses({ extensionPath: extensionEntry });
511
+ return { status: "none" as const };
512
+ }
513
+ if (owner.pid === process.pid) {
514
+ await stop();
515
+ reapDetachedDaemonProcesses({ keepPids: [process.pid], extensionPath: extensionEntry });
516
+ return { status: "stopped-current" as const };
517
+ }
518
+ try {
519
+ process.kill(owner.pid, "SIGTERM");
520
+ await sleep(800);
521
+ reapDetachedDaemonProcesses({ extensionPath: extensionEntry });
522
+ return { status: "stopped" as const, owner };
523
+ } catch (error) {
524
+ return { status: "error" as const, owner, error };
525
+ }
526
+ }
527
+
528
+ async function restartDaemon(dir: string = currentInstanceDir()) {
529
+ const stopped = await stopDaemon(dir);
530
+ if (stopped.status === "error") return { status: "error" as const, stopped };
531
+ const started = await startDaemon(true, dir);
532
+ return { status: "restarted" as const, stopped, started };
533
+ }
534
+
535
+ /** `/feishu bots` 的列表视图:名字、appId、连接状态(看网关锁)、目录。 */
536
+ function describeInstances() {
537
+ const current = currentInstanceDir();
538
+ const instances = listInstances(process.cwd());
539
+ if (!instances.length) return "还没有任何飞书实例。用 /feishu setup 配第一个,或 /feishu bots add <名字> 加第二个。";
540
+ const lines = instances.map((instance) => {
541
+ const marker = instance.dir === current ? "*" : " ";
542
+ const name = instanceNameFromDir(process.cwd(), instance.dir) || instance.name;
543
+ if (!instance.configured) return `${marker} ${name}\t未配置\t${instance.dir}`;
544
+ const owner = readGatewayOwner(instance.appId);
545
+ const state = owner
546
+ ? `${owner.status}(pid=${owner.pid}, 心跳 ${owner.heartbeatAt.slice(11, 19)})`
547
+ : "未运行";
548
+ const port = instance.webhookPort ? ` port=${instance.webhookPort}` : "";
549
+ return `${marker} ${name}\t${mask(instance.appId || "")}\t${state}\tautoStart=${instance.autoStart ? "on" : "off"}${port}\t${instance.dir}`;
550
+ });
551
+ return [
552
+ `飞书实例(* = 当前 TUI 绑定的那个):`,
553
+ "``name appId 状态 选项 目录``",
554
+ ...lines,
555
+ ].join("\n");
556
+ }
557
+
558
+ pi.registerCommand("feishu", {
559
+ description: "Feishu/Lark: setup, start, stop, restart, status, bots, debug, autostart, reset, tools on|off, progress",
560
+ handler: async (args, ctx) => {
561
+ uiRef = ctx.ui as any;
562
+ const parts = args.trim().split(/\s+/).filter(Boolean);
563
+ const cmd = (parts[0] || "status").toLowerCase();
564
+ const cmdArg = (parts[1] || "").toLowerCase();
565
+ const cmdArg2 = (parts[2] || "").toLowerCase();
566
+ /** 解析 `/feishu bots <action> <名字>` 的目标目录;非法名字直接提示并返回 undefined。 */
567
+ const instanceDirArg = (name: string): string | undefined => {
568
+ const dir = dirForInstanceName(name);
569
+ if (!dir) {
570
+ ctx.ui.notify(
571
+ `实例名不合法:${name || "(空)"}。只允许小写字母/数字/连字符,不能是 default。`,
572
+ "error",
573
+ );
574
+ return undefined;
575
+ }
576
+ return dir;
577
+ };
578
+ try {
579
+ if (cmd === "bots" || cmd === "instances") {
580
+ const action = cmdArg;
581
+ const name = cmdArg2;
582
+ if (!action || action === "list") {
583
+ ctx.ui.notify(describeInstances(), "info");
584
+ return;
585
+ }
586
+ if (action === "add") {
587
+ if (!name || !isValidInstanceName(name)) {
588
+ ctx.ui.notify("用法:/feishu bots add <名字>(小写字母/数字/连字符,不能是 default)", "warning");
589
+ return;
590
+ }
591
+ const dir = instanceDirForName(process.cwd(), name);
592
+ if (readInstanceConfig(dir)) {
593
+ ctx.ui.notify(`${name} 已经配置过了(${dir})。要重连用 /feishu bots restart ${name}。`, "warning");
594
+ return;
595
+ }
596
+ const configToStart = await runSetup(ctx, { configPath: instanceConfigPath(dir), dir });
597
+ if (configToStart) {
598
+ notifyDaemonStartResult(ctx, await startDaemon(false, dir));
599
+ }
600
+ ctx.ui.notify(describeInstances(), "info");
601
+ return;
602
+ }
603
+ if (!name) {
604
+ ctx.ui.notify(`用法:/feishu bots ${action} <名字>。先 /feishu bots 看有哪些实例。`, "warning");
605
+ return;
606
+ }
607
+ const dir = instanceDirArg(name);
608
+ if (!dir) return;
609
+ if (action === "start") {
610
+ notifyDaemonStartResult(ctx, await startDaemon(false, dir));
611
+ return;
612
+ }
613
+ if (action === "restart") {
614
+ const result = await restartDaemon(dir);
615
+ if (result.status === "error") {
616
+ ctx.ui.notify(`实例 ${name} 重启失败:${String((result.stopped as any)?.error ?? "")}`, "error");
617
+ return;
618
+ }
619
+ notifyDaemonStartResult(ctx, result.started);
620
+ return;
621
+ }
622
+ if (action === "stop") {
623
+ const result = await stopDaemon(dir);
624
+ ctx.ui.notify(result.status === "none" ? `实例 ${name} 未在运行。` : `实例 ${name} 已停止。`, "info");
625
+ return;
626
+ }
627
+ if (action === "rm" || action === "remove") {
628
+ if (dir === currentInstanceDir()) {
629
+ ctx.ui.notify("默认实例不能删除,用 /feishu reset 清配置。", "warning");
630
+ return;
631
+ }
632
+ const ok = await uiConfirm(
633
+ ctx,
634
+ `确认删除实例 ${name}?会停掉它的 daemon 并删除 ${dir}(该机器人的飞书会话映射、去重记录一并没了;pi 会话历史保留)。`,
635
+ false,
636
+ );
637
+ if (!ok) {
638
+ ctx.ui.notify("已取消。", "info");
639
+ return;
640
+ }
641
+ await stopDaemon(dir);
642
+ rmSync(dir, { recursive: true, force: true });
643
+ ctx.ui.notify(`实例 ${name} 已删除。`, "info");
644
+ ctx.ui.notify(describeInstances(), "info");
645
+ return;
646
+ }
647
+ ctx.ui.notify("用法:/feishu bots [add|start|stop|restart|rm] <名字>", "warning");
648
+ return;
649
+ }
650
+ if (cmd === "setup") {
651
+ const configToStart = await runSetup(ctx);
652
+ if (configToStart) {
653
+ writeJson(CONFIG_PI_PATH, configToStart);
654
+ notifyDaemonStartResult(ctx, await startDaemon(false));
655
+ }
656
+ refreshStatusFromState();
657
+ return;
658
+ }
659
+ if (cmd === "start") {
660
+ notifyDaemonStartResult(ctx, await startDaemon(false));
661
+ refreshStatusFromState();
662
+ return;
663
+ }
664
+ if (cmd === "stop") {
665
+ const result = await stopDaemon();
666
+ if (result.status === "error") {
667
+ ctx.ui.notify(`停止飞书连接失败:${result.error instanceof Error ? result.error.message : String(result.error)}\nOwner: ${formatOwner(result.owner)}`, "error");
668
+ refreshStatusFromState();
669
+ return;
670
+ }
671
+ ctx.ui.notify(result.status === "none" ? "飞书连接未在运行。" : "飞书连接已停止。", "info");
672
+ refreshStatusFromState();
673
+ return;
674
+ }
675
+ if (cmd === "restart") {
676
+ const result = await restartDaemon();
677
+ if (result.status === "error") {
678
+ const stopped = result.stopped;
679
+ ctx.ui.notify(`飞书连接重启失败:${stopped.error instanceof Error ? stopped.error.message : String(stopped.error)}\nOwner: ${formatOwner(stopped.owner)}`, "error");
680
+ refreshStatusFromState();
681
+ return;
682
+ }
683
+ ctx.ui.notify(`飞书连接已重启,最新代码和配置已生效。\nOwner: ${formatOwner(result.started.owner)}\nLog: ${DAEMON_LOG_PATH}`, "info");
684
+ refreshStatusFromState();
685
+ return;
686
+ }
687
+ if (cmd === "reset") {
688
+ const ok = await uiConfirm(
689
+ ctx,
690
+ "确认重置飞书扩展?会删除配置和会话映射,但保留所有会话历史。 / Reset Feishu extension? This deletes config and conversation mappings, but keeps all session history.",
691
+ false,
692
+ );
693
+ if (!ok) {
694
+ ctx.ui.notify("Reset cancelled / 已取消重置", "info");
695
+ return;
696
+ }
697
+ await stopDaemon();
698
+ removePath(CONFIG_PI_PATH);
699
+ removePath(STATE_PI_PATH);
700
+ removePath(DEDUPE_PI_PATH);
701
+ removePath(`${DEDUPE_PI_PATH}.lock`);
702
+ removePath(BRIDGE_PI_PATH);
703
+ conversations.resetMemory();
704
+ messageHandler.reset();
705
+ ensureRoot();
706
+ updateStatus("not configured");
707
+ ctx.ui.notify(
708
+ "Feishu extension reset. Session history was kept. Run /feishu setup. / 飞书扩展已重置,会话历史已保留,请运行 /feishu setup。",
709
+ "info",
710
+ );
711
+ refreshStatusFromState();
712
+ return;
713
+ }
714
+ if (cmd === "status") {
715
+ refreshStatusFromState();
716
+ const cfg = loadConfig();
717
+ const owner = gatewayLock?.owner || currentGatewayOwner();
718
+ ctx.ui.notify(
719
+ [
720
+ describeInstances(),
721
+ "",
722
+ `Status: ${lastStatusText || (loadConfig() ? "Feishu: disconnected" : "Feishu: not configured")}`,
723
+ `Gateway owner: ${formatOwner(owner)}`,
724
+ `Config: ${cfg ? `${cfg.domain}, appId=${mask(cfg.appId)}, groupPolicy=${cfg.groupPolicy}, autoStart=${cfg.autoStart !== false}` : "missing"}`,
725
+ `Path: ${CONFIG_PI_PATH}`,
726
+ `Gateway lock: ${gatewayLockPath()}`,
727
+ `Debug: ${DEBUG_PI_LOG_PATH}`,
728
+ `Gateway log: ${DAEMON_LOG_PATH}`,
729
+ ].join("\n"),
730
+ "info",
731
+ );
732
+ return;
733
+ }
734
+ if (cmd === "debug") {
735
+ if (!existsSync(DEBUG_PI_LOG_PATH)) {
736
+ ctx.ui.notify("还没有飞书调试日志。请先在飞书里发一条消息给机器人。", "info");
737
+ return;
738
+ }
739
+ const lines = readFileSync(DEBUG_PI_LOG_PATH, "utf8").trim().split("\n").slice(-20);
740
+ ctx.ui.notify(lines.join("\n"), "info");
741
+ return;
742
+ }
743
+ if (cmd === "autostart") {
744
+ const cfg = loadConfig();
745
+ if (!cfg) {
746
+ ctx.ui.notify("Missing config. Run /feishu setup first.", "warning");
747
+ return;
748
+ }
749
+ cfg.autoStart = cfg.autoStart === false;
750
+ writeJson(CONFIG_PI_PATH, cfg);
751
+ ctx.ui.notify(cfg.autoStart ? "飞书自动启动已开启。" : "飞书自动启动已关闭。", "info");
752
+ refreshStatusFromState();
753
+ return;
754
+ }
755
+ if (cmd === "tools") {
756
+ const active = pi.getActiveTools();
757
+ const enabled = FEISHU_CONFIG_TOOLS.every((t) => active.includes(t));
758
+ if (cmdArg === "on") {
759
+ if (enabled) {
760
+ ctx.ui.notify("飞书配置工具已启用。", "info");
761
+ return;
762
+ }
763
+ pi.setActiveTools([...active, ...FEISHU_CONFIG_TOOLS]);
764
+ ctx.ui.notify("飞书配置工具已启用(仅当前会话生效)。", "info");
765
+ return;
766
+ }
767
+ if (cmdArg === "off") {
768
+ if (!enabled) {
769
+ ctx.ui.notify("飞书配置工具已隐藏。", "info");
770
+ return;
771
+ }
772
+ hideFeishuConfigTools(pi);
773
+ ctx.ui.notify("飞书配置工具已隐藏。", "info");
774
+ return;
775
+ }
776
+ ctx.ui.notify(
777
+ `飞书配置工具当前:${enabled ? "已启用" : "已隐藏"}。用 /feishu tools on|off 切换。`,
778
+ "info",
779
+ );
780
+ return;
781
+ }
782
+ if (cmd === "progress") {
783
+ const progressCfg = loadConfig();
784
+ if (!cmdArg) {
785
+ ctx.ui.notify(
786
+ `飞书进度展示:${progressCfg?.progressMode ?? "off"}`
787
+ + `(清单上限 ${progressCfg?.progressMaxLines ?? 50} 行,耗时阈值 ${progressCfg?.progressTimeoutSeconds ?? 30}s)\n`
788
+ + "用法:/feishu progress steps | action | timeout | off",
789
+ "info",
790
+ );
791
+ return;
792
+ }
793
+ // 写进 runtime-overrides 白名单:飞书侧 /config progressMode 也能改同一份
794
+ const progressSet = setRuntimeConfig("progressMode", cmdArg);
795
+ if (progressSet.ok === false) {
796
+ ctx.ui.notify(progressSet.error, "error");
797
+ return;
798
+ }
799
+ ctx.ui.notify(
800
+ `飞书进度展示已设为 ${progressSet.value}(全局生效,下一轮回复起)`,
801
+ "info",
802
+ );
803
+ return;
804
+ }
805
+ ctx.ui.notify("可用命令:/feishu setup | start | stop | restart | status | debug | autostart | reset | tools on|off | progress <mode>", "info");
806
+ } catch (error) {
807
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
808
+ }
809
+ },
810
+ });
811
+
812
+ const bootConfig = loadConfig();
813
+
814
+ pi.on("session_start", async (_event, ctx) => {
815
+ uiRef = ctx.ui as any;
816
+ startStatusRefresh();
817
+ if (foreignWorkspaceOwner) {
818
+ ctx.ui.notify(
819
+ `本目录不是该机器人的所属工作区(所属:${foreignWorkspaceOwner}),已跳过自动启动。\n` +
820
+ "要多开:设 FEISHU_DATA_DIR 并用另一个自建应用的 appId/appSecret;确需在本目录临时接管请设 FEISHU_ALLOW_FOREIGN_WORKSPACE=1。",
821
+ "warning",
822
+ );
823
+ }
824
+ // 每个新会话默认隐藏配置工具,保持提示词干净;用户可用 /feishu tools on 打开。
825
+ hideFeishuConfigTools(pi);
826
+ // 多实例时启动就把「有几个机器人、各自 daemon 什么状态」摆出来,省得再去 /feishu status。
827
+ if (multiInstanceStatusText()) ctx.ui.notify(describeInstances(), "info");
828
+ });
829
+
830
+ if (bootConfig?.autoStart) {
831
+ // 裸开保护:未做实例隔离且这把锁属于**另一个目录**时,拒绝自动启动 ——
832
+ // 否则会顶掉别的工作区的机器人连接(飞书长连接不广播,消息会随机落到错的工作区)。
833
+ const foreignOwner = currentGatewayOwner();
834
+ const recordedOwner = readOwnerWorkspace();
835
+ if (isForeignWorkspace(foreignOwner?.cwd, process.cwd(), process.env, recordedOwner)) {
836
+ foreignWorkspaceOwner = foreignOwner?.cwd ?? recordedOwner!;
837
+ console.error(
838
+ `[feishu] 本目录不是该机器人的所属工作区,已跳过自动启动:owner cwd=${foreignWorkspaceOwner},本目录=${process.cwd()}。` +
839
+ " 要多开请设 FEISHU_DATA_DIR 并配另一个自建应用;FEISHU_ALLOW_FOREIGN_WORKSPACE=1 可强制接管。",
840
+ );
841
+ } else if (process.env.PI_FEISHU_DAEMON === "1") {
842
+ start().then((result) => {
843
+ if (typeof result === "object" && result.status === "owned") {
844
+ console.error("[feishu] daemon found existing owner, exiting:", formatOwner(result.owner));
845
+ process.exit(0);
846
+ }
847
+ }).catch((error) => {
848
+ updateStatus(error instanceof BotUnavailableError ? "bot unavailable" : "disconnected");
849
+ console.error("[feishu] daemon autoStart failed:", error instanceof Error ? error.message : error);
850
+ process.exit(1);
851
+ });
852
+ } else {
853
+ startDaemon(false).catch((error) => {
854
+ updateStatus("disconnected");
855
+ console.error("[feishu] daemon spawn failed:", error instanceof Error ? error.message : error);
856
+ });
857
+ }
858
+ }
859
+
860
+ pi.on("session_shutdown", async () => {
861
+ await stop();
862
+ clearStatus();
863
+ });
864
+ }
865
+
866
+ type DaemonProcessInfo = {
867
+ pid: number;
868
+ ppid: number;
869
+ command: string;
870
+ };
871
+
872
+ // 导出仅供测试直接验证多开隔离(见 test/reap-instance.test.ts)。
873
+ export function reapDetachedDaemonProcesses(options: { keepPids?: number[]; extensionPath?: string } = {}) {
874
+ if (process.platform === "win32") return;
875
+
876
+ // 【必须带入口路径】没有明确的扩展入口就**不扫**(fail-safe):
877
+ // 2026-10-14 事故 —— 旧实现不传入口时回退到广谱匹配 `feishu/index.ts`,
878
+ // 插件自己的 `npm test`(test/reap-instance.test.ts 在隔离 HOME 里跑 reap,
879
+ // 真实 daemon 不在那把临时锁里)一次把两个工作区的 daemon 全 SIGTERM 掉,
880
+ // 表现为「重启 pi 刚连上就断、只剩一个能用」。
881
+ // 现在扫描只作用于**本实例扩展入口**拉起的 daemon:跨工作区的 daemon 即便无锁也不会被误杀。
882
+ if (!options.extensionPath) {
883
+ debugLog("feishu.reap.skipped_missing_extension_path", {});
884
+ return;
885
+ }
886
+
887
+ // 多开(同机多个工作区):同一条扩展入口可能被多个工作区共用(全局安装),
888
+ // 所以「本实例入口匹配到的」还要再用网关锁判一次「有主」—— 被任何一把锁认领的
889
+ // pid(及其后代)都保留,只回收没人认领的残留空壳(bash + tail)。见 gateway-lock.readAllGatewayOwnerPids。
890
+ const keep = new Set([...(options.keepPids || []), ...readAllGatewayOwnerPids()]);
891
+ const allProcesses = listProcesses();
892
+
893
+ const byParent = new Map<number, DaemonProcessInfo[]>();
894
+ for (const proc of allProcesses) {
895
+ const children = byParent.get(proc.ppid) || [];
896
+ children.push(proc);
897
+ byParent.set(proc.ppid, children);
898
+ }
899
+
900
+ // 启动链与喂 stdin 的 tail 都不持锁,只锁住 pi 真身不够:
901
+ // 壳(`bash -lc 'tail -f /dev/null | exec pi ...'`,外面还可能再套一层)被回收,
902
+ // tail 就变孤儿,管道写端一关 → pi 的 stdin 直接 EOF → 那个工作区的桥接就掉线。
903
+ // 所以每个被锁认领的 pid 要保**两条线**:
904
+ // ① 整条祖先链(外层 launcher 也可能命中根判据,得一起保,2026-10-14 二次事故的成因);
905
+ // ② 它自己的整棵子树(多层中间壳、工具子进程)。
906
+ // 注意②只对**持锁真身**展开,不能对整条祖先链展开:
907
+ // 祖先里包含本次扫描者自己,对它展开会把「扫描者的兄弟进程」也一起保下来,
908
+ // 无主残留空壳就再也回收不掉了(测试用例 `orphan.wrapper === false` 抓的就是这个)。
909
+ const holders = [...keep];
910
+ const parentOf = new Map(allProcesses.map((proc) => [proc.pid, proc.ppid]));
911
+ for (const pid of holders) {
912
+ let parent = parentOf.get(pid);
913
+ for (let hops = 0; parent && parent > 1 && hops < 32; hops += 1) {
914
+ keep.add(parent);
915
+ parent = parentOf.get(parent);
916
+ }
917
+ }
918
+ for (const pid of holders) collectSubtreePids(pid, byParent, keep);
919
+
920
+ const roots = allProcesses.filter((proc) => looksLikeFeishuDaemon(proc.command, options.extensionPath));
921
+ if (!roots.length) return;
922
+
923
+ const keptRoots = roots.filter((proc) => keep.has(proc.pid));
924
+ if (keptRoots.length) {
925
+ debugLog("feishu.reap.kept_locked_daemons", {
926
+ pids: keptRoots.map((proc) => proc.pid),
927
+ candidates: roots.length,
928
+ });
929
+ }
930
+
931
+ const toKill = new Set<number>();
932
+ for (const proc of roots) {
933
+ // 自己这条不算:本进程命令行里也会出现这些字串,把自己当成根会把**自己名下的子进程**
934
+ // 当残留回收(工具子进程、别的 agent 都会被误杀)。
935
+ if (proc.pid === process.pid) continue;
936
+ if (keep.has(proc.pid)) continue;
937
+ toKill.add(proc.pid);
938
+ collectDescendantPids(proc.pid, byParent, toKill, keep);
939
+ }
940
+
941
+ for (const pid of [...toKill].sort((a, b) => b - a)) {
942
+ if (keep.has(pid) || pid === process.pid) continue;
943
+ try { process.kill(pid, "SIGTERM"); } catch {}
944
+ }
945
+ }
946
+
947
+ function collectDescendantPids(pid: number, byParent: Map<number, DaemonProcessInfo[]>, toKill: Set<number>, keep: Set<number>) {
948
+ for (const child of byParent.get(pid) || []) {
949
+ if (keep.has(child.pid)) continue;
950
+ toKill.add(child.pid);
951
+ collectDescendantPids(child.pid, byParent, toKill, keep);
952
+ }
953
+ }
954
+
955
+ /** 把一个 pid 的整棵子树并进 `out`(含多层中间壳):用于「活着的 daemon 全家都不许动」。 */
956
+ function collectSubtreePids(rootPid: number, byParent: Map<number, DaemonProcessInfo[]>, out: Set<number>) {
957
+ const stack = [rootPid];
958
+ const seen = new Set<number>([rootPid]);
959
+ while (stack.length) {
960
+ const pid = stack.pop() as number;
961
+ for (const child of byParent.get(pid) || []) {
962
+ if (seen.has(child.pid)) continue;
963
+ seen.add(child.pid);
964
+ out.add(child.pid);
965
+ stack.push(child.pid);
966
+ }
967
+ }
968
+ }
969
+
970
+ function listProcesses() {
971
+ const result = spawnSync("ps", ["-wwaxo", "pid=,ppid=,command="], { encoding: "utf8" });
972
+ if (result.status !== 0) return [] as DaemonProcessInfo[];
973
+
974
+ const processes: DaemonProcessInfo[] = [];
975
+ for (const line of result.stdout.split("\n")) {
976
+ const trimmed = line.trim();
977
+ if (!trimmed) continue;
978
+ const match = trimmed.match(/^(\d+)\s+(\d+)\s+(.*)$/);
979
+ if (!match) continue;
980
+ const pid = Number(match[1]);
981
+ const ppid = Number(match[2]);
982
+ const command = match[3] || "";
983
+ if (!Number.isFinite(pid) || !Number.isFinite(ppid)) continue;
984
+ processes.push({ pid, ppid, command });
985
+ }
986
+ return processes;
987
+ }
988
+
989
+ function looksLikeFeishuDaemon(command: string, extensionPath: string) {
990
+ // 启动命令经 quoteShell 处理,每个参数单独加引号('--mode' 'rpc' '--no-extensions'),
991
+ // 直接匹配 "--mode rpc" 永远失败 —— 那样残留的 daemon 空壳(bash + tail 喂 stdin)
992
+ // 永远不会被 reap 掉。所以先去引号再匹配。
993
+ const normalized = command.replace(/'/g, "");
994
+ const hasDaemonFlags = normalized.includes("--mode rpc")
995
+ && normalized.includes("--no-extensions")
996
+ && normalized.includes("--no-builtin-tools");
997
+ if (!hasDaemonFlags) return false;
998
+ if (!extensionPath) return false;
999
+ // 入口路径必须**紧跟在 `-e` 后面**(daemon 的启动形状),而不是「命令行里提到过这个路径」:
1000
+ // 否则一段只是引用了启动命令的脚本 / heredoc(测试探针、重启脚本)也会被当成 daemon 回收。
1001
+ return normalized.includes(`-e ${extensionPath}`);
1002
+ }
1003
+
1004
+ /**
1005
+ * 收掉 daemon 的启动壳 `bash -lc 'tail -f /dev/null | exec pi …'`。
1006
+ *
1007
+ * 只 kill 父 bash 是不够的:`tail -f /dev/null` 是它的**兄弟子进程**,父 bash 一死就被
1008
+ * reparent 到 init,永久挂着——每重启一次漏一个(2026-10-23 实测:一次 /restart 后
1009
+ * 孤儿 tail 从 7 涨到 8)。所以安全时按进程组整组收。
1010
+ *
1011
+ * 安全边界:detached spawn 的 launcher 自成一组(pgid == pid),组里只有 bash + tail + 本进程;
1012
+ * 命令行里必须同时出现 `tail -f /dev/null` 与 `feishu/index.ts` 才动手,
1013
+ * 否则(比如在用户终端里前台跑)宁可什么都不杀。
1014
+ */
1015
+ function terminateLauncherParent() {
1016
+ if (process.platform === "win32") return;
1017
+ const parentPid = process.ppid;
1018
+ if (!parentPid || parentPid <= 1) return;
1019
+
1020
+ const result = spawnSync("ps", ["-wwaxo", "pid=,pgid=,command="], { encoding: "utf8" });
1021
+ if (result.status !== 0) return;
1022
+
1023
+ const line = result.stdout.split("\n")
1024
+ .map((entry) => entry.trim())
1025
+ .find((entry) => entry.startsWith(`${parentPid} `));
1026
+ if (!line) return;
1027
+ if (!line.includes("tail -f /dev/null") || !line.includes("feishu/index.ts")) return;
1028
+ const pgid = Number(line.split(/\s+/)[1]);
1029
+ if (Number.isFinite(pgid) && pgid === parentPid) {
1030
+ try {
1031
+ process.kill(-pgid, "SIGTERM");
1032
+ return;
1033
+ } catch {}
1034
+ }
1035
+ try { process.kill(parentPid, "SIGTERM"); } catch {}
1036
+ }
1037
+
1038
+ async function withDaemonSpawnLock<T>(fn: () => Promise<T>): Promise<T> {
1039
+ const lockPath = `${gatewayLockPath()}.spawn.lock`;
1040
+ for (let attempt = 0; attempt < 40; attempt += 1) {
1041
+ if (tryAcquireSpawnLock(lockPath)) {
1042
+ try {
1043
+ return await fn();
1044
+ } finally {
1045
+ try { rmSync(lockPath, { recursive: true, force: true }); } catch {}
1046
+ }
1047
+ }
1048
+ await sleep(25);
1049
+ }
1050
+ // Last resort: run without the spawn lock. The daemon-side gateway lock still
1051
+ // prevents duplicate live Feishu connections.
1052
+ return fn();
1053
+ }
1054
+
1055
+ function tryAcquireSpawnLock(lockPath: string) {
1056
+ try {
1057
+ mkdirSync(lockPath, { recursive: false });
1058
+ return true;
1059
+ } catch {
1060
+ try {
1061
+ const age = Date.now() - statSync(lockPath).mtimeMs;
1062
+ if (age > 30_000) rmSync(lockPath, { recursive: true, force: true });
1063
+ } catch {}
1064
+ return false;
1065
+ }
1066
+ }
1067
+
1068
+ function sleep(ms: number) {
1069
+ return new Promise((resolve) => setTimeout(resolve, ms));
1070
+ }
1071
+
1072
+ function textToolResult(text: string) {
1073
+ return {
1074
+ content: [{ type: "text" as const, text }],
1075
+ details: {},
1076
+ };
1077
+ }
1078
+
1079
+ // feishu_config_* 工具名单:默认从提示词隐藏,可用 /feishu tools on|off 切换。
1080
+ const FEISHU_CONFIG_TOOLS = [
1081
+ "feishu_config_get",
1082
+ "feishu_config_set",
1083
+ "feishu_config_clear",
1084
+ ];
1085
+
1086
+ function hideFeishuConfigTools(pi: ExtensionAPI) {
1087
+ const active = pi.getActiveTools();
1088
+ const filtered = active.filter((t) => !FEISHU_CONFIG_TOOLS.includes(t));
1089
+ if (filtered.length !== active.length) {
1090
+ pi.setActiveTools(filtered);
1091
+ }
1092
+ }
1093
+
1094
+ function registerFeishuConfigTools(pi: ExtensionAPI) {
1095
+ pi.registerTool({
1096
+ name: "feishu_config_get",
1097
+ label: "Feishu Config Get",
1098
+ description:
1099
+ "Read Feishu runtime config whitelist (groupPolicy, groupKeywords, streaming, etc). Secrets are never returned.",
1100
+ promptSnippet: "Read Feishu bot runtime settings (keywords, mention policy, streaming).",
1101
+ parameters: Type.Object({}),
1102
+ async execute() {
1103
+ const cfg = loadConfig();
1104
+ if (!cfg) {
1105
+ return textToolResult("Feishu config unavailable (missing FEISHU_APP_ID/SECRET).");
1106
+ }
1107
+ return textToolResult(formatRuntimeConfig(cfg, getRuntimeOverrides()));
1108
+ },
1109
+ });
1110
+
1111
+ pi.registerTool({
1112
+ name: "feishu_config_set",
1113
+ label: "Feishu Config Set",
1114
+ description:
1115
+ `Set a Feishu runtime config key. HOT-RELOADS immediately and persists to runtime-overrides.json — NEVER tell the user to restart the container or edit docker-compose.yml. Allowed keys: ${RUNTIME_CONFIG_KEYS.join(", ")}. Do not set appId/appSecret.`,
1116
+ promptSnippet: "Update Feishu group trigger keywords / streaming / emoji at runtime (no restart).",
1117
+ promptGuidelines: [
1118
+ "Only use whitelisted keys; never attempt to set app credentials.",
1119
+ "After set, subsequent group messages use the new settings immediately — no docker restart.",
1120
+ "Never edit docker-compose.yml or env files for these settings; use this tool only.",
1121
+ ],
1122
+ parameters: Type.Object({
1123
+ key: Type.String({ description: `One of: ${RUNTIME_CONFIG_KEYS.join(", ")}` }),
1124
+ value: Type.String({ description: "New value (keywords comma-separated; bool true/false; numbers as digits)" }),
1125
+ }),
1126
+ async execute(_id, params) {
1127
+ const key = String((params as any)?.key || "").trim();
1128
+ const value = String((params as any)?.value ?? "");
1129
+ if (!key) return textToolResult("key is required");
1130
+ const result = setRuntimeConfig(key, value);
1131
+ if (result.ok === false) return textToolResult(`Error: ${result.error}`);
1132
+ const cfg = loadConfig();
1133
+ return textToolResult(
1134
+ [
1135
+ `Updated ${result.key} = ${Array.isArray(result.value) ? result.value.join(", ") : String(result.value)}`,
1136
+ "Hot-reloaded and persisted (runtime-overrides.json).",
1137
+ "",
1138
+ cfg ? formatRuntimeConfig(cfg, getRuntimeOverrides()) : "",
1139
+ ]
1140
+ .filter(Boolean)
1141
+ .join("\n"),
1142
+ );
1143
+ },
1144
+ });
1145
+
1146
+ pi.registerTool({
1147
+ name: "feishu_config_clear",
1148
+ label: "Feishu Config Clear",
1149
+ description: "Clear one runtime override key or all overrides (reverts to env/base config).",
1150
+ parameters: Type.Object({
1151
+ key: Type.Optional(Type.String({ description: "Whitelist key, or omit/all for all overrides" })),
1152
+ }),
1153
+ async execute(_id, params) {
1154
+ const target = String((params as any)?.key || "all").trim() || "all";
1155
+ const result = clearRuntimeOverrides(target);
1156
+ if (result.ok === false) return textToolResult(`Error: ${result.error}`);
1157
+ const cfg = loadConfig();
1158
+ return textToolResult(
1159
+ [
1160
+ target === "all" ? "Cleared all runtime overrides." : `Cleared override: ${target}`,
1161
+ "",
1162
+ cfg ? formatRuntimeConfig(cfg, getRuntimeOverrides()) : "",
1163
+ ]
1164
+ .filter(Boolean)
1165
+ .join("\n"),
1166
+ );
1167
+ },
1168
+ });
1169
+ }