@suwenguang/pi-feishu-bridge 0.0.0-stage → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.pi/extensions/feishu/index.ts +11 -0
- package/.pi/feishu/debug.pi.log +81 -0
- package/.pi/feishu/state.pi.json +12 -0
- package/README.md +210 -2
- package/package.json +57 -4
- package/src/adapters/pi/PiConversationRuntime.ts +1559 -0
- package/src/adapters/pi/index.ts +1169 -0
- package/src/adapters/pi/setup.ts +108 -0
- package/src/feishu/app-register.ts +50 -0
- package/src/feishu/ask.ts +388 -0
- package/src/feishu/attachment-processor.ts +198 -0
- package/src/feishu/attachments.ts +192 -0
- package/src/feishu/bridge-runtime.ts +129 -0
- package/src/feishu/bridge-store.ts +92 -0
- package/src/feishu/card-action-webhook.ts +141 -0
- package/src/feishu/card-actions.ts +241 -0
- package/src/feishu/card-builder.ts +277 -0
- package/src/feishu/cardkit-stream.ts +483 -0
- package/src/feishu/cards.ts +413 -0
- package/src/feishu/config.ts +427 -0
- package/src/feishu/daemon-spec.ts +43 -0
- package/src/feishu/debug.ts +51 -0
- package/src/feishu/dedupe-store.ts +150 -0
- package/src/feishu/delivery.ts +185 -0
- package/src/feishu/gateway-lock.ts +256 -0
- package/src/feishu/group-trigger.ts +128 -0
- package/src/feishu/image-send.ts +256 -0
- package/src/feishu/instance.ts +170 -0
- package/src/feishu/instances.ts +148 -0
- package/src/feishu/interactive-card.ts +236 -0
- package/src/feishu/learn-approval.ts +321 -0
- package/src/feishu/live-cards.ts +128 -0
- package/src/feishu/message-handler.ts +512 -0
- package/src/feishu/messages.ts +356 -0
- package/src/feishu/oversize-progress-card.ts +101 -0
- package/src/feishu/progress-channel.ts +154 -0
- package/src/feishu/progress-note.ts +371 -0
- package/src/feishu/prompt-timeout.ts +81 -0
- package/src/feishu/reply-card-options.ts +73 -0
- package/src/feishu/reply-card.ts +498 -0
- package/src/feishu/restart.ts +286 -0
- package/src/feishu/retry.ts +102 -0
- package/src/feishu/rich-text.ts +387 -0
- package/src/feishu/runtime-config.ts +286 -0
- package/src/feishu/runtime.ts +110 -0
- package/src/feishu/slash-commands.ts +239 -0
- package/src/feishu/thinking.ts +24 -0
- package/src/feishu/transport.ts +792 -0
- package/src/feishu/types.ts +183 -0
- package/src/feishu/ui-notify.ts +44 -0
- package/src/feishu/user-name.ts +121 -0
- package/src/feishu/workspace.ts +42 -0
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync, rmSync, renameSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { parseGroupKeywords } from "./group-trigger.ts";
|
|
4
|
+
import { instanceWebhookPort, LEGACY_GLOBAL_ROOT_DIR, normalizeDir, OWNER_WORKSPACE_FILE, readOwnerWorkspaceAt, resolveRootDir } from "./instance.ts";
|
|
5
|
+
import { applyRuntimeOverrides, getRuntimeOverrides, setRuntimeOverridesPath } from "./runtime-config.ts";
|
|
6
|
+
import type { CardActionMode, Domain, FeishuConfig, GroupPolicy, LearnApprovalConfig } from "./types.ts";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Feishu 数据根目录。**跟着工作区走**:默认 `<工作区根>/.pi/feishu`,
|
|
10
|
+
* 设了 `FEISHU_DATA_DIR` 则用显式值(见 instance.ts)。
|
|
11
|
+
*/
|
|
12
|
+
export const ROOT_DIR = resolveRootDir();
|
|
13
|
+
|
|
14
|
+
// ---------- Pi 适配器路径 ----------
|
|
15
|
+
export const CONFIG_PI_PATH = join(ROOT_DIR, "config.pi.json");
|
|
16
|
+
export const STATE_PI_PATH = join(ROOT_DIR, "state.pi.json");
|
|
17
|
+
export const BRIDGE_PI_PATH = join(ROOT_DIR, "bridge.pi.json");
|
|
18
|
+
export const DEDUPE_PI_PATH = join(ROOT_DIR, "dedupe.pi.json");
|
|
19
|
+
export const DEBUG_PI_LOG_PATH = join(ROOT_DIR, "debug.pi.log");
|
|
20
|
+
export const DAEMON_LOG_PATH = join(ROOT_DIR, "daemon.log");
|
|
21
|
+
|
|
22
|
+
// ---------- 兼容旧引用(等价于 Pi 版) ----------
|
|
23
|
+
export const CONFIG_PATH = CONFIG_PI_PATH;
|
|
24
|
+
export const STATE_PATH = STATE_PI_PATH;
|
|
25
|
+
export const BRIDGE_PATH = BRIDGE_PI_PATH;
|
|
26
|
+
export const DEDUPE_PATH = DEDUPE_PI_PATH;
|
|
27
|
+
export const DEBUG_LOG_PATH = DEBUG_PI_LOG_PATH;
|
|
28
|
+
|
|
29
|
+
export const CHILD_SESSION_ENV = "PI_FEISHU_CHILD_SESSION";
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Agent Runtime 的配置/状态/记录文件集合。
|
|
33
|
+
* 本仓只有 Pi 一个 runtime,这层间接只是让公共代码通过 loadConfig/debugLog
|
|
34
|
+
* 取文件时不必散落常量。
|
|
35
|
+
*/
|
|
36
|
+
export type RuntimeSource = {
|
|
37
|
+
id: "pi";
|
|
38
|
+
/** 环境变量前缀:FEISHU_ */
|
|
39
|
+
envPrefix: string;
|
|
40
|
+
configPath: string;
|
|
41
|
+
statePath: string;
|
|
42
|
+
bridgePath: string;
|
|
43
|
+
dedupePath: string;
|
|
44
|
+
debugLogPath: string;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export const PI_SOURCE: RuntimeSource = {
|
|
48
|
+
id: "pi",
|
|
49
|
+
envPrefix: "FEISHU",
|
|
50
|
+
configPath: CONFIG_PI_PATH,
|
|
51
|
+
statePath: STATE_PI_PATH,
|
|
52
|
+
bridgePath: BRIDGE_PI_PATH,
|
|
53
|
+
dedupePath: DEDUPE_PI_PATH,
|
|
54
|
+
debugLogPath: DEBUG_PI_LOG_PATH,
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/** 默认 Pi(向后兼容:Pi 进程无需显式设置)。 */
|
|
58
|
+
let currentSource: RuntimeSource = PI_SOURCE;
|
|
59
|
+
|
|
60
|
+
export function setRuntimeSource(source: RuntimeSource) {
|
|
61
|
+
currentSource = source;
|
|
62
|
+
// 运行时热更新配置落在实例目录里
|
|
63
|
+
setRuntimeOverridesPath(join(ROOT_DIR, "runtime-overrides.json"));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function getRuntimeSource(): RuntimeSource {
|
|
67
|
+
return currentSource;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 按当前 runtime 的环境变量前缀读取(如 STREAM_PRINT_FREQUENCY_MS → FEISHU_STREAM_PRINT_FREQUENCY_MS)。 */
|
|
71
|
+
export function runtimeEnv(name: string): string | undefined {
|
|
72
|
+
return process.env[`${currentSource.envPrefix}_${name}`];
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export const DEFAULT_CONFIG: Pick<
|
|
76
|
+
FeishuConfig,
|
|
77
|
+
| "domain"
|
|
78
|
+
| "groupPolicy"
|
|
79
|
+
| "groupKeywords"
|
|
80
|
+
| "groupAlsoOnReply"
|
|
81
|
+
| "ignoreBotMessages"
|
|
82
|
+
| "cardActionMode"
|
|
83
|
+
| "cardActionWebhookHost"
|
|
84
|
+
| "cardActionWebhookPort"
|
|
85
|
+
| "cardActionWebhookPath"
|
|
86
|
+
| "language"
|
|
87
|
+
| "reactEmoji"
|
|
88
|
+
| "autoStart"
|
|
89
|
+
| "parseInteractiveCards"
|
|
90
|
+
| "includeQuotedMessage"
|
|
91
|
+
| "quotedMessageMaxChars"
|
|
92
|
+
| "promptNotifySec"
|
|
93
|
+
| "promptTimeoutSec"
|
|
94
|
+
| "sendMaxRetries"
|
|
95
|
+
| "streamingReply"
|
|
96
|
+
| "streamPrintFrequencyMs"
|
|
97
|
+
| "streamPrintStep"
|
|
98
|
+
| "streamPushIntervalMs"
|
|
99
|
+
| "streamFlushMs"
|
|
100
|
+
| "streamFirstFlushMs"
|
|
101
|
+
| "streamMinChars"
|
|
102
|
+
| "streamMaxBodyChars"
|
|
103
|
+
| "messageDelivery"
|
|
104
|
+
> = {
|
|
105
|
+
domain: "feishu",
|
|
106
|
+
groupPolicy: "open",
|
|
107
|
+
groupKeywords: [],
|
|
108
|
+
groupAlsoOnReply: false,
|
|
109
|
+
ignoreBotMessages: true,
|
|
110
|
+
cardActionMode: "webhook",
|
|
111
|
+
cardActionWebhookHost: "0.0.0.0",
|
|
112
|
+
// 默认端口,实际值由 defaultCardActionWebhookPort() 按实例目录派生
|
|
113
|
+
cardActionWebhookPort: 3001,
|
|
114
|
+
cardActionWebhookPath: "/webhook/card",
|
|
115
|
+
language: "zh",
|
|
116
|
+
reactEmoji: "Get",
|
|
117
|
+
autoStart: true,
|
|
118
|
+
parseInteractiveCards: true,
|
|
119
|
+
includeQuotedMessage: true,
|
|
120
|
+
quotedMessageMaxChars: 8000,
|
|
121
|
+
promptNotifySec: 180,
|
|
122
|
+
promptTimeoutSec: 0,
|
|
123
|
+
sendMaxRetries: 2,
|
|
124
|
+
streamingReply: true,
|
|
125
|
+
// 正在生成时又收到新消息:默认排队(与历史行为一致),可改 interrupt 立即打断
|
|
126
|
+
messageDelivery: "queue",
|
|
127
|
+
// CardKit 客户端逐字打印
|
|
128
|
+
streamPrintFrequencyMs: 50,
|
|
129
|
+
streamPrintStep: 1,
|
|
130
|
+
streamPushIntervalMs: 120,
|
|
131
|
+
// 兼容旧 message.patch 参数(CardKit 路径基本忽略)
|
|
132
|
+
streamFlushMs: 350,
|
|
133
|
+
streamFirstFlushMs: 50,
|
|
134
|
+
streamMinChars: 8,
|
|
135
|
+
streamMaxBodyChars: 12000,
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* 卡片回调端口:按实例目录稳定派生到 3003-3099,
|
|
140
|
+
* 避免同一台机器上多个工作区在同一个端口上互抢;
|
|
141
|
+
* 显式 `FEISHU_CARD_ACTION_WEBHOOK_PORT` 优先。
|
|
142
|
+
*/
|
|
143
|
+
export function defaultCardActionWebhookPort(): number {
|
|
144
|
+
return instanceWebhookPort(3001);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function ensureRoot() {
|
|
148
|
+
migrateLegacyGlobalInstance();
|
|
149
|
+
mkdirSync(ROOT_DIR, { recursive: true });
|
|
150
|
+
migrateLegacyFiles();
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* 把 0.5.x 的全局实例数据搬到工作区实例目录(0.6.0 起实例跟着工作区走,不再有全局实例)。
|
|
155
|
+
*
|
|
156
|
+
* 三个条件同时成立才搬,避免偷走别的工作区的数据:
|
|
157
|
+
* 1. 没有显式指定 `FEISHU_DATA_DIR`;
|
|
158
|
+
* 2. 本工作区实例目录还不存在,而旧全局目录存在;
|
|
159
|
+
* 3. 旧全局目录里的属主工作区记录就是本工作区。
|
|
160
|
+
*
|
|
161
|
+
* 用 rename(同盘瞬间完成),失败只打印提示、不做任何删除。
|
|
162
|
+
*
|
|
163
|
+
* 属主判定用**严格相等**(不是 sameWorkspace 的「子目录也算同一工作区」):
|
|
164
|
+
* 迁移是真移动,宁可漏搬也不能错搬 —— 在子目录(例如 `.pi/ax-feishu-bridge`)里
|
|
165
|
+
* 跑一次程序就把父工作区的实例数据搬进子目录,是很贵的错误。
|
|
166
|
+
*/
|
|
167
|
+
function migrateLegacyGlobalInstance() {
|
|
168
|
+
if (existsSync(ROOT_DIR) || !existsSync(LEGACY_GLOBAL_ROOT_DIR)) return;
|
|
169
|
+
// 测试进程绝不搬真实数据(测试里到处都会 ensureRoot(),而 cwd/HOME 都不是真实工作区)
|
|
170
|
+
if (isTestProcess()) return;
|
|
171
|
+
const owner = readOwnerWorkspaceAt(join(LEGACY_GLOBAL_ROOT_DIR, OWNER_WORKSPACE_FILE));
|
|
172
|
+
if (!owner || normalizeDir(owner) !== normalizeDir(process.cwd())) {
|
|
173
|
+
console.error(
|
|
174
|
+
`[feishu] 检测到旧全局实例目录 ${LEGACY_GLOBAL_ROOT_DIR}(属主:${owner ?? "未知"}),不属于本工作区(当前 ${process.cwd()}),未自动搬迁。`,
|
|
175
|
+
);
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
try {
|
|
179
|
+
mkdirSync(dirname(ROOT_DIR), { recursive: true });
|
|
180
|
+
renameSync(LEGACY_GLOBAL_ROOT_DIR, ROOT_DIR);
|
|
181
|
+
console.error(`[feishu] 已把旧全局实例数据搬到工作区实例目录:${ROOT_DIR}`);
|
|
182
|
+
} catch (error) {
|
|
183
|
+
console.error(
|
|
184
|
+
`[feishu] 搬迁旧全局实例数据失败(未做任何删除):${error instanceof Error ? error.message : String(error)}`,
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** 是否跑在测试进程里(`node --test` 会设 NODE_TEST_CONTEXT);测试不得移动真实实例数据。 */
|
|
190
|
+
function isTestProcess(): boolean {
|
|
191
|
+
return Boolean(process.env.NODE_TEST_CONTEXT) || process.argv.includes("--test");
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* 旧版本所有文件不带 runtime 后缀;首次运行新版本时把旧文件改名为 Pi 版,
|
|
196
|
+
* 避免丢失已有配置/会话绑定。
|
|
197
|
+
*/
|
|
198
|
+
function migrateLegacyFiles() {
|
|
199
|
+
migrateFile("state.json", STATE_PI_PATH);
|
|
200
|
+
migrateFile("config.json", CONFIG_PI_PATH);
|
|
201
|
+
migrateFile("bridge.json", BRIDGE_PI_PATH);
|
|
202
|
+
migrateFile("dedupe.json", DEDUPE_PI_PATH);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function migrateFile(legacyName: string, targetPath: string) {
|
|
206
|
+
const legacyPath = join(ROOT_DIR, legacyName);
|
|
207
|
+
if (!existsSync(legacyPath) || existsSync(targetPath)) return;
|
|
208
|
+
try {
|
|
209
|
+
renameSync(legacyPath, targetPath);
|
|
210
|
+
} catch {}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export function readJson<T>(path: string, fallback: T): T {
|
|
214
|
+
if (!existsSync(path)) return fallback;
|
|
215
|
+
try {
|
|
216
|
+
return JSON.parse(readFileSync(path, "utf8")) as T;
|
|
217
|
+
} catch {
|
|
218
|
+
return fallback;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export function writeJson(path: string, value: unknown) {
|
|
223
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
224
|
+
writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`, "utf8");
|
|
225
|
+
try {
|
|
226
|
+
chmodSync(path, 0o600);
|
|
227
|
+
} catch {}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export function removePath(path: string) {
|
|
231
|
+
rmSync(path, { recursive: true, force: true });
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** 工具过程展示档位:off / steps / action / timeout(非法值当作未设,回落默认档) */
|
|
235
|
+
function parseProgressMode(raw: unknown): "off" | "steps" | "action" | "timeout" | undefined {
|
|
236
|
+
const v = typeof raw === "string" ? raw.trim().toLowerCase() : "";
|
|
237
|
+
if (v === "off" || v === "steps" || v === "action" || v === "timeout") return v;
|
|
238
|
+
return undefined;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function parseBool(value: unknown, fallback: boolean): boolean {
|
|
242
|
+
if (typeof value === "boolean") return value;
|
|
243
|
+
if (typeof value === "string") {
|
|
244
|
+
const v = value.trim().toLowerCase();
|
|
245
|
+
if (["1", "true", "yes", "on"].includes(v)) return true;
|
|
246
|
+
if (["0", "false", "no", "off"].includes(v)) return false;
|
|
247
|
+
}
|
|
248
|
+
return fallback;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function parsePositiveInt(value: unknown, fallback: number): number {
|
|
252
|
+
const n = typeof value === "number" ? value : typeof value === "string" ? Number.parseInt(value, 10) : NaN;
|
|
253
|
+
if (!Number.isFinite(n) || n <= 0) return fallback;
|
|
254
|
+
return Math.floor(n);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function parseEnvSeconds(value: string | undefined) {
|
|
258
|
+
if (!value) return undefined;
|
|
259
|
+
const seconds = Number.parseInt(value, 10);
|
|
260
|
+
return Number.isFinite(seconds) && seconds >= 0 ? seconds : undefined;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function numberOr(value: unknown, fallback: number) {
|
|
264
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : fallback;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function applyRuntimeDefaults(cfg: FeishuConfig): FeishuConfig {
|
|
268
|
+
return {
|
|
269
|
+
...cfg,
|
|
270
|
+
learnApproval: parseLearnApproval(cfg.learnApproval),
|
|
271
|
+
groupKeywords: Array.isArray(cfg.groupKeywords)
|
|
272
|
+
? parseGroupKeywords(cfg.groupKeywords)
|
|
273
|
+
: (cfg.groupKeywords ?? DEFAULT_CONFIG.groupKeywords),
|
|
274
|
+
groupAlsoOnReply: cfg.groupAlsoOnReply ?? DEFAULT_CONFIG.groupAlsoOnReply,
|
|
275
|
+
ignoreBotMessages: cfg.ignoreBotMessages ?? DEFAULT_CONFIG.ignoreBotMessages,
|
|
276
|
+
parseInteractiveCards: cfg.parseInteractiveCards ?? DEFAULT_CONFIG.parseInteractiveCards,
|
|
277
|
+
includeQuotedMessage: cfg.includeQuotedMessage ?? DEFAULT_CONFIG.includeQuotedMessage,
|
|
278
|
+
quotedMessageMaxChars: cfg.quotedMessageMaxChars ?? DEFAULT_CONFIG.quotedMessageMaxChars,
|
|
279
|
+
promptNotifySec: numberOr(cfg.promptNotifySec, DEFAULT_CONFIG.promptNotifySec!),
|
|
280
|
+
promptTimeoutSec: numberOr(cfg.promptTimeoutSec, DEFAULT_CONFIG.promptTimeoutSec!),
|
|
281
|
+
sendMaxRetries: cfg.sendMaxRetries ?? DEFAULT_CONFIG.sendMaxRetries,
|
|
282
|
+
streamingReply: cfg.streamingReply ?? DEFAULT_CONFIG.streamingReply,
|
|
283
|
+
messageDelivery: cfg.messageDelivery ?? DEFAULT_CONFIG.messageDelivery,
|
|
284
|
+
streamPrintFrequencyMs: cfg.streamPrintFrequencyMs ?? DEFAULT_CONFIG.streamPrintFrequencyMs,
|
|
285
|
+
streamPrintStep: cfg.streamPrintStep ?? DEFAULT_CONFIG.streamPrintStep,
|
|
286
|
+
streamPushIntervalMs: cfg.streamPushIntervalMs ?? DEFAULT_CONFIG.streamPushIntervalMs,
|
|
287
|
+
streamFlushMs: cfg.streamFlushMs ?? DEFAULT_CONFIG.streamFlushMs,
|
|
288
|
+
streamFirstFlushMs: cfg.streamFirstFlushMs ?? DEFAULT_CONFIG.streamFirstFlushMs,
|
|
289
|
+
streamMinChars: cfg.streamMinChars ?? DEFAULT_CONFIG.streamMinChars,
|
|
290
|
+
streamMaxBodyChars: cfg.streamMaxBodyChars ?? DEFAULT_CONFIG.streamMaxBodyChars,
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
export function loadConfig(): FeishuConfig | undefined {
|
|
295
|
+
const base = loadBaseConfig();
|
|
296
|
+
if (!base) return undefined;
|
|
297
|
+
// runtime-overrides 覆盖 env/config 中的白名单字段(热更新 + 落盘)
|
|
298
|
+
return applyRuntimeOverrides(base, getRuntimeOverrides());
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** 不含 runtime overrides 的基础配置(env 或 config.json) */
|
|
302
|
+
export function loadBaseConfig(): FeishuConfig | undefined {
|
|
303
|
+
const source = getRuntimeSource();
|
|
304
|
+
const env = (name: string) => process.env[`${source.envPrefix}_${name}`];
|
|
305
|
+
const envAppId = env("APP_ID")?.trim();
|
|
306
|
+
const envSecret = env("APP_SECRET")?.trim();
|
|
307
|
+
if (envAppId && envSecret) {
|
|
308
|
+
return applyRuntimeDefaults({
|
|
309
|
+
appId: envAppId,
|
|
310
|
+
appSecret: envSecret,
|
|
311
|
+
domain: (env("DOMAIN") as Domain) || DEFAULT_CONFIG.domain,
|
|
312
|
+
groupPolicy: (env("GROUP_POLICY") as GroupPolicy) || DEFAULT_CONFIG.groupPolicy,
|
|
313
|
+
groupKeywords: parseGroupKeywords(env("GROUP_KEYWORDS")),
|
|
314
|
+
groupAlsoOnReply: parseBool(env("GROUP_ALSO_ON_REPLY"), DEFAULT_CONFIG.groupAlsoOnReply!),
|
|
315
|
+
ignoreBotMessages: parseBool(env("IGNORE_BOT_MESSAGES"), DEFAULT_CONFIG.ignoreBotMessages!),
|
|
316
|
+
cardActionMode: parseCardActionMode(env("CARD_ACTION_MODE")) || DEFAULT_CONFIG.cardActionMode,
|
|
317
|
+
cardActionWebhookHost: env("CARD_ACTION_WEBHOOK_HOST")?.trim() || DEFAULT_CONFIG.cardActionWebhookHost,
|
|
318
|
+
cardActionWebhookPort: parsePort(env("CARD_ACTION_WEBHOOK_PORT")) ?? defaultCardActionWebhookPort(),
|
|
319
|
+
cardActionWebhookPath: normalizeWebhookPath(env("CARD_ACTION_WEBHOOK_PATH")) || DEFAULT_CONFIG.cardActionWebhookPath,
|
|
320
|
+
language: (env("LANGUAGE") as "zh" | "en") || DEFAULT_CONFIG.language,
|
|
321
|
+
reactEmoji: env("REACT_EMOJI") || DEFAULT_CONFIG.reactEmoji,
|
|
322
|
+
autoStart: env("AUTO_START") ? env("AUTO_START") !== "0" : DEFAULT_CONFIG.autoStart,
|
|
323
|
+
parseInteractiveCards: parseBool(env("PARSE_INTERACTIVE_CARDS"), DEFAULT_CONFIG.parseInteractiveCards!),
|
|
324
|
+
includeQuotedMessage: parseBool(env("INCLUDE_QUOTED_MESSAGE"), DEFAULT_CONFIG.includeQuotedMessage!),
|
|
325
|
+
quotedMessageMaxChars: parsePositiveInt(env("QUOTED_MESSAGE_MAX_CHARS"), DEFAULT_CONFIG.quotedMessageMaxChars!),
|
|
326
|
+
promptNotifySec: parseEnvSeconds(env("PROMPT_NOTIFY_SEC")) ?? DEFAULT_CONFIG.promptNotifySec!,
|
|
327
|
+
promptTimeoutSec: parseEnvSeconds(env("PROMPT_TIMEOUT_SEC")) ?? DEFAULT_CONFIG.promptTimeoutSec!,
|
|
328
|
+
sendMaxRetries: parsePositiveInt(env("SEND_MAX_RETRIES"), DEFAULT_CONFIG.sendMaxRetries!),
|
|
329
|
+
streamingReply: parseBool(env("STREAMING_REPLY"), DEFAULT_CONFIG.streamingReply!),
|
|
330
|
+
streamPrintFrequencyMs: parsePositiveInt(env("STREAM_PRINT_FREQUENCY_MS"), DEFAULT_CONFIG.streamPrintFrequencyMs!),
|
|
331
|
+
streamPrintStep: parsePositiveInt(env("STREAM_PRINT_STEP"), DEFAULT_CONFIG.streamPrintStep!),
|
|
332
|
+
streamPushIntervalMs: parsePositiveInt(env("STREAM_PUSH_INTERVAL_MS"), DEFAULT_CONFIG.streamPushIntervalMs!),
|
|
333
|
+
streamFlushMs: parsePositiveInt(env("STREAM_FLUSH_MS"), DEFAULT_CONFIG.streamFlushMs!),
|
|
334
|
+
streamFirstFlushMs: parsePositiveInt(env("STREAM_FIRST_FLUSH_MS"), DEFAULT_CONFIG.streamFirstFlushMs!),
|
|
335
|
+
streamMinChars: parsePositiveInt(env("STREAM_MIN_CHARS"), DEFAULT_CONFIG.streamMinChars!),
|
|
336
|
+
streamMaxBodyChars: parsePositiveInt(env("STREAM_MAX_BODY_CHARS"), DEFAULT_CONFIG.streamMaxBodyChars!),
|
|
337
|
+
progressMode: parseProgressMode(env("PROGRESS_MODE")),
|
|
338
|
+
progressMaxLines: parsePositiveInt(env("PROGRESS_MAX_LINES"), 50),
|
|
339
|
+
progressTimeoutSeconds: parsePositiveInt(env("PROGRESS_TIMEOUT_SECONDS"), 30),
|
|
340
|
+
// 进化审批:环境变量只提供 approval_code,超时/轮询间隔走默认值
|
|
341
|
+
learnApproval: parseLearnApproval(
|
|
342
|
+
env("LEARN_APPROVAL_CODE") ? { approvalCode: env("LEARN_APPROVAL_CODE") } : undefined,
|
|
343
|
+
),
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
if (!existsSync(source.configPath)) return undefined;
|
|
347
|
+
const cfg = readJson<Partial<FeishuConfig>>(source.configPath, {});
|
|
348
|
+
if (!cfg.appId || !cfg.appSecret) return undefined;
|
|
349
|
+
return applyRuntimeDefaults({
|
|
350
|
+
appId: cfg.appId,
|
|
351
|
+
appSecret: cfg.appSecret,
|
|
352
|
+
domain: cfg.domain || DEFAULT_CONFIG.domain,
|
|
353
|
+
groupPolicy: cfg.groupPolicy || DEFAULT_CONFIG.groupPolicy,
|
|
354
|
+
groupKeywords: parseGroupKeywords(cfg.groupKeywords),
|
|
355
|
+
groupAlsoOnReply: parseBool(cfg.groupAlsoOnReply, DEFAULT_CONFIG.groupAlsoOnReply!),
|
|
356
|
+
ignoreBotMessages: parseBool(cfg.ignoreBotMessages, DEFAULT_CONFIG.ignoreBotMessages!),
|
|
357
|
+
cardActionMode: parseCardActionMode(cfg.cardActionMode) || DEFAULT_CONFIG.cardActionMode,
|
|
358
|
+
cardActionWebhookHost: cfg.cardActionWebhookHost || DEFAULT_CONFIG.cardActionWebhookHost,
|
|
359
|
+
cardActionWebhookPort: typeof cfg.cardActionWebhookPort === "number" ? cfg.cardActionWebhookPort : defaultCardActionWebhookPort(),
|
|
360
|
+
cardActionWebhookPath: normalizeWebhookPath(cfg.cardActionWebhookPath) || DEFAULT_CONFIG.cardActionWebhookPath,
|
|
361
|
+
language: cfg.language || DEFAULT_CONFIG.language,
|
|
362
|
+
reactEmoji: cfg.reactEmoji || DEFAULT_CONFIG.reactEmoji,
|
|
363
|
+
autoStart: cfg.autoStart ?? DEFAULT_CONFIG.autoStart,
|
|
364
|
+
parseInteractiveCards: cfg.parseInteractiveCards,
|
|
365
|
+
includeQuotedMessage: cfg.includeQuotedMessage,
|
|
366
|
+
quotedMessageMaxChars: cfg.quotedMessageMaxChars,
|
|
367
|
+
promptNotifySec: numberOr(cfg.promptNotifySec, DEFAULT_CONFIG.promptNotifySec!),
|
|
368
|
+
promptTimeoutSec: numberOr(cfg.promptTimeoutSec, DEFAULT_CONFIG.promptTimeoutSec!),
|
|
369
|
+
sendMaxRetries: cfg.sendMaxRetries,
|
|
370
|
+
streamingReply: cfg.streamingReply,
|
|
371
|
+
messageDelivery: cfg.messageDelivery,
|
|
372
|
+
streamPrintFrequencyMs: cfg.streamPrintFrequencyMs,
|
|
373
|
+
streamPrintStep: cfg.streamPrintStep,
|
|
374
|
+
streamPushIntervalMs: cfg.streamPushIntervalMs,
|
|
375
|
+
streamFlushMs: cfg.streamFlushMs,
|
|
376
|
+
streamFirstFlushMs: cfg.streamFirstFlushMs,
|
|
377
|
+
streamMinChars: cfg.streamMinChars,
|
|
378
|
+
streamMaxBodyChars: cfg.streamMaxBodyChars,
|
|
379
|
+
// 工具过程展示:此前只认 runtime-overrides,写在 config.pi.json 里会被静默忽略
|
|
380
|
+
progressMode: parseProgressMode(cfg.progressMode),
|
|
381
|
+
progressMaxLines: typeof cfg.progressMaxLines === "number" ? cfg.progressMaxLines : undefined,
|
|
382
|
+
progressTimeoutSeconds:
|
|
383
|
+
typeof cfg.progressTimeoutSeconds === "number" ? cfg.progressTimeoutSeconds : undefined,
|
|
384
|
+
learnApproval: parseLearnApproval(cfg.learnApproval),
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function parseCardActionMode(value: unknown): CardActionMode | undefined {
|
|
389
|
+
if (value !== "webhook" && value !== "ws") return undefined;
|
|
390
|
+
return value;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* 解析进化审批配置。
|
|
395
|
+
* approvalCode 是必需项:没有它就说明用户还没在飞书审批后台建好审批定义,
|
|
396
|
+
* 此时整个 learnApproval 视为未配置,/learn 应用 会明确提示去配。
|
|
397
|
+
*/
|
|
398
|
+
export function parseLearnApproval(value: unknown): LearnApprovalConfig | undefined {
|
|
399
|
+
if (!value || typeof value !== "object") return undefined;
|
|
400
|
+
const raw = value as Record<string, unknown>;
|
|
401
|
+
const approvalCode = typeof raw.approvalCode === "string" ? raw.approvalCode.trim() : "";
|
|
402
|
+
if (!approvalCode) return undefined;
|
|
403
|
+
return {
|
|
404
|
+
approvalCode,
|
|
405
|
+
timeoutSec: typeof raw.timeoutSec === "number" && raw.timeoutSec > 0 ? Math.floor(raw.timeoutSec) : undefined,
|
|
406
|
+
pollIntervalSec:
|
|
407
|
+
typeof raw.pollIntervalSec === "number" && raw.pollIntervalSec > 0 ? Math.floor(raw.pollIntervalSec) : undefined,
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function parsePort(value: string | undefined) {
|
|
412
|
+
if (!value) return undefined;
|
|
413
|
+
const port = Number.parseInt(value, 10);
|
|
414
|
+
if (!Number.isFinite(port) || port <= 0 || port > 65535) return undefined;
|
|
415
|
+
return port;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
function normalizeWebhookPath(value: string | undefined) {
|
|
419
|
+
const trimmed = value?.trim();
|
|
420
|
+
if (!trimmed) return undefined;
|
|
421
|
+
return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
export function mask(s: string) {
|
|
425
|
+
if (s.length <= 8) return "****";
|
|
426
|
+
return `${s.slice(0, 4)}****${s.slice(-4)}`;
|
|
427
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* daemon 启动形状的**唯一来源**。
|
|
3
|
+
*
|
|
4
|
+
* 抽出来的原因:`/restart` 要在不加载 Pi SDK 的独立 worker 里复刻完全相同的启动参数。
|
|
5
|
+
* 只要两边形状不一致,`looksLikeFeishuDaemon()`(认紧跟在 `-e` 后面的扩展入口)就认不出
|
|
6
|
+
* 新进程是 daemon,残留进程回收会把重启后的实例当野进程留着或反复重建。
|
|
7
|
+
*/
|
|
8
|
+
import { DAEMON_LOG_PATH } from "./config.ts";
|
|
9
|
+
|
|
10
|
+
export type DaemonSpec = {
|
|
11
|
+
extensionPath: string;
|
|
12
|
+
piBin: string;
|
|
13
|
+
args: string[];
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/** POSIX 单引号转义:`it's` → `'it'\''s'` */
|
|
17
|
+
export function quoteShell(value: string): string {
|
|
18
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function daemonSpec(extensionPath: string): DaemonSpec {
|
|
22
|
+
const piBin = process.env.PI_BIN || "pi";
|
|
23
|
+
const args = [
|
|
24
|
+
"--mode", "rpc",
|
|
25
|
+
"--no-extensions",
|
|
26
|
+
"--no-skills",
|
|
27
|
+
"--no-prompt-templates",
|
|
28
|
+
"--no-themes",
|
|
29
|
+
"--no-context-files",
|
|
30
|
+
"--no-builtin-tools",
|
|
31
|
+
"-e", extensionPath,
|
|
32
|
+
];
|
|
33
|
+
return { extensionPath, piBin, args };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function daemonCommand(spec: DaemonSpec): string {
|
|
37
|
+
return `tail -f /dev/null | exec ${quoteShell(spec.piBin)} ${spec.args.map(quoteShell).join(" ")}`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** daemon 的 stdout/stderr 落点;worker 与 `startDaemon` 共用,便于一次 tail 看全流程 */
|
|
41
|
+
export function daemonLogPath(): string {
|
|
42
|
+
return DAEMON_LOG_PATH;
|
|
43
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { ensureRoot, getRuntimeSource } from "./config.ts";
|
|
3
|
+
|
|
4
|
+
const MAX_VALUE_LENGTH = 1200;
|
|
5
|
+
const MAX_LOG_LINES = 1000;
|
|
6
|
+
const TRIM_TRIGGER_LINES = 1200;
|
|
7
|
+
|
|
8
|
+
function debugLogPath() {
|
|
9
|
+
return getRuntimeSource().debugLogPath;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function debugLog(event: string, details?: Record<string, unknown>) {
|
|
13
|
+
try {
|
|
14
|
+
ensureRoot();
|
|
15
|
+
const path = debugLogPath();
|
|
16
|
+
const line = JSON.stringify({
|
|
17
|
+
at: new Date().toISOString(),
|
|
18
|
+
event,
|
|
19
|
+
...(details ? { details: truncate(details) } : {}),
|
|
20
|
+
});
|
|
21
|
+
appendFileSync(path, `${line}\n`, "utf8");
|
|
22
|
+
trimDebugLogIfNeeded(path);
|
|
23
|
+
} catch {
|
|
24
|
+
// Debug logging must never break message handling.
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function trimDebugLogIfNeeded(path: string) {
|
|
29
|
+
const content = readFileSync(path, "utf8");
|
|
30
|
+
const lines = content.split("\n");
|
|
31
|
+
const hasTrailingNewline = lines[lines.length - 1] === "";
|
|
32
|
+
const effectiveLines = hasTrailingNewline ? lines.slice(0, -1) : lines;
|
|
33
|
+
if (effectiveLines.length <= TRIM_TRIGGER_LINES) return;
|
|
34
|
+
const recent = effectiveLines.slice(-MAX_LOG_LINES);
|
|
35
|
+
writeFileSync(path, `${recent.join("\n")}\n`, "utf8");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function truncate(value: unknown): unknown {
|
|
39
|
+
if (typeof value === "string") {
|
|
40
|
+
return value.length > MAX_VALUE_LENGTH ? `${value.slice(0, MAX_VALUE_LENGTH)}...` : value;
|
|
41
|
+
}
|
|
42
|
+
if (Array.isArray(value)) return value.map((item) => truncate(item));
|
|
43
|
+
if (value && typeof value === "object") {
|
|
44
|
+
const out: Record<string, unknown> = {};
|
|
45
|
+
for (const [key, item] of Object.entries(value)) {
|
|
46
|
+
out[key] = truncate(item);
|
|
47
|
+
}
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
return value;
|
|
51
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { ensureRoot, getRuntimeSource } from "./config.ts";
|
|
4
|
+
import { debugLog } from "./debug.ts";
|
|
5
|
+
|
|
6
|
+
const MESSAGE_TTL_MS = 24 * 60 * 60 * 1000;
|
|
7
|
+
const LOCK_STALE_MS = 5000;
|
|
8
|
+
const LOCK_RETRY_MS = 25;
|
|
9
|
+
const LOCK_ATTEMPTS = 40;
|
|
10
|
+
|
|
11
|
+
function dedupePath() {
|
|
12
|
+
return getRuntimeSource().dedupePath;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
type DedupeStatus = "processing" | "replied" | "ignored" | "failed";
|
|
16
|
+
|
|
17
|
+
type DedupeRecord = {
|
|
18
|
+
status: DedupeStatus;
|
|
19
|
+
firstSeenAt: number;
|
|
20
|
+
updatedAt: number;
|
|
21
|
+
pid: number;
|
|
22
|
+
error?: string;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
type DedupeStore = {
|
|
26
|
+
messages?: Record<string, DedupeRecord>;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export async function claimFeishuMessage(messageId: string): Promise<boolean> {
|
|
30
|
+
if (!messageId) return true;
|
|
31
|
+
|
|
32
|
+
return withStoreLock(() => {
|
|
33
|
+
const now = Date.now();
|
|
34
|
+
const store = readStore();
|
|
35
|
+
const messages = store.messages || {};
|
|
36
|
+
pruneExpired(messages, now);
|
|
37
|
+
|
|
38
|
+
const existing = messages[messageId];
|
|
39
|
+
if (existing) {
|
|
40
|
+
existing.updatedAt = now;
|
|
41
|
+
writeStore({ messages });
|
|
42
|
+
debugLog("feishu.dedupe.ignored_message", {
|
|
43
|
+
messageId,
|
|
44
|
+
status: existing.status,
|
|
45
|
+
firstSeenAt: new Date(existing.firstSeenAt).toISOString(),
|
|
46
|
+
ownerPid: existing.pid,
|
|
47
|
+
currentPid: process.pid,
|
|
48
|
+
});
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
messages[messageId] = {
|
|
53
|
+
status: "processing",
|
|
54
|
+
firstSeenAt: now,
|
|
55
|
+
updatedAt: now,
|
|
56
|
+
pid: process.pid,
|
|
57
|
+
};
|
|
58
|
+
writeStore({ messages });
|
|
59
|
+
debugLog("feishu.dedupe.claimed_message", { messageId, pid: process.pid });
|
|
60
|
+
return true;
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function markFeishuMessage(messageId: string, status: DedupeStatus, error?: string): Promise<void> {
|
|
65
|
+
if (!messageId) return;
|
|
66
|
+
|
|
67
|
+
await withStoreLock(() => {
|
|
68
|
+
const now = Date.now();
|
|
69
|
+
const store = readStore();
|
|
70
|
+
const messages = store.messages || {};
|
|
71
|
+
pruneExpired(messages, now);
|
|
72
|
+
|
|
73
|
+
const existing = messages[messageId] || {
|
|
74
|
+
status,
|
|
75
|
+
firstSeenAt: now,
|
|
76
|
+
updatedAt: now,
|
|
77
|
+
pid: process.pid,
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
messages[messageId] = {
|
|
81
|
+
...existing,
|
|
82
|
+
status,
|
|
83
|
+
updatedAt: now,
|
|
84
|
+
error: error ? error.slice(0, 500) : undefined,
|
|
85
|
+
};
|
|
86
|
+
writeStore({ messages });
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function readStore(): DedupeStore {
|
|
91
|
+
try {
|
|
92
|
+
const path = dedupePath();
|
|
93
|
+
if (!existsSync(path)) return {};
|
|
94
|
+
return JSON.parse(readFileSync(path, "utf8")) as DedupeStore;
|
|
95
|
+
} catch {
|
|
96
|
+
return {};
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function writeStore(store: DedupeStore) {
|
|
101
|
+
ensureRoot();
|
|
102
|
+
writeFileSync(dedupePath(), `${JSON.stringify(store, null, 2)}\n`, "utf8");
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function pruneExpired(messages: Record<string, DedupeRecord>, now: number) {
|
|
106
|
+
for (const [messageId, record] of Object.entries(messages)) {
|
|
107
|
+
if (!record.updatedAt || now - record.updatedAt > MESSAGE_TTL_MS) {
|
|
108
|
+
delete messages[messageId];
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async function withStoreLock<T>(fn: () => T | Promise<T>): Promise<T> {
|
|
114
|
+
ensureRoot();
|
|
115
|
+
const lockPath = `${dedupePath()}.lock`;
|
|
116
|
+
|
|
117
|
+
for (let attempt = 0; attempt < LOCK_ATTEMPTS; attempt += 1) {
|
|
118
|
+
if (tryAcquireLock(lockPath)) {
|
|
119
|
+
try {
|
|
120
|
+
return await fn();
|
|
121
|
+
} finally {
|
|
122
|
+
try { rmSync(lockPath, { recursive: true, force: true }); } catch {}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
await sleep(LOCK_RETRY_MS);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
debugLog("feishu.dedupe.lock_timeout", { lockPath });
|
|
129
|
+
return await fn();
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function tryAcquireLock(lockPath: string) {
|
|
133
|
+
try {
|
|
134
|
+
mkdirSync(dirname(lockPath), { recursive: true });
|
|
135
|
+
mkdirSync(lockPath);
|
|
136
|
+
return true;
|
|
137
|
+
} catch {
|
|
138
|
+
try {
|
|
139
|
+
const age = Date.now() - statSync(lockPath).mtimeMs;
|
|
140
|
+
if (age > LOCK_STALE_MS) {
|
|
141
|
+
rmSync(lockPath, { recursive: true, force: true });
|
|
142
|
+
}
|
|
143
|
+
} catch {}
|
|
144
|
+
return false;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function sleep(ms: number) {
|
|
149
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
150
|
+
}
|