dsh-plugin-lark-bridge 0.1.2 → 0.1.4
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/README.md +20 -60
- package/cordis.patch.yml +2 -8
- package/dist/auth.d.ts +12 -38
- package/dist/auth.d.ts.map +1 -1
- package/dist/bridge.d.ts +19 -5
- package/dist/bridge.d.ts.map +1 -1
- package/dist/cli.d.ts +17 -21
- package/dist/cli.d.ts.map +1 -1
- package/dist/client/api.d.ts +9 -33
- package/dist/client/api.d.ts.map +1 -1
- package/dist/client/auth-overlay.d.ts +54 -6
- package/dist/client/auth-overlay.d.ts.map +1 -1
- package/dist/client/auth-panel.d.ts +17 -5
- package/dist/client/auth-panel.d.ts.map +1 -1
- package/dist/client/config-form.d.ts +10 -11
- package/dist/client/config-form.d.ts.map +1 -1
- package/dist/client/config-page.d.ts +40 -6
- package/dist/client/config-page.d.ts.map +1 -1
- package/dist/client/index.d.ts +4 -8
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/locales.d.ts +37 -41
- package/dist/client/locales.d.ts.map +1 -1
- package/dist/client/model-defaults.d.ts +49 -0
- package/dist/client/model-defaults.d.ts.map +1 -0
- package/dist/client/preset-defaults.d.ts +84 -0
- package/dist/client/preset-defaults.d.ts.map +1 -0
- package/dist/client/preset-select.d.ts +26 -0
- package/dist/client/preset-select.d.ts.map +1 -0
- package/dist/client/status-controller.d.ts +43 -0
- package/dist/client/status-controller.d.ts.map +1 -0
- package/dist/client/terminal-command.d.ts +11 -0
- package/dist/client/terminal-command.d.ts.map +1 -0
- package/dist/client.js +2004 -656
- package/dist/config.d.ts +25 -21
- package/dist/config.d.ts.map +1 -1
- package/dist/constants.d.ts +8 -4
- package/dist/constants.d.ts.map +1 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +814 -510
- package/dist/message.d.ts +27 -0
- package/dist/message.d.ts.map +1 -0
- package/dist/quote.d.ts +49 -0
- package/dist/quote.d.ts.map +1 -0
- package/dist/reminder.d.ts +33 -0
- package/dist/reminder.d.ts.map +1 -0
- package/dist/routes.d.ts +5 -15
- package/dist/routes.d.ts.map +1 -1
- package/dist/sessions.d.ts +22 -17
- package/dist/sessions.d.ts.map +1 -1
- package/dist/state.d.ts +0 -2
- package/dist/state.d.ts.map +1 -1
- package/dist/tools.d.ts +1 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/types.d.ts +2 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/utils.d.ts +5 -1
- package/dist/utils.d.ts.map +1 -1
- package/dist/workspace-path.d.ts +8 -0
- package/dist/workspace-path.d.ts.map +1 -0
- package/dist/workspace.d.ts +32 -0
- package/dist/workspace.d.ts.map +1 -0
- package/icon.svg +9 -0
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +33 -21
package/dist/index.mjs
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
|
-
import { createRequire } from "node:module";
|
|
2
1
|
import { spawn } from "node:child_process";
|
|
3
|
-
import { existsSync } from "node:fs";
|
|
4
|
-
import { dirname, join, resolve } from "node:path";
|
|
5
2
|
import { createInterface } from "node:readline";
|
|
6
3
|
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, join, resolve } from "node:path";
|
|
5
|
+
import { ReasoningEffortId, createUserMessage } from "@deepseek-ai/dsh-llm";
|
|
7
6
|
import Schema from "@deepseek-ai/schemastery";
|
|
8
7
|
import { randomUUID } from "node:crypto";
|
|
9
8
|
import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
10
|
-
import { createUserMessage } from "@deepseek-ai/dsh-llm";
|
|
11
9
|
import { SessionId } from "@deepseek-ai/dsh-session";
|
|
12
10
|
//#region src/utils.ts
|
|
13
11
|
/** 零依赖工具函数。 */
|
|
@@ -15,20 +13,34 @@ import { SessionId } from "@deepseek-ai/dsh-session";
|
|
|
15
13
|
function isRecord(value) {
|
|
16
14
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
17
15
|
}
|
|
18
|
-
/** 把毫秒时间戳或 ISO
|
|
16
|
+
/** 把毫秒时间戳或 ISO 文本转成 `YYYY-MM-DD HH:mm:ss`;非法值返回空串。 */
|
|
19
17
|
function formatTime(value, timeZone = "Asia/Shanghai") {
|
|
20
18
|
const date = typeof value === "number" ? new Date(value) : new Date(String(value ?? ""));
|
|
21
19
|
if (Number.isNaN(date.getTime())) return "";
|
|
22
|
-
return
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
20
|
+
return new Intl.DateTimeFormat("sv-SE", {
|
|
21
|
+
timeZone,
|
|
22
|
+
year: "numeric",
|
|
23
|
+
month: "2-digit",
|
|
24
|
+
day: "2-digit",
|
|
25
|
+
hour: "2-digit",
|
|
26
|
+
minute: "2-digit",
|
|
27
|
+
second: "2-digit",
|
|
28
|
+
hourCycle: "h23"
|
|
29
|
+
}).format(date);
|
|
30
|
+
}
|
|
31
|
+
/** 转义属性值中的 `&`、`"` 与 `<`。 */
|
|
32
|
+
function escapeAttribute(value) {
|
|
33
|
+
return value.replaceAll("&", "&").replaceAll("\"", """).replaceAll("<", "<");
|
|
26
34
|
}
|
|
27
35
|
/** 解析毫秒时间戳字符串;非法值返回当前时间。 */
|
|
28
36
|
function parseTimestamp(value) {
|
|
29
37
|
const parsed = Number(value);
|
|
30
38
|
return Number.isFinite(parsed) && parsed > 0 ? parsed : Date.now();
|
|
31
39
|
}
|
|
40
|
+
/** 转义块内正文的结束标记,避免提前闭合外层块。 */
|
|
41
|
+
function escapeBlockText(value) {
|
|
42
|
+
return value.replaceAll("</lark-message>", "<\\/lark-message>").replaceAll("</quote>", "<\\/quote>").replaceAll("</forwarded_messages>", "<\\/forwarded_messages>");
|
|
43
|
+
}
|
|
32
44
|
/**
|
|
33
45
|
* 把文本包成 system-reminder 帧。
|
|
34
46
|
* @param text - 提醒正文。
|
|
@@ -57,14 +69,6 @@ function splitText(text, limit) {
|
|
|
57
69
|
parts.push(rest);
|
|
58
70
|
return parts;
|
|
59
71
|
}
|
|
60
|
-
/** 规范化路径用于比较;Windows 忽略大小写与斜杠差异。 */
|
|
61
|
-
function samePath(a, b) {
|
|
62
|
-
const normalize = (value) => {
|
|
63
|
-
const slashed = value.replaceAll("\\", "/").replace(/\/+$/, "");
|
|
64
|
-
return process.platform === "win32" ? slashed.toLowerCase() : slashed;
|
|
65
|
-
};
|
|
66
|
-
return normalize(a) === normalize(b);
|
|
67
|
-
}
|
|
68
72
|
/** 压缩并截断一段用于日志的错误文本。 */
|
|
69
73
|
function describeError(error, max = 500) {
|
|
70
74
|
const text = error instanceof Error ? error.message : String(error);
|
|
@@ -73,8 +77,8 @@ function describeError(error, max = 500) {
|
|
|
73
77
|
//#endregion
|
|
74
78
|
//#region src/cli.ts
|
|
75
79
|
/**
|
|
76
|
-
* `lark-cli`
|
|
77
|
-
* 导出 LarkCli、CliError
|
|
80
|
+
* `lark-cli` 适配层:调用本机命令、管理子进程、解析 JSON envelope。
|
|
81
|
+
* 导出 LarkCli、CliError 与进程构造辅助函数。
|
|
78
82
|
*/
|
|
79
83
|
/** CLI 调用失败。 */
|
|
80
84
|
var CliError = class extends Error {
|
|
@@ -89,88 +93,45 @@ var CliError = class extends Error {
|
|
|
89
93
|
this.exitCode = exitCode;
|
|
90
94
|
}
|
|
91
95
|
};
|
|
92
|
-
|
|
93
|
-
const
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
96
|
+
/** Windows 命令字符串只允许不需要转义的安全 token。 */
|
|
97
|
+
const WINDOWS_SAFE_TOKEN = /^[A-Za-z0-9._:+-]+$/;
|
|
98
|
+
/** 构造进程参数;Windows 用安全 token 组成单一命令字符串。 */
|
|
99
|
+
function createSpawnSpec(command, args, platform = process.platform) {
|
|
100
|
+
const tokens = [
|
|
101
|
+
command.file,
|
|
102
|
+
...command.args,
|
|
103
|
+
...args
|
|
104
|
+
];
|
|
105
|
+
if (platform !== "win32") return {
|
|
106
|
+
file: command.file,
|
|
107
|
+
args: [...command.args, ...args],
|
|
108
|
+
shell: false
|
|
105
109
|
};
|
|
106
|
-
const
|
|
107
|
-
|
|
108
|
-
file:
|
|
109
|
-
args: [
|
|
110
|
+
for (const token of tokens) if (token === "" || !WINDOWS_SAFE_TOKEN.test(token)) throw new CliError("unsafe-arg", "lark-cli argument contains unsupported Windows characters");
|
|
111
|
+
return {
|
|
112
|
+
file: tokens.join(" "),
|
|
113
|
+
args: [],
|
|
114
|
+
shell: true
|
|
110
115
|
};
|
|
111
116
|
}
|
|
112
|
-
/**
|
|
113
|
-
function
|
|
117
|
+
/** 启动 CLI 子进程,并把同步启动异常归一化为 CliError。 */
|
|
118
|
+
function createCliProcess(command, args, options, platform = process.platform, spawnFn = spawn) {
|
|
119
|
+
const spec = createSpawnSpec(command, args, platform);
|
|
114
120
|
try {
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
* @param explicit - 配置中的覆盖路径;空串表示未覆盖。
|
|
125
|
-
* @param env - 环境变量;默认 `process.env`。
|
|
126
|
-
* @param nodePath - 运行入口脚本时使用的 Node/Electron 路径。
|
|
127
|
-
* @returns 可执行的命令与固定参数。
|
|
128
|
-
*/
|
|
129
|
-
function resolveLarkCli(explicit = "", env = process.env, nodePath = process.execPath) {
|
|
130
|
-
const trimmed = explicit.trim();
|
|
131
|
-
if (trimmed !== "") {
|
|
132
|
-
if (/\.(c|m)?js$/i.test(trimmed)) return {
|
|
133
|
-
file: nodePath,
|
|
134
|
-
args: [trimmed]
|
|
135
|
-
};
|
|
136
|
-
return {
|
|
137
|
-
file: trimmed,
|
|
138
|
-
args: []
|
|
139
|
-
};
|
|
140
|
-
}
|
|
141
|
-
const fromEnv = String(env["LARK_CLI"] ?? "").trim();
|
|
142
|
-
if (fromEnv !== "") {
|
|
143
|
-
if (/\.(c|m)?js$/i.test(fromEnv)) return {
|
|
144
|
-
file: nodePath,
|
|
145
|
-
args: [fromEnv]
|
|
146
|
-
};
|
|
147
|
-
return {
|
|
148
|
-
file: fromEnv,
|
|
149
|
-
args: []
|
|
150
|
-
};
|
|
151
|
-
}
|
|
152
|
-
const packaged = resolvePackage(nodePath);
|
|
153
|
-
if (packaged !== void 0) return packaged;
|
|
154
|
-
const directories = String(env["PATH"] ?? env["Path"] ?? "").split(WINDOWS ? ";" : ":").filter((item) => item !== "");
|
|
155
|
-
for (const directory of directories) {
|
|
156
|
-
const local = fromPackageDir(join(directory, "node_modules", "@larksuite", "cli"), nodePath);
|
|
157
|
-
if (local !== void 0) return local;
|
|
158
|
-
const direct = join(directory, WINDOWS ? "lark-cli.exe" : "lark-cli");
|
|
159
|
-
if (hasFile(direct)) return {
|
|
160
|
-
file: direct,
|
|
161
|
-
args: []
|
|
162
|
-
};
|
|
163
|
-
}
|
|
164
|
-
const appData = String(env["APPDATA"] ?? "").trim();
|
|
165
|
-
if (appData !== "") {
|
|
166
|
-
const global = fromPackageDir(join(appData, "npm", "node_modules", "@larksuite", "cli"), nodePath);
|
|
167
|
-
if (global !== void 0) return global;
|
|
121
|
+
return spec.shell ? spawnFn(spec.file, {
|
|
122
|
+
...options,
|
|
123
|
+
shell: true
|
|
124
|
+
}) : spawnFn(spec.file, [...spec.args], {
|
|
125
|
+
...options,
|
|
126
|
+
shell: false
|
|
127
|
+
});
|
|
128
|
+
} catch (error) {
|
|
129
|
+
throw new CliError("spawn-failed", describeError(error));
|
|
168
130
|
}
|
|
169
|
-
return {
|
|
170
|
-
file: "lark-cli",
|
|
171
|
-
args: []
|
|
172
|
-
};
|
|
173
131
|
}
|
|
132
|
+
const WINDOWS = process.platform === "win32";
|
|
133
|
+
const TIMEOUT_DEFAULT = 12e4;
|
|
134
|
+
const VIEWPORT = 10485760;
|
|
174
135
|
/** 杀掉子进程及其后代。 */
|
|
175
136
|
function killChildTree(child) {
|
|
176
137
|
if (child.pid === void 0) {
|
|
@@ -194,9 +155,9 @@ function killChildTree(child) {
|
|
|
194
155
|
}
|
|
195
156
|
child.kill("SIGTERM");
|
|
196
157
|
}
|
|
197
|
-
/**
|
|
158
|
+
/** 默认运行器:按平台安全调用本机命令。 */
|
|
198
159
|
const defaultRunner = (command, args, options) => new Promise((resolvePromise, reject) => {
|
|
199
|
-
const child =
|
|
160
|
+
const child = createCliProcess(command, args, {
|
|
200
161
|
windowsHide: true,
|
|
201
162
|
stdio: [
|
|
202
163
|
"pipe",
|
|
@@ -273,30 +234,19 @@ function parseJsonOutput(text) {
|
|
|
273
234
|
}
|
|
274
235
|
/** 面向插件的 CLI 封装。 */
|
|
275
236
|
var LarkCli = class {
|
|
276
|
-
/**
|
|
277
|
-
command
|
|
237
|
+
/** 固定的本机命令。 */
|
|
238
|
+
command = {
|
|
239
|
+
file: "lark-cli",
|
|
240
|
+
args: []
|
|
241
|
+
};
|
|
278
242
|
runner;
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
* @param explicit - 配置覆盖的可执行文件路径。
|
|
282
|
-
* @param runner - 运行器;测试注入。
|
|
283
|
-
* @param nodePath - 运行入口脚本的 Node 路径。
|
|
284
|
-
*/
|
|
285
|
-
constructor(explicit = "", runner = defaultRunner, nodePath = process.execPath) {
|
|
286
|
-
this.nodePath = nodePath;
|
|
287
|
-
this.command = resolveLarkCli(explicit, process.env, nodePath);
|
|
243
|
+
/** @param runner - 运行器;测试注入。 */
|
|
244
|
+
constructor(runner = defaultRunner) {
|
|
288
245
|
this.runner = runner;
|
|
289
246
|
}
|
|
290
247
|
/** 运行一次调用;非零退出码转为 CliError。 */
|
|
291
248
|
async run(args, options = {}) {
|
|
292
|
-
const
|
|
293
|
-
...options.env ?? {},
|
|
294
|
-
ELECTRON_RUN_AS_NODE: "1"
|
|
295
|
-
} : options.env ?? {};
|
|
296
|
-
const result = await this.runner(this.command, args, {
|
|
297
|
-
...options,
|
|
298
|
-
env
|
|
299
|
-
});
|
|
249
|
+
const result = await this.runner(this.command, args, options);
|
|
300
250
|
if (result.code !== 0 && options.allowFailure !== true) {
|
|
301
251
|
const detail = result.stderr.trim() !== "" ? result.stderr.trim() : result.stdout.trim() !== "" ? result.stdout.trim() : `exit ${result.code}`;
|
|
302
252
|
throw new CliError("exit", `lark-cli ${args.join(" ")} failed: ${detail.slice(0, 800)}`, result.code);
|
|
@@ -313,63 +263,27 @@ var LarkCli = class {
|
|
|
313
263
|
* @returns 子进程与 stdout/stderr 读取器。
|
|
314
264
|
*/
|
|
315
265
|
spawn(args) {
|
|
316
|
-
|
|
317
|
-
...process.env,
|
|
318
|
-
ELECTRON_RUN_AS_NODE: "1"
|
|
319
|
-
} : process.env;
|
|
320
|
-
return spawn(this.command.file, [...this.command.args, ...args], {
|
|
266
|
+
return createCliProcess(this.command, args, {
|
|
321
267
|
windowsHide: true,
|
|
322
268
|
stdio: [
|
|
323
269
|
"pipe",
|
|
324
270
|
"pipe",
|
|
325
271
|
"pipe"
|
|
326
272
|
],
|
|
327
|
-
env
|
|
273
|
+
env: process.env
|
|
328
274
|
});
|
|
329
275
|
}
|
|
330
276
|
};
|
|
331
277
|
//#endregion
|
|
332
|
-
//#region src/constants.ts
|
|
333
|
-
/** 共享常量:插件标识、默认值、工具名与状态目录。 */
|
|
334
|
-
/** 插件标识,与包名、cordis.patch.yml 的 id 一致。 */
|
|
335
|
-
const PLUGIN_LABEL = "dsh-plugin-lark-bridge";
|
|
336
|
-
/** 工具名。 */
|
|
337
|
-
const NOTIFY_TOOL_NAME = "lark_notify";
|
|
338
|
-
/** 桥接会话的默认标题。 */
|
|
339
|
-
const DEFAULT_SESSION_TITLE = "飞书";
|
|
340
|
-
/** 状态目录名,位于 DSH home 下。 */
|
|
341
|
-
const STATE_DIR = "lark-bridge";
|
|
342
|
-
/** 状态文件名。 */
|
|
343
|
-
const STATE_FILE = "state.json";
|
|
344
|
-
/** 单条飞书文本消息的最大字符数。 */
|
|
345
|
-
const MAX_MESSAGE_CHARS = 15e3;
|
|
346
|
-
/** 监听重启的初始与最大退避。 */
|
|
347
|
-
const RESTART_MIN_MS = 2e3;
|
|
348
|
-
const RESTART_MAX_MS = 6e4;
|
|
349
|
-
//#endregion
|
|
350
278
|
//#region src/auth.ts
|
|
351
279
|
/**
|
|
352
|
-
* lark-cli
|
|
353
|
-
* 导出
|
|
280
|
+
* lark-cli 连接状态机:独立探测 CLI、bot 身份与用户身份。
|
|
281
|
+
* 导出 AuthSnapshot 与 AuthManager。
|
|
354
282
|
*/
|
|
355
283
|
/** 把未知值收窄为对象。 */
|
|
356
284
|
function recordOf(value) {
|
|
357
285
|
return typeof value === "object" && value !== null ? value : {};
|
|
358
286
|
}
|
|
359
|
-
/** 读取设备码输出。 */
|
|
360
|
-
function parseLoginFlow(value) {
|
|
361
|
-
const record = recordOf(value);
|
|
362
|
-
const url = record["verification_url"];
|
|
363
|
-
const code = record["device_code"];
|
|
364
|
-
const expires = Number(record["expires_in"]);
|
|
365
|
-
if (typeof url !== "string" || url === "") throw new CliError("invalid-login", "lark-cli did not return a verification URL");
|
|
366
|
-
if (typeof code !== "string" || code === "") throw new CliError("invalid-login", "lark-cli did not return a device code");
|
|
367
|
-
return {
|
|
368
|
-
verificationUrl: url,
|
|
369
|
-
deviceCode: code,
|
|
370
|
-
expiresAt: Date.now() + (Number.isFinite(expires) && expires > 0 ? expires : 600) * 1e3
|
|
371
|
-
};
|
|
372
|
-
}
|
|
373
287
|
/** 读取 auth status 的身份信息。 */
|
|
374
288
|
function statusIdentities(value) {
|
|
375
289
|
const root = recordOf(value);
|
|
@@ -380,7 +294,6 @@ function statusIdentities(value) {
|
|
|
380
294
|
appId: typeof root["appId"] === "string" ? root["appId"] : void 0,
|
|
381
295
|
bot: typeof bot["status"] === "string" ? bot["status"] : void 0,
|
|
382
296
|
user: {
|
|
383
|
-
status: typeof user["status"] === "string" ? user["status"] : void 0,
|
|
384
297
|
openId: typeof user["openId"] === "string" ? user["openId"] : void 0,
|
|
385
298
|
name: typeof user["userName"] === "string" ? user["userName"] : void 0
|
|
386
299
|
}
|
|
@@ -399,55 +312,49 @@ async function probeCli(cli) {
|
|
|
399
312
|
return true;
|
|
400
313
|
}
|
|
401
314
|
}
|
|
402
|
-
/**
|
|
315
|
+
/** 构造检测完成后的基础快照。 */
|
|
316
|
+
function disconnected(checkedAt) {
|
|
317
|
+
return {
|
|
318
|
+
cli: "disconnected",
|
|
319
|
+
bot: "disconnected",
|
|
320
|
+
user: "disconnected",
|
|
321
|
+
ready: false,
|
|
322
|
+
checkedAt,
|
|
323
|
+
appId: void 0,
|
|
324
|
+
userName: void 0,
|
|
325
|
+
ownerOpenId: void 0,
|
|
326
|
+
detail: void 0
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
/** 完整检测与状态发布。 */
|
|
403
330
|
var AuthManager = class {
|
|
404
331
|
deps;
|
|
405
332
|
snapshot;
|
|
406
333
|
checking;
|
|
407
|
-
flow;
|
|
408
|
-
completing;
|
|
409
|
-
cancelled = 0;
|
|
410
334
|
constructor(deps) {
|
|
411
335
|
this.deps = deps;
|
|
412
336
|
this.snapshot = {
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
userName: void 0,
|
|
418
|
-
ownerOpenId: void 0,
|
|
419
|
-
checkedAt: 0,
|
|
420
|
-
detail: void 0
|
|
337
|
+
...disconnected(0),
|
|
338
|
+
cli: "checking",
|
|
339
|
+
bot: "checking",
|
|
340
|
+
user: "checking"
|
|
421
341
|
};
|
|
422
342
|
}
|
|
423
343
|
/** 最近一次检测结果。 */
|
|
424
344
|
get current() {
|
|
425
345
|
return this.snapshot;
|
|
426
346
|
}
|
|
427
|
-
/**
|
|
428
|
-
|
|
429
|
-
return this.flow;
|
|
430
|
-
}
|
|
431
|
-
/** 重新检测;并发调用共享同一次检查。 */
|
|
432
|
-
check(options = {}) {
|
|
347
|
+
/** 完整检测;并发调用共享同一次检查。 */
|
|
348
|
+
check() {
|
|
433
349
|
if (this.checking !== void 0) return this.checking;
|
|
434
|
-
this.checking = this.runCheck(
|
|
350
|
+
this.checking = this.runCheck().finally(() => {
|
|
435
351
|
this.checking = void 0;
|
|
436
352
|
});
|
|
437
353
|
return this.checking;
|
|
438
354
|
}
|
|
439
|
-
async runCheck(
|
|
355
|
+
async runCheck() {
|
|
440
356
|
const cli = this.deps.getCli();
|
|
441
|
-
const base =
|
|
442
|
-
stage: "cli-missing",
|
|
443
|
-
ready: false,
|
|
444
|
-
appId: void 0,
|
|
445
|
-
botStatus: void 0,
|
|
446
|
-
userName: void 0,
|
|
447
|
-
ownerOpenId: void 0,
|
|
448
|
-
checkedAt: Date.now(),
|
|
449
|
-
detail: void 0
|
|
450
|
-
};
|
|
357
|
+
const base = disconnected(Date.now());
|
|
451
358
|
let next;
|
|
452
359
|
if (!await probeCli(cli)) next = base;
|
|
453
360
|
else try {
|
|
@@ -455,93 +362,32 @@ var AuthManager = class {
|
|
|
455
362
|
"auth",
|
|
456
363
|
"status",
|
|
457
364
|
"--json",
|
|
458
|
-
|
|
365
|
+
"--verify"
|
|
459
366
|
], { timeoutMs: 6e4 }));
|
|
460
367
|
const owner = identities.user.openId;
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
};
|
|
466
|
-
else if (owner === void 0 || owner === "") next = {
|
|
467
|
-
...base,
|
|
468
|
-
stage: "user-missing",
|
|
469
|
-
appId: identities.appId,
|
|
470
|
-
botStatus: identities.bot,
|
|
471
|
-
userName: identities.user.name
|
|
472
|
-
};
|
|
473
|
-
else next = {
|
|
368
|
+
const botReady = identities.bot === "ready";
|
|
369
|
+
const userReady = owner !== void 0 && owner !== "";
|
|
370
|
+
const ready = botReady && userReady;
|
|
371
|
+
next = {
|
|
474
372
|
...base,
|
|
475
|
-
|
|
476
|
-
|
|
373
|
+
cli: "connected",
|
|
374
|
+
bot: botReady ? "connected" : "disconnected",
|
|
375
|
+
user: userReady ? "connected" : "disconnected",
|
|
376
|
+
ready,
|
|
477
377
|
appId: identities.appId,
|
|
478
|
-
botStatus: identities.bot,
|
|
479
378
|
userName: identities.user.name,
|
|
480
|
-
ownerOpenId: owner
|
|
379
|
+
ownerOpenId: ready ? owner : void 0
|
|
481
380
|
};
|
|
482
381
|
} catch (error) {
|
|
483
382
|
next = {
|
|
484
383
|
...base,
|
|
485
|
-
|
|
384
|
+
cli: "connected",
|
|
486
385
|
detail: describeError(error)
|
|
487
386
|
};
|
|
488
387
|
}
|
|
489
388
|
this.publish(next);
|
|
490
389
|
return next;
|
|
491
390
|
}
|
|
492
|
-
/**
|
|
493
|
-
* 启动设备码授权。
|
|
494
|
-
* @returns 授权链接与设备码;完成后台轮询。
|
|
495
|
-
*/
|
|
496
|
-
async startLogin() {
|
|
497
|
-
const cli = this.deps.getCli();
|
|
498
|
-
const scope = this.deps.loginScope ?? "auth:user.id:read";
|
|
499
|
-
const flow = parseLoginFlow(await cli.json([
|
|
500
|
-
"auth",
|
|
501
|
-
"login",
|
|
502
|
-
"--no-wait",
|
|
503
|
-
"--json",
|
|
504
|
-
"--scope",
|
|
505
|
-
scope
|
|
506
|
-
], { timeoutMs: 6e4 }));
|
|
507
|
-
this.flow = flow;
|
|
508
|
-
this.cancelled += 1;
|
|
509
|
-
const generation = this.cancelled;
|
|
510
|
-
this.deps.logger.info(`lark-bridge: device login started, expires at ${new Date(flow.expiresAt).toISOString()}`);
|
|
511
|
-
this.completing = this.completeLogin(flow, generation);
|
|
512
|
-
return flow;
|
|
513
|
-
}
|
|
514
|
-
/** 后台完成设备码授权;失败时记录并刷新状态。 */
|
|
515
|
-
async completeLogin(flow, generation) {
|
|
516
|
-
const cli = this.deps.getCli();
|
|
517
|
-
const remaining = Math.max(3e4, flow.expiresAt - Date.now() + 15e3);
|
|
518
|
-
try {
|
|
519
|
-
await cli.run([
|
|
520
|
-
"auth",
|
|
521
|
-
"login",
|
|
522
|
-
"--device-code",
|
|
523
|
-
flow.deviceCode,
|
|
524
|
-
"--json"
|
|
525
|
-
], { timeoutMs: remaining });
|
|
526
|
-
if (generation !== this.cancelled) return this.snapshot;
|
|
527
|
-
this.flow = void 0;
|
|
528
|
-
return await this.check({ verify: true });
|
|
529
|
-
} catch (error) {
|
|
530
|
-
if (generation !== this.cancelled) return this.snapshot;
|
|
531
|
-
this.flow = void 0;
|
|
532
|
-
this.deps.logger.warn(`lark-bridge: device login failed: ${describeError(error)}`);
|
|
533
|
-
return this.check();
|
|
534
|
-
}
|
|
535
|
-
}
|
|
536
|
-
/** 等待后台授权结束;测试与关闭流程使用。 */
|
|
537
|
-
async whenLoginSettled() {
|
|
538
|
-
return this.completing === void 0 ? void 0 : this.completing;
|
|
539
|
-
}
|
|
540
|
-
/** 取消当前授权;后台轮询的结果会被丢弃。 */
|
|
541
|
-
cancelLogin() {
|
|
542
|
-
this.cancelled += 1;
|
|
543
|
-
this.flow = void 0;
|
|
544
|
-
}
|
|
545
391
|
/** 更新快照并通知订阅者。 */
|
|
546
392
|
publish(next) {
|
|
547
393
|
this.snapshot = next;
|
|
@@ -549,27 +395,183 @@ var AuthManager = class {
|
|
|
549
395
|
}
|
|
550
396
|
};
|
|
551
397
|
//#endregion
|
|
398
|
+
//#region src/constants.ts
|
|
399
|
+
/** 共享常量:插件标识、默认值、工具名与状态目录。 */
|
|
400
|
+
/** 插件标识,与包名、cordis.patch.yml 的 id 一致。 */
|
|
401
|
+
const PLUGIN_LABEL = "dsh-plugin-lark-bridge";
|
|
402
|
+
/** 工具名。 */
|
|
403
|
+
const NOTIFY_TOOL_NAME = "lark_notify";
|
|
404
|
+
/** 桥接会话的固定标题。 */
|
|
405
|
+
const SESSION_TITLE = "飞书桥接会话";
|
|
406
|
+
/** 状态目录名,位于 DSH home 下。 */
|
|
407
|
+
const STATE_DIR = "lark-bridge";
|
|
408
|
+
/** 状态文件名。 */
|
|
409
|
+
const STATE_FILE = "state.json";
|
|
410
|
+
/** 单条飞书文本消息的最大字符数。 */
|
|
411
|
+
const MAX_MESSAGE_CHARS = 15e3;
|
|
412
|
+
/** 读取被引消息单次调用的超时毫秒数。 */
|
|
413
|
+
const QUOTE_TIMEOUT_MS = 8e3;
|
|
414
|
+
/** 注入前的静默窗口:队列在此期间没有新消息才发起注入。 */
|
|
415
|
+
const INJECT_SILENCE_MS = 15e3;
|
|
416
|
+
/** 监听重启的初始与最大退避。 */
|
|
417
|
+
const RESTART_MIN_MS = 2e3;
|
|
418
|
+
const RESTART_MAX_MS = 6e4;
|
|
419
|
+
//#endregion
|
|
420
|
+
//#region src/quote.ts
|
|
421
|
+
/** 读取身份顺序:user 优先,bot 兜底。 */
|
|
422
|
+
const IDENTITIES = ["user", "bot"];
|
|
423
|
+
/** 读取失败时的引用模型。 */
|
|
424
|
+
function unavailableQuote(messageId) {
|
|
425
|
+
return {
|
|
426
|
+
messageId,
|
|
427
|
+
from: "user",
|
|
428
|
+
time: "",
|
|
429
|
+
kind: "text",
|
|
430
|
+
text: "",
|
|
431
|
+
unavailable: true
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
/** 从 mget 输出中取出第一条消息。 */
|
|
435
|
+
function firstMessage(value) {
|
|
436
|
+
if (!isRecord(value)) return void 0;
|
|
437
|
+
const messages = value["messages"];
|
|
438
|
+
if (!Array.isArray(messages)) return void 0;
|
|
439
|
+
const first = messages[0];
|
|
440
|
+
return isRecord(first) ? first : void 0;
|
|
441
|
+
}
|
|
442
|
+
/** mget 已格式化的时间文本(`YYYY-MM-DD HH:mm[:ss]`)。 */
|
|
443
|
+
const MGET_TIME = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}(?::\d{2})?$/;
|
|
444
|
+
/** 归一时间:mget 已在本机时区格式化,直接沿用;其他形式交给 formatTime。 */
|
|
445
|
+
function quoteTime(value) {
|
|
446
|
+
if (typeof value !== "string") return "";
|
|
447
|
+
const text = value.trim();
|
|
448
|
+
if (MGET_TIME.test(text)) return text.length === 16 ? `${text}:00` : text;
|
|
449
|
+
return formatTime(text);
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* 把一条 mget 消息转成引用模型。
|
|
453
|
+
* @param messageId - 被引消息标识。
|
|
454
|
+
* @param raw - mget 返回的单条消息。
|
|
455
|
+
*/
|
|
456
|
+
function toQuotedMessage(messageId, raw) {
|
|
457
|
+
const senderType = (isRecord(raw["sender"]) ? raw["sender"] : {})["sender_type"];
|
|
458
|
+
const from = senderType === "bot" || senderType === "app" ? "bot" : "user";
|
|
459
|
+
const type = String(raw["msg_type"] ?? "text");
|
|
460
|
+
const content = typeof raw["content"] === "string" ? raw["content"].trim() : "";
|
|
461
|
+
const time = quoteTime(raw["create_time"]);
|
|
462
|
+
if (type === "merge_forward") return {
|
|
463
|
+
messageId,
|
|
464
|
+
from,
|
|
465
|
+
time,
|
|
466
|
+
kind: "forwarded",
|
|
467
|
+
text: "",
|
|
468
|
+
unavailable: false
|
|
469
|
+
};
|
|
470
|
+
if (type !== "text" && type !== "post") return {
|
|
471
|
+
messageId,
|
|
472
|
+
from,
|
|
473
|
+
time,
|
|
474
|
+
kind: "other",
|
|
475
|
+
text: `[${type} 消息]`,
|
|
476
|
+
unavailable: false
|
|
477
|
+
};
|
|
478
|
+
return {
|
|
479
|
+
messageId,
|
|
480
|
+
from,
|
|
481
|
+
time,
|
|
482
|
+
kind: "text",
|
|
483
|
+
text: content === "" ? `[${type} 消息]` : content,
|
|
484
|
+
unavailable: false
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* 把引用正文截断到上限,去掉代理对残留。
|
|
489
|
+
* @param text - 原始正文。
|
|
490
|
+
* @param limit - 最大字符数。
|
|
491
|
+
*/
|
|
492
|
+
function truncateQuote(text, limit = 500) {
|
|
493
|
+
if (text.length <= limit) return text;
|
|
494
|
+
return `${splitText(text, limit)[0] ?? ""}(已截断)`;
|
|
495
|
+
}
|
|
496
|
+
/** 转义引用正文中的块结束标记。 */
|
|
497
|
+
function escapeBody(text) {
|
|
498
|
+
return text.replaceAll("</quote>", "<\\/quote>").replaceAll("</lark-message>", "<\\/lark-message>");
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* 渲染 `<quote>` 块。
|
|
502
|
+
* @param quote - 被引消息。
|
|
503
|
+
*/
|
|
504
|
+
function formatQuote(quote) {
|
|
505
|
+
const attributes = [`message_id="${escapeAttribute(quote.messageId)}"`, `from="${quote.from}"`];
|
|
506
|
+
if (quote.time !== "") attributes.push(`time="${escapeAttribute(quote.time)}"`);
|
|
507
|
+
let body = "[引用内容读取失败]";
|
|
508
|
+
if (!quote.unavailable) {
|
|
509
|
+
if (quote.kind === "forwarded") body = `<forwarded_messages message_id="${escapeAttribute(quote.messageId)}"/>`;
|
|
510
|
+
else body = escapeBody(truncateQuote(quote.text));
|
|
511
|
+
}
|
|
512
|
+
return `<quote ${attributes.join(" ")}>\n${body}\n</quote>`;
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* 读取被引消息:user 身份优先,bot 兜底,均失败时返回不可用引用。
|
|
516
|
+
* @param cli - lark-cli 适配层。
|
|
517
|
+
* @param messageId - 被引消息标识。
|
|
518
|
+
* @param timeoutMs - 单次调用超时。
|
|
519
|
+
*/
|
|
520
|
+
async function readQuoted(cli, messageId, timeoutMs = QUOTE_TIMEOUT_MS) {
|
|
521
|
+
for (const identity of IDENTITIES) {
|
|
522
|
+
let value;
|
|
523
|
+
try {
|
|
524
|
+
value = await cli.json([
|
|
525
|
+
"im",
|
|
526
|
+
"+messages-mget",
|
|
527
|
+
"--as",
|
|
528
|
+
identity,
|
|
529
|
+
"--message-ids",
|
|
530
|
+
messageId,
|
|
531
|
+
"--no-reactions"
|
|
532
|
+
], { timeoutMs });
|
|
533
|
+
} catch {
|
|
534
|
+
continue;
|
|
535
|
+
}
|
|
536
|
+
const raw = firstMessage(value);
|
|
537
|
+
if (raw === void 0 || raw["deleted"] === true) continue;
|
|
538
|
+
return toQuotedMessage(messageId, raw);
|
|
539
|
+
}
|
|
540
|
+
return unavailableQuote(messageId);
|
|
541
|
+
}
|
|
542
|
+
//#endregion
|
|
552
543
|
//#region src/bridge.ts
|
|
553
544
|
/**
|
|
554
545
|
* 飞书事件桥:消费 bot 身份事件、过滤与去重,并把消息注入桥接会话。
|
|
555
|
-
* 导出 EventBridge 与
|
|
546
|
+
* 导出 EventBridge 与 formatLarkMessage。
|
|
556
547
|
*/
|
|
557
|
-
/**
|
|
558
|
-
function
|
|
559
|
-
|
|
560
|
-
const text = typeof event.content === "string" ? event.content.trim() : "";
|
|
561
|
-
const type = String(event.message_type ?? event.msg_type ?? "text");
|
|
562
|
-
const body = text === "" ? `[${type} 消息]` : text;
|
|
563
|
-
const id = String(event.message_id ?? event.id ?? "");
|
|
564
|
-
const header = ["飞书消息", `发送者:${senderName}`];
|
|
565
|
-
if (time !== "") header.push(`时间:${time}`);
|
|
566
|
-
if (id !== "") header.push(`消息 ID:${id}`);
|
|
567
|
-
return `${header.join("\n")}\n\n${body}`;
|
|
548
|
+
/** 把队列条目拼成日志用的 `id@创建时间/到达时间` 列表。 */
|
|
549
|
+
function describeQueue(items) {
|
|
550
|
+
return items.map((item) => `${item.id}@${formatTime(item.createdAt)}/${formatTime(item.receivedAt)}`).join(",");
|
|
568
551
|
}
|
|
569
552
|
/** 返回事件的消息标识。 */
|
|
570
553
|
function messageId(event) {
|
|
571
554
|
return String(event.message_id ?? event.id ?? "");
|
|
572
555
|
}
|
|
556
|
+
/** 返回事件的被引消息标识;没有引用时为空串。 */
|
|
557
|
+
function replyToId(event) {
|
|
558
|
+
return typeof event.reply_to === "string" ? event.reply_to.trim() : "";
|
|
559
|
+
}
|
|
560
|
+
/** 把一条飞书消息渲染为 `<lark-message>` 块。 */
|
|
561
|
+
function formatLarkMessage(event, quote) {
|
|
562
|
+
const time = formatTime(parseTimestamp(event.timestamp ?? event.create_time));
|
|
563
|
+
const text = typeof event.content === "string" ? event.content.trim() : "";
|
|
564
|
+
const type = String(event.message_type ?? event.msg_type ?? "text");
|
|
565
|
+
const id = escapeAttribute(messageId(event));
|
|
566
|
+
const replyTo = escapeAttribute(replyToId(event));
|
|
567
|
+
const attributes = [`message_id="${id}"`];
|
|
568
|
+
if (replyTo !== "") attributes.push(`reply_to="${replyTo}"`);
|
|
569
|
+
if (time !== "") attributes.push(`time="${time}"`);
|
|
570
|
+
let body = text === "" ? `[${type} 消息]` : escapeBlockText(text);
|
|
571
|
+
if (type === "merge_forward") body = `<forwarded_messages message_id="${id}"/>`;
|
|
572
|
+
const inner = quote === void 0 ? body : `${formatQuote(quote)}\n${body}`;
|
|
573
|
+
return `<lark-message ${attributes.join(" ")}>\n${inner}\n</lark-message>`;
|
|
574
|
+
}
|
|
573
575
|
/** 判断事件是否来自目标用户的私聊。 */
|
|
574
576
|
function acceptEvent(event, ownerOpenId) {
|
|
575
577
|
if (event.chat_type !== "p2p") return false;
|
|
@@ -584,6 +586,9 @@ var EventBridge = class {
|
|
|
584
586
|
backoff = RESTART_MIN_MS;
|
|
585
587
|
startedAt = 0;
|
|
586
588
|
stopped = true;
|
|
589
|
+
queue = [];
|
|
590
|
+
silenceTimer;
|
|
591
|
+
draining = false;
|
|
587
592
|
constructor(deps) {
|
|
588
593
|
this.deps = deps;
|
|
589
594
|
}
|
|
@@ -591,9 +596,9 @@ var EventBridge = class {
|
|
|
591
596
|
get running() {
|
|
592
597
|
return this.child !== void 0;
|
|
593
598
|
}
|
|
594
|
-
/**
|
|
599
|
+
/** 鉴权与工作区均有效时启动;否则保持停止。 */
|
|
595
600
|
start() {
|
|
596
|
-
if (this.deps.getAuth().ready !== true) return;
|
|
601
|
+
if (this.deps.getAuth().ready !== true || !this.deps.getWorkspaceReady()) return;
|
|
597
602
|
this.stopped = false;
|
|
598
603
|
this.spawn();
|
|
599
604
|
}
|
|
@@ -602,17 +607,23 @@ var EventBridge = class {
|
|
|
602
607
|
this.stopped = true;
|
|
603
608
|
if (this.restartTimer !== void 0) clearTimeout(this.restartTimer);
|
|
604
609
|
this.restartTimer = void 0;
|
|
610
|
+
if (this.silenceTimer !== void 0) clearTimeout(this.silenceTimer);
|
|
611
|
+
this.silenceTimer = void 0;
|
|
612
|
+
if (this.queue.length > 0) {
|
|
613
|
+
this.deps.logger.warn(`lark-bridge: dropped ${this.queue.length} queued message(s) [${describeQueue(this.queue)}] on stop`);
|
|
614
|
+
this.queue.length = 0;
|
|
615
|
+
}
|
|
605
616
|
const child = this.child;
|
|
606
617
|
this.child = void 0;
|
|
607
618
|
if (child !== void 0) killChildTree(child);
|
|
608
619
|
}
|
|
609
|
-
/**
|
|
620
|
+
/** 鉴权或工作区状态变化时同步监听;工作区变化不停止已运行的监听。 */
|
|
610
621
|
sync(snapshot) {
|
|
611
|
-
if (snapshot.ready) {
|
|
612
|
-
|
|
622
|
+
if (!snapshot.ready) {
|
|
623
|
+
this.stop();
|
|
613
624
|
return;
|
|
614
625
|
}
|
|
615
|
-
this.
|
|
626
|
+
if (!this.running && this.deps.getWorkspaceReady()) this.start();
|
|
616
627
|
}
|
|
617
628
|
/** 启动一个消费者子进程。 */
|
|
618
629
|
spawn() {
|
|
@@ -688,113 +699,296 @@ var EventBridge = class {
|
|
|
688
699
|
}, delay);
|
|
689
700
|
this.restartTimer.unref?.();
|
|
690
701
|
}
|
|
691
|
-
/**
|
|
702
|
+
/** 处理一条事件:过滤、去重、过滤过期消息、读取引用并放入队列。 */
|
|
692
703
|
async handleEvent(event) {
|
|
704
|
+
const id = messageId(event);
|
|
705
|
+
if (id === "") return false;
|
|
693
706
|
const auth = this.deps.getAuth();
|
|
694
|
-
if (auth.ready !== true) return false;
|
|
695
707
|
const owner = auth.ownerOpenId;
|
|
696
|
-
if (owner === void 0 || owner === "")
|
|
708
|
+
if (auth.ready !== true || owner === void 0 || owner === "") {
|
|
709
|
+
this.deps.logger.warn(`lark-bridge: dropped ${id}: auth not ready`);
|
|
710
|
+
return false;
|
|
711
|
+
}
|
|
697
712
|
if (!acceptEvent(event, owner)) return false;
|
|
698
|
-
const
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
if (
|
|
702
|
-
|
|
713
|
+
const createdAt = parseTimestamp(event.timestamp ?? event.create_time);
|
|
714
|
+
const receivedAt = Date.now();
|
|
715
|
+
if (!await this.deps.store.markSeen(id, createdAt)) return false;
|
|
716
|
+
if (createdAt < this.startedAt) {
|
|
717
|
+
this.deps.logger.warn(`lark-bridge: filtered ${id} created=${formatTime(createdAt)} received=${formatTime(receivedAt)} listenerStart=${formatTime(this.startedAt)}`);
|
|
718
|
+
return false;
|
|
719
|
+
}
|
|
720
|
+
const quote = await this.readQuote(event);
|
|
721
|
+
this.queue.push({
|
|
722
|
+
id,
|
|
723
|
+
createdAt,
|
|
724
|
+
receivedAt,
|
|
725
|
+
block: formatLarkMessage(event, quote)
|
|
726
|
+
});
|
|
727
|
+
this.schedule();
|
|
728
|
+
return true;
|
|
729
|
+
}
|
|
730
|
+
/** 重置静默计时;窗口内没有新消息时发起注入。 */
|
|
731
|
+
schedule() {
|
|
732
|
+
if (this.silenceTimer !== void 0) clearTimeout(this.silenceTimer);
|
|
733
|
+
const timer = setTimeout(() => {
|
|
734
|
+
this.silenceTimer = void 0;
|
|
735
|
+
this.drain();
|
|
736
|
+
}, INJECT_SILENCE_MS);
|
|
737
|
+
timer.unref?.();
|
|
738
|
+
this.silenceTimer = timer;
|
|
739
|
+
}
|
|
740
|
+
/** 取空队列并按创建时间升序批量注入;失败的批次直接丢弃。 */
|
|
741
|
+
async drain() {
|
|
742
|
+
if (this.draining || this.queue.length === 0) return;
|
|
743
|
+
this.draining = true;
|
|
703
744
|
try {
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
745
|
+
while (this.queue.length > 0) {
|
|
746
|
+
const batch = this.queue.splice(0).sort((a, b) => a.createdAt - b.createdAt);
|
|
747
|
+
const text = batch.map((item) => item.block).join("\n\n");
|
|
748
|
+
const ids = batch.map((item) => `${item.id}@${formatTime(item.createdAt)}/${formatTime(item.receivedAt)}`).join(",");
|
|
749
|
+
try {
|
|
750
|
+
const result = await this.deps.sessions.inject(text);
|
|
751
|
+
this.deps.logger.info(`lark-bridge: delivered ${batch.length} message(s) [${ids}] to session ${result.sessionId} (created=${String(result.created)})`);
|
|
752
|
+
} catch (error) {
|
|
753
|
+
this.deps.logger.warn(`lark-bridge: failed ${batch.length} message(s) [${ids}]: ${describeError(error)}`);
|
|
754
|
+
}
|
|
755
|
+
if (this.silenceTimer !== void 0) return;
|
|
756
|
+
}
|
|
757
|
+
} finally {
|
|
758
|
+
this.draining = false;
|
|
759
|
+
if (this.queue.length > 0 && this.silenceTimer === void 0) this.schedule();
|
|
710
760
|
}
|
|
711
761
|
}
|
|
762
|
+
/** 读取被引消息;没有引用或读取失败时返回降级模型。 */
|
|
763
|
+
async readQuote(event) {
|
|
764
|
+
const replyTo = replyToId(event);
|
|
765
|
+
if (replyTo === "") return void 0;
|
|
766
|
+
const quote = await readQuoted(this.deps.getCli(), replyTo);
|
|
767
|
+
if (quote.unavailable) this.deps.logger.warn(`lark-bridge: cannot read quoted message ${replyTo}`);
|
|
768
|
+
return quote;
|
|
769
|
+
}
|
|
712
770
|
};
|
|
713
771
|
//#endregion
|
|
772
|
+
//#region src/workspace-path.ts
|
|
773
|
+
/** 工作区路径:统一 Linux 风格表示、平台比较与 Host 原生路径转换。 */
|
|
774
|
+
/** 判断原始或归一化路径是否使用 Windows 语义。 */
|
|
775
|
+
function isWindowsPath(value) {
|
|
776
|
+
return /^(?:[A-Za-z]:[\\/]|\\\\|\/\/|\/[A-Za-z](?:\/|$))/.test(value);
|
|
777
|
+
}
|
|
778
|
+
/** 统一斜杠、末尾分隔符与 Windows 盘符,例如 `C:\work\demo` 转为 `/c/work/demo`。 */
|
|
779
|
+
function normalizeWorkspacePath(value) {
|
|
780
|
+
const slashed = value.trim().replaceAll("\\", "/");
|
|
781
|
+
if (slashed === "") return "";
|
|
782
|
+
const drive = /^([A-Za-z]):(?:\/+(.*))?$/.exec(slashed);
|
|
783
|
+
if (drive !== null) {
|
|
784
|
+
const rest = (drive[2] ?? "").replace(/\/{2,}/g, "/").replace(/\/+$/, "");
|
|
785
|
+
return `/${drive[1]?.toLowerCase()}${rest === "" ? "" : `/${rest}`}`;
|
|
786
|
+
}
|
|
787
|
+
const unc = slashed.startsWith("//");
|
|
788
|
+
const collapsed = slashed.replace(/\/{2,}/g, "/");
|
|
789
|
+
const withoutTrailing = collapsed.length > 1 ? collapsed.replace(/\/+$/, "") : collapsed;
|
|
790
|
+
return unc ? `/${withoutTrailing}` : withoutTrailing;
|
|
791
|
+
}
|
|
792
|
+
/** 比较工作区路径;Windows 忽略大小写,POSIX 保持大小写敏感。 */
|
|
793
|
+
function sameWorkspacePath(a, b) {
|
|
794
|
+
const left = normalizeWorkspacePath(a);
|
|
795
|
+
const right = normalizeWorkspacePath(b);
|
|
796
|
+
return isWindowsPath(a) || isWindowsPath(b) ? left.toLowerCase() === right.toLowerCase() : left === right;
|
|
797
|
+
}
|
|
798
|
+
/** 在 Host 边界把归一化路径转换为当前平台的原生形式。 */
|
|
799
|
+
function toHostWorkspacePath(value, platform = process.platform) {
|
|
800
|
+
const normalized = normalizeWorkspacePath(value);
|
|
801
|
+
if (platform !== "win32") return normalized;
|
|
802
|
+
const drive = /^\/([A-Za-z])(?:\/(.*))?$/.exec(normalized);
|
|
803
|
+
if (drive !== null) return `${drive[1]?.toUpperCase()}:${drive[2] === void 0 ? "/" : `/${drive[2]}`}`;
|
|
804
|
+
if (normalized.startsWith("//")) return `\\\\${normalized.slice(2).replaceAll("/", "\\")}`;
|
|
805
|
+
return normalized;
|
|
806
|
+
}
|
|
807
|
+
//#endregion
|
|
714
808
|
//#region src/config.ts
|
|
715
|
-
/**
|
|
716
|
-
|
|
717
|
-
* 导出 Config、PluginConfig、resolveConfig 与 readConfig。
|
|
718
|
-
*/
|
|
719
|
-
/**
|
|
720
|
-
* 配置 schema。`.volatile()` 字段修改后不重启插件,并出现在配置页。
|
|
721
|
-
* schema 不拒绝未知键,严格校验由 resolveConfig 完成。
|
|
722
|
-
*/
|
|
809
|
+
/** 插件配置:单工作区 schema、路径归一化、严格校验与旧键兼容。 */
|
|
810
|
+
/** 配置 schema;严格键校验由 resolveConfig 完成。 */
|
|
723
811
|
const Config = Schema.object({
|
|
724
812
|
workspaceRoot: Schema.string().default("").volatile(),
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
813
|
+
sessionProvider: Schema.string().default("").volatile(),
|
|
814
|
+
sessionModel: Schema.string().default("").volatile(),
|
|
815
|
+
sessionEffort: Schema.string().default("").volatile(),
|
|
816
|
+
sessionPreset: Schema.string().default("").volatile()
|
|
728
817
|
});
|
|
729
818
|
/** 默认配置。 */
|
|
730
819
|
const DEFAULT_CONFIG = Object.freeze({
|
|
731
820
|
workspaceRoot: "",
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
821
|
+
sessionProvider: "",
|
|
822
|
+
sessionModel: "",
|
|
823
|
+
sessionEffort: "",
|
|
824
|
+
sessionPreset: ""
|
|
735
825
|
});
|
|
736
|
-
/**
|
|
826
|
+
/** 合法的当前配置键。 */
|
|
737
827
|
const CONFIG_KEYS = /* @__PURE__ */ new Set([
|
|
738
828
|
"workspaceRoot",
|
|
739
|
-
"
|
|
829
|
+
"sessionProvider",
|
|
830
|
+
"sessionModel",
|
|
831
|
+
"sessionEffort",
|
|
832
|
+
"sessionPreset"
|
|
833
|
+
]);
|
|
834
|
+
/** 需要校验为字符串的配置键。 */
|
|
835
|
+
const STRING_KEYS = [
|
|
836
|
+
"workspaceRoot",
|
|
837
|
+
"sessionProvider",
|
|
838
|
+
"sessionModel",
|
|
839
|
+
"sessionEffort",
|
|
840
|
+
"sessionPreset"
|
|
841
|
+
];
|
|
842
|
+
/** 旧版本的配置键:接受并丢弃,避免升级后插件加载失败。 */
|
|
843
|
+
const LEGACY_KEYS = /* @__PURE__ */ new Set([
|
|
844
|
+
"profile",
|
|
845
|
+
"ownerOpenId",
|
|
740
846
|
"larkCli",
|
|
847
|
+
"sessionTitle",
|
|
741
848
|
"authCheckOnStartup"
|
|
742
849
|
]);
|
|
743
|
-
/** 旧版本的配置键:接受并丢弃,避免升级后插件加载失败。 */
|
|
744
|
-
const LEGACY_KEYS = /* @__PURE__ */ new Set(["profile", "ownerOpenId"]);
|
|
745
850
|
/** 把缺省或 null 的输入转为空对象。 */
|
|
746
851
|
function normalizeConfigInput(raw) {
|
|
747
852
|
if (raw === void 0 || raw === null) return {};
|
|
748
853
|
if (!isRecord(raw)) throw new Error(`${PLUGIN_LABEL}: config must be an object`);
|
|
749
854
|
return raw;
|
|
750
855
|
}
|
|
751
|
-
/**
|
|
752
|
-
function stringField(input, key, fallback, validate) {
|
|
753
|
-
const raw = input[key];
|
|
754
|
-
if (raw === void 0 || raw === null) return fallback;
|
|
755
|
-
if (typeof raw !== "string") throw new Error(`${PLUGIN_LABEL}: config ${key} must be a string`);
|
|
756
|
-
const value = raw.trim();
|
|
757
|
-
validate(value);
|
|
758
|
-
return value;
|
|
759
|
-
}
|
|
760
|
-
/** 校验配置并与默认值合并,返回冻结的完整配置。 */
|
|
856
|
+
/** 校验配置并与默认值合并,工作区路径统一为 Linux 风格。 */
|
|
761
857
|
function resolveConfig(raw) {
|
|
762
858
|
const input = normalizeConfigInput(raw);
|
|
763
859
|
for (const key of Object.keys(input)) if (!CONFIG_KEYS.has(key) && !LEGACY_KEYS.has(key)) throw new Error(`${PLUGIN_LABEL}: unknown config key "${key}"`);
|
|
764
|
-
const
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
if (value === "") throw new Error(`${PLUGIN_LABEL}: config sessionTitle must not be empty`);
|
|
768
|
-
});
|
|
769
|
-
config.larkCli = stringField(input, "larkCli", DEFAULT_CONFIG.larkCli, () => {});
|
|
770
|
-
const authCheck = input.authCheckOnStartup;
|
|
771
|
-
if (authCheck !== void 0 && authCheck !== null) {
|
|
772
|
-
if (typeof authCheck !== "boolean") throw new Error(`${PLUGIN_LABEL}: config authCheckOnStartup must be a boolean`);
|
|
773
|
-
config.authCheckOnStartup = authCheck;
|
|
860
|
+
for (const key of STRING_KEYS) {
|
|
861
|
+
const value = input[key];
|
|
862
|
+
if (value !== void 0 && value !== null && typeof value !== "string") throw new Error(`${PLUGIN_LABEL}: config ${key} must be a string`);
|
|
774
863
|
}
|
|
775
|
-
|
|
864
|
+
const text = (key) => {
|
|
865
|
+
const value = input[key];
|
|
866
|
+
return typeof value === "string" ? value : DEFAULT_CONFIG[key];
|
|
867
|
+
};
|
|
868
|
+
return Object.freeze({
|
|
869
|
+
workspaceRoot: normalizeWorkspacePath(text("workspaceRoot")),
|
|
870
|
+
sessionProvider: text("sessionProvider"),
|
|
871
|
+
sessionModel: text("sessionModel"),
|
|
872
|
+
sessionEffort: text("sessionEffort"),
|
|
873
|
+
sessionPreset: text("sessionPreset")
|
|
874
|
+
});
|
|
875
|
+
}
|
|
876
|
+
/**
|
|
877
|
+
* 从配置派生新建会话的模型选择。
|
|
878
|
+
* provider 与 model 同时非空才成立;effort 只在模型成立时生效。
|
|
879
|
+
*/
|
|
880
|
+
function modelSelectionOf(config) {
|
|
881
|
+
const provider = config.sessionProvider.trim();
|
|
882
|
+
const model = config.sessionModel.trim();
|
|
883
|
+
if (provider === "" || model === "") return void 0;
|
|
884
|
+
const effort = config.sessionEffort.trim();
|
|
885
|
+
return {
|
|
886
|
+
provider,
|
|
887
|
+
model,
|
|
888
|
+
...effort === "" ? {} : { reasoningEffort: ReasoningEffortId(effort) }
|
|
889
|
+
};
|
|
890
|
+
}
|
|
891
|
+
/** 从配置派生新建会话的预设标识;空白按未配置处理。 */
|
|
892
|
+
function presetOf(config) {
|
|
893
|
+
return config.sessionPreset.trim();
|
|
776
894
|
}
|
|
777
895
|
/** 判断值是否是热重载引用。 */
|
|
778
896
|
function isVolatileRef(value) {
|
|
779
897
|
return isRecord(value) && typeof value.get === "function";
|
|
780
898
|
}
|
|
781
|
-
/**
|
|
899
|
+
/** 展开热重载引用后交给 resolveConfig 校验。 */
|
|
782
900
|
function readConfig(config) {
|
|
783
901
|
if (!isRecord(config)) return resolveConfig(config);
|
|
784
902
|
const values = {};
|
|
785
903
|
for (const [key, value] of Object.entries(config)) values[key] = isVolatileRef(value) ? value.get() : value;
|
|
786
904
|
return resolveConfig(values);
|
|
787
905
|
}
|
|
788
|
-
/**
|
|
789
|
-
* 解析插件状态文件路径。
|
|
790
|
-
* @param home - DSH home;省略时读取 `DSH_HOME`,再回落到 `~/.dsh`。
|
|
791
|
-
* @returns `state.json` 的绝对路径。
|
|
792
|
-
*/
|
|
906
|
+
/** 解析插件状态文件路径。 */
|
|
793
907
|
function statePath(home) {
|
|
794
908
|
const root = home ?? process.env["DSH_HOME"] ?? join(homedir(), ".dsh");
|
|
795
909
|
return join(root, STATE_DIR, STATE_FILE);
|
|
796
910
|
}
|
|
797
911
|
//#endregion
|
|
912
|
+
//#region src/message.ts
|
|
913
|
+
/** 飞书消息块的来源标记。 */
|
|
914
|
+
const LARK_SOURCE = { kind: "lark-bridge" };
|
|
915
|
+
/** 桥接提醒的来源标记。 */
|
|
916
|
+
const REMINDER_SOURCE = {
|
|
917
|
+
kind: "lark-bridge",
|
|
918
|
+
reminder: true
|
|
919
|
+
};
|
|
920
|
+
/** 判断消息是否由本插件注入。 */
|
|
921
|
+
function isLarkMessage(message) {
|
|
922
|
+
return message.role === "user" && message.source.kind === "lark-bridge";
|
|
923
|
+
}
|
|
924
|
+
/** 判断消息是否是一条桥接提醒。 */
|
|
925
|
+
function isReminderMessage(message) {
|
|
926
|
+
if (!isLarkMessage(message)) return false;
|
|
927
|
+
return message.source.kind === "lark-bridge" && message.source.reminder === true;
|
|
928
|
+
}
|
|
929
|
+
//#endregion
|
|
930
|
+
//#region src/reminder.ts
|
|
931
|
+
/** 提醒正文;说明块含义、回复规则与引用读取方式。 */
|
|
932
|
+
const BRIDGE_REMINDER = [
|
|
933
|
+
"<lark-message> 块是用户通过飞书远程发送的消息。",
|
|
934
|
+
"用户只能看到 lark_notify 发送的内容,看不到本会话的回复。",
|
|
935
|
+
"- 回复飞书消息时调用 lark_notify,把要发给用户的内容放进 text。",
|
|
936
|
+
"- 用户连续发来多条 <lark-message> 时只回复一次,用一次 lark_notify 覆盖全部内容。",
|
|
937
|
+
"- 填入 reply_to(某条的 message_id)可以让这条通知引用该消息。",
|
|
938
|
+
"- 回复用户时引用用户的消息,以提高对应关系的准确性。",
|
|
939
|
+
"- <quote> 是用户引用的原消息;<forwarded_messages> 只给记录 id,需要内容时用 lark-cli im +messages-mget --as user --message-ids <id> 读取。",
|
|
940
|
+
"- 用户在移动端远程与你通信,回复要简洁,不涉及细节。",
|
|
941
|
+
"- 会话里的 text 块用户看不到,尽量少输出,说明性文字也放进 lark_notify。",
|
|
942
|
+
"- 其他来源的用户消息按普通方式回复,不调用 lark_notify。"
|
|
943
|
+
].join("\n");
|
|
944
|
+
/** 构造提醒消息。 */
|
|
945
|
+
function createReminderMessage() {
|
|
946
|
+
return createUserMessage({
|
|
947
|
+
content: [{
|
|
948
|
+
type: "text",
|
|
949
|
+
text: reminder(BRIDGE_REMINDER)
|
|
950
|
+
}],
|
|
951
|
+
source: REMINDER_SOURCE
|
|
952
|
+
});
|
|
953
|
+
}
|
|
954
|
+
/** 表层是否已有桥接提醒。 */
|
|
955
|
+
function surfaceHasReminder(session) {
|
|
956
|
+
for (const seq of session.surface.nodes) {
|
|
957
|
+
const event = session.eventAt(seq);
|
|
958
|
+
if (event?.type === "user/message" && isReminderMessage(event.data)) return true;
|
|
959
|
+
}
|
|
960
|
+
return false;
|
|
961
|
+
}
|
|
962
|
+
/**
|
|
963
|
+
* 注册 `agent/pre-step` 补注:桥接会话表层缺少提醒时,把它插到本批第一条块之前。
|
|
964
|
+
* @param deps - 上下文、会话判定与日志。
|
|
965
|
+
* @returns 注销函数。
|
|
966
|
+
*/
|
|
967
|
+
function installReminderGuard(deps) {
|
|
968
|
+
return deps.ctx.on("agent/pre-step", async ({ agent, step }, next) => {
|
|
969
|
+
const decision = await next();
|
|
970
|
+
if (decision.kind === "reject") return decision;
|
|
971
|
+
if (step === 1 && decision.messages.length === 0) return decision;
|
|
972
|
+
const session = agent.session;
|
|
973
|
+
let bridge = false;
|
|
974
|
+
try {
|
|
975
|
+
bridge = await deps.sessions.isBridgeSession(session);
|
|
976
|
+
} catch (error) {
|
|
977
|
+
deps.logger.warn(`lark-bridge: cannot resolve reminder state: ${describeError(error)}`);
|
|
978
|
+
return decision;
|
|
979
|
+
}
|
|
980
|
+
if (!bridge) return decision;
|
|
981
|
+
if (surfaceHasReminder(session)) return decision;
|
|
982
|
+
if (decision.messages.some(isReminderMessage)) return decision;
|
|
983
|
+
const index = decision.messages.findIndex(isLarkMessage);
|
|
984
|
+
const messages = decision.messages.toSpliced(index === -1 ? 0 : index, 0, createReminderMessage());
|
|
985
|
+
return {
|
|
986
|
+
...decision,
|
|
987
|
+
messages
|
|
988
|
+
};
|
|
989
|
+
});
|
|
990
|
+
}
|
|
991
|
+
//#endregion
|
|
798
992
|
//#region src/errors.ts
|
|
799
993
|
/** 插件可诊断错误:携带稳定错误码,供工具与路由返回。 */
|
|
800
994
|
var BridgeError = class extends Error {
|
|
@@ -845,82 +1039,43 @@ function rejectReason(deps, req) {
|
|
|
845
1039
|
return describeError(error);
|
|
846
1040
|
}
|
|
847
1041
|
}
|
|
848
|
-
/**
|
|
849
|
-
|
|
850
|
-
const config = deps.getConfig();
|
|
1042
|
+
/** 投影浏览器可读的笼统状态,排除内部身份与诊断信息。 */
|
|
1043
|
+
function projectStatus(deps) {
|
|
851
1044
|
const snapshot = deps.auth.current;
|
|
852
|
-
const state = await deps.store.load();
|
|
853
|
-
const flow = deps.auth.pendingLogin;
|
|
854
1045
|
return {
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
error: deps.sessions.lastError,
|
|
861
|
-
login: flow === void 0 ? null : {
|
|
862
|
-
verificationUrl: flow.verificationUrl,
|
|
863
|
-
expiresAt: flow.expiresAt
|
|
864
|
-
}
|
|
1046
|
+
cli: snapshot.cli,
|
|
1047
|
+
bot: snapshot.bot,
|
|
1048
|
+
user: snapshot.user,
|
|
1049
|
+
ready: snapshot.ready,
|
|
1050
|
+
checkedAt: snapshot.checkedAt
|
|
865
1051
|
};
|
|
866
1052
|
}
|
|
867
1053
|
/** 执行路由动作并生成响应。 */
|
|
868
1054
|
async function handle(deps, path, method) {
|
|
869
1055
|
if (method === "GET" && path === `/lark-bridge/status`) return {
|
|
870
1056
|
ok: true,
|
|
871
|
-
data:
|
|
1057
|
+
data: projectStatus(deps)
|
|
872
1058
|
};
|
|
873
1059
|
if (method !== "POST") throw new BridgeError("method-not-allowed", "只支持 GET 与 POST");
|
|
874
1060
|
if (path === `/lark-bridge/check`) {
|
|
875
|
-
const snapshot = await deps.auth.check(
|
|
1061
|
+
const snapshot = await deps.auth.check();
|
|
876
1062
|
deps.onAuthChanged?.(snapshot);
|
|
877
|
-
return {
|
|
878
|
-
ok: true,
|
|
879
|
-
data: await projectStatus(deps)
|
|
880
|
-
};
|
|
881
|
-
}
|
|
882
|
-
if (path === `/lark-bridge/auth/start`) {
|
|
883
|
-
const flow = await deps.auth.startLogin();
|
|
884
|
-
deps.auth.whenLoginSettled().then((snapshot) => {
|
|
885
|
-
if (snapshot !== void 0) deps.onAuthChanged?.(snapshot);
|
|
886
|
-
});
|
|
887
1063
|
return {
|
|
888
1064
|
ok: true,
|
|
889
1065
|
data: {
|
|
890
|
-
|
|
891
|
-
|
|
1066
|
+
cli: snapshot.cli,
|
|
1067
|
+
bot: snapshot.bot,
|
|
1068
|
+
user: snapshot.user,
|
|
1069
|
+
ready: snapshot.ready,
|
|
1070
|
+
checkedAt: snapshot.checkedAt
|
|
892
1071
|
}
|
|
893
1072
|
};
|
|
894
1073
|
}
|
|
895
|
-
if (path === `/lark-bridge/auth/cancel`) {
|
|
896
|
-
deps.auth.cancelLogin();
|
|
897
|
-
return {
|
|
898
|
-
ok: true,
|
|
899
|
-
data: await projectStatus(deps)
|
|
900
|
-
};
|
|
901
|
-
}
|
|
902
|
-
if (path === `/lark-bridge/session/reset`) {
|
|
903
|
-
await deps.sessions.reset();
|
|
904
|
-
return {
|
|
905
|
-
ok: true,
|
|
906
|
-
data: await projectStatus(deps)
|
|
907
|
-
};
|
|
908
|
-
}
|
|
909
1074
|
throw new BridgeError("not-found", "未知的桥接接口");
|
|
910
1075
|
}
|
|
911
|
-
/**
|
|
912
|
-
* 注册全部桥接路由。
|
|
913
|
-
* @param deps - 服务、存储与状态来源。
|
|
914
|
-
* @returns 注销全部路由的清理函数。
|
|
915
|
-
*/
|
|
1076
|
+
/** 注册桥接路由并返回清理函数。 */
|
|
916
1077
|
function registerRoutes(deps) {
|
|
917
|
-
const paths = [
|
|
918
|
-
"status",
|
|
919
|
-
"check",
|
|
920
|
-
"auth/start",
|
|
921
|
-
"auth/cancel",
|
|
922
|
-
"session/reset"
|
|
923
|
-
];
|
|
1078
|
+
const paths = ["status", "check"];
|
|
924
1079
|
const disposers = [];
|
|
925
1080
|
for (const suffix of paths) {
|
|
926
1081
|
const path = `${ROUTE_PREFIX}/${suffix}`;
|
|
@@ -963,11 +1118,9 @@ function registerRoutes(deps) {
|
|
|
963
1118
|
//#endregion
|
|
964
1119
|
//#region src/sessions.ts
|
|
965
1120
|
/**
|
|
966
|
-
*
|
|
1121
|
+
* 桥接会话:工作区校验、创建或恢复、新建标题、挂载、置顶与状态持久化。
|
|
967
1122
|
* 导出 SessionManager。
|
|
968
1123
|
*/
|
|
969
|
-
/** 飞书来源的消息标记。 */
|
|
970
|
-
const SOURCE = { kind: "lark-bridge" };
|
|
971
1124
|
/** 把路径解析为绝对路径。 */
|
|
972
1125
|
function absolute(path) {
|
|
973
1126
|
return resolve(path);
|
|
@@ -992,16 +1145,6 @@ function appendTitle(session, title) {
|
|
|
992
1145
|
};
|
|
993
1146
|
session.append.call(session, "session/title", data);
|
|
994
1147
|
}
|
|
995
|
-
/** 构造用于注入的 system-reminder 用户消息。 */
|
|
996
|
-
function reminderMessage(text) {
|
|
997
|
-
return createUserMessage({
|
|
998
|
-
content: [{
|
|
999
|
-
type: "text",
|
|
1000
|
-
text: reminder(text)
|
|
1001
|
-
}],
|
|
1002
|
-
source: SOURCE
|
|
1003
|
-
});
|
|
1004
|
-
}
|
|
1005
1148
|
/** 桥接会话的创建、恢复与注入。 */
|
|
1006
1149
|
var SessionManager = class {
|
|
1007
1150
|
deps;
|
|
@@ -1043,16 +1186,15 @@ var SessionManager = class {
|
|
|
1043
1186
|
}
|
|
1044
1187
|
};
|
|
1045
1188
|
}
|
|
1046
|
-
/**
|
|
1047
|
-
async attach(sessionId,
|
|
1048
|
-
const registry = this.registry();
|
|
1049
|
-
const workspace = await registry.resolveByPath(cwd) ?? await registry.create(cwd);
|
|
1189
|
+
/** 把会话挂到已注册工作区。 */
|
|
1190
|
+
async attach(sessionId, workspace) {
|
|
1050
1191
|
const id = SessionId(sessionId);
|
|
1051
1192
|
if (!workspace.sessionIds.includes(id)) await workspace.attachSession(id);
|
|
1052
1193
|
}
|
|
1053
1194
|
/** 恢复一个可用会话;失败返回 undefined。 */
|
|
1054
1195
|
async resume(sessionId) {
|
|
1055
1196
|
const id = SessionId(sessionId);
|
|
1197
|
+
if (this.registry().archivedSessionIds.includes(id)) return void 0;
|
|
1056
1198
|
const live = this.ctx.agents.get(id);
|
|
1057
1199
|
if (live !== void 0) return live;
|
|
1058
1200
|
try {
|
|
@@ -1067,36 +1209,92 @@ var SessionManager = class {
|
|
|
1067
1209
|
return;
|
|
1068
1210
|
}
|
|
1069
1211
|
}
|
|
1070
|
-
/**
|
|
1071
|
-
async
|
|
1072
|
-
const
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
})
|
|
1081
|
-
|
|
1212
|
+
/** 解析可用的预设;名册缺失、读取失败或候选不可用时返回空串。 */
|
|
1213
|
+
async resolvePreset() {
|
|
1214
|
+
const candidate = presetOf(this.deps.getConfig());
|
|
1215
|
+
if (candidate === "") return "";
|
|
1216
|
+
const presets = this.ctx.get("agentPresets");
|
|
1217
|
+
if (presets === void 0) return "";
|
|
1218
|
+
try {
|
|
1219
|
+
if ((await presets.list()).some((row) => row.id === candidate && row.broken === void 0)) return candidate;
|
|
1220
|
+
this.deps.logger.warn(`lark-bridge: configured preset "${candidate}" is unavailable; using the host default`);
|
|
1221
|
+
return "";
|
|
1222
|
+
} catch (error) {
|
|
1223
|
+
this.deps.logger.warn(`lark-bridge: cannot read agent presets; using the host default: ${describeError(error)}`);
|
|
1224
|
+
return "";
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
/** 校验配置的模型选择;服务缺失或校验失败时返回 undefined。 */
|
|
1228
|
+
async resolveSelection() {
|
|
1229
|
+
const selection = modelSelectionOf(this.deps.getConfig());
|
|
1230
|
+
if (selection === void 0) return void 0;
|
|
1231
|
+
const llm = this.ctx.get("llm");
|
|
1232
|
+
if (llm === void 0) {
|
|
1233
|
+
this.deps.logger.warn("lark-bridge: llm service is unavailable; using the host default model");
|
|
1234
|
+
return;
|
|
1235
|
+
}
|
|
1236
|
+
try {
|
|
1237
|
+
await llm.resolveCallConfig(selection);
|
|
1238
|
+
return selection;
|
|
1239
|
+
} catch (error) {
|
|
1240
|
+
this.deps.logger.warn(`lark-bridge: configured model is unavailable; using the host default: ${describeError(error)}`);
|
|
1241
|
+
return;
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
/** 把模型选择写入新会话;失败只记录警告。 */
|
|
1245
|
+
applySelection(agent, selection) {
|
|
1246
|
+
try {
|
|
1247
|
+
agent.model.select(selection);
|
|
1248
|
+
} catch (error) {
|
|
1249
|
+
this.deps.logger.warn(`lark-bridge: cannot apply the model selection: ${describeError(error)}`);
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
/** 新建会话,应用预设与模型,设置标题、挂到工作区并置顶。 */
|
|
1253
|
+
async create(cwd, title, workspace) {
|
|
1254
|
+
const selection = await this.resolveSelection();
|
|
1255
|
+
const preset = await this.resolvePreset();
|
|
1256
|
+
const controller = this.ctx.get("sessionController");
|
|
1257
|
+
let sessionId = randomUUID();
|
|
1258
|
+
let agent;
|
|
1259
|
+
if (controller?.create !== void 0) {
|
|
1260
|
+
sessionId = (await controller.create({
|
|
1261
|
+
sessionId,
|
|
1262
|
+
workspaceId: String(workspace.id),
|
|
1263
|
+
cwd,
|
|
1264
|
+
...preset === "" ? {} : { agentPreset: preset }
|
|
1265
|
+
})).sessionId;
|
|
1266
|
+
const resolved = await controller.resolveAgent(SessionId(sessionId));
|
|
1267
|
+
if ("error" in resolved) {
|
|
1268
|
+
const live = this.ctx.agents.get(SessionId(sessionId));
|
|
1269
|
+
if (live === void 0) throw resolved.error;
|
|
1270
|
+
this.deps.logger.warn(`lark-bridge: cannot resolve the new session; using the live agent: ${describeError(resolved.error)}`);
|
|
1271
|
+
agent = live;
|
|
1272
|
+
} else agent = resolved.agent;
|
|
1273
|
+
} else {
|
|
1274
|
+
if (preset !== "") this.deps.logger.warn("lark-bridge: sessionController is unavailable; the preset was ignored");
|
|
1275
|
+
agent = (await this.ctx.agents.create({
|
|
1276
|
+
sessionId: SessionId(sessionId),
|
|
1277
|
+
agentOptions: this.agentOptions(),
|
|
1278
|
+
meta: { cwd }
|
|
1279
|
+
})).agent;
|
|
1280
|
+
}
|
|
1281
|
+
if (selection !== void 0) this.applySelection(agent, selection);
|
|
1282
|
+
appendTitle(agent.session, title);
|
|
1283
|
+
await this.attach(sessionId, workspace);
|
|
1082
1284
|
await this.registry().pinSession(SessionId(sessionId));
|
|
1083
1285
|
await this.deps.store.patch({
|
|
1084
1286
|
sessionId,
|
|
1085
|
-
workspaceRoot: cwd,
|
|
1287
|
+
workspaceRoot: normalizeWorkspacePath(cwd),
|
|
1086
1288
|
title
|
|
1087
1289
|
});
|
|
1088
1290
|
this.deps.logger.info(`lark-bridge: created session ${sessionId} in ${cwd}`);
|
|
1089
1291
|
return {
|
|
1090
1292
|
sessionId,
|
|
1091
|
-
agent
|
|
1293
|
+
agent
|
|
1092
1294
|
};
|
|
1093
1295
|
}
|
|
1094
|
-
/**
|
|
1095
|
-
async
|
|
1096
|
-
if (createdTitle !== title) {
|
|
1097
|
-
appendTitle(agent.session, title);
|
|
1098
|
-
await this.deps.store.patch({ title });
|
|
1099
|
-
}
|
|
1296
|
+
/** 置顶会话;失败只记日志。 */
|
|
1297
|
+
async pin(sessionId) {
|
|
1100
1298
|
try {
|
|
1101
1299
|
await this.registry().pinSession(SessionId(sessionId));
|
|
1102
1300
|
} catch (error) {
|
|
@@ -1109,38 +1307,47 @@ var SessionManager = class {
|
|
|
1109
1307
|
* @returns 会话标识、会话实例与是否新建。
|
|
1110
1308
|
*/
|
|
1111
1309
|
async ensure(workspaceRoot) {
|
|
1112
|
-
const cwd =
|
|
1113
|
-
|
|
1310
|
+
const cwd = toHostWorkspacePath(workspaceRoot);
|
|
1311
|
+
await assertWorkspace(cwd);
|
|
1312
|
+
const workspace = await this.registry().resolveByPath(cwd);
|
|
1313
|
+
if (workspace === void 0) throw new BridgeError("workspace-unregistered", `工作区未注册:${normalizeWorkspacePath(cwd)}`);
|
|
1114
1314
|
const state = await this.deps.store.load();
|
|
1115
|
-
if (state.sessionId !== null && state.workspaceRoot !== null &&
|
|
1315
|
+
if (state.sessionId !== null && state.workspaceRoot !== null && sameWorkspacePath(state.workspaceRoot, cwd)) {
|
|
1116
1316
|
const agent = await this.resume(state.sessionId);
|
|
1117
1317
|
if (agent !== void 0) {
|
|
1118
|
-
await this.
|
|
1318
|
+
await this.pin(state.sessionId);
|
|
1119
1319
|
return {
|
|
1120
1320
|
sessionId: state.sessionId,
|
|
1121
1321
|
agent,
|
|
1122
|
-
created: false
|
|
1322
|
+
created: false,
|
|
1323
|
+
cwd
|
|
1123
1324
|
};
|
|
1124
1325
|
}
|
|
1125
1326
|
}
|
|
1126
|
-
const created = await this.create(cwd, config.sessionTitle);
|
|
1127
1327
|
return {
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1328
|
+
...await this.create(cwd, SESSION_TITLE, workspace),
|
|
1329
|
+
created: true,
|
|
1330
|
+
cwd
|
|
1131
1331
|
};
|
|
1132
1332
|
}
|
|
1133
1333
|
/**
|
|
1134
|
-
*
|
|
1135
|
-
* @param
|
|
1334
|
+
* 把一段飞书消息块注入桥接会话。
|
|
1335
|
+
* @param block - 已格式化的 `<lark-message>` 块。
|
|
1136
1336
|
* @returns 注入目标与会话是否新建。
|
|
1137
1337
|
*/
|
|
1138
|
-
async inject(
|
|
1338
|
+
async inject(block) {
|
|
1139
1339
|
try {
|
|
1140
1340
|
const config = this.deps.getConfig();
|
|
1141
1341
|
if (config.workspaceRoot === "") throw new BridgeError("workspace-missing", "尚未配置桥接工作区");
|
|
1142
|
-
const { sessionId, agent, created } = await this.ensure(config.workspaceRoot);
|
|
1143
|
-
|
|
1342
|
+
const { sessionId, agent, created, cwd } = await this.ensure(config.workspaceRoot);
|
|
1343
|
+
if (await this.registry().resolveByPath(cwd) === void 0) throw new BridgeError("workspace-unregistered", `工作区未注册:${normalizeWorkspacePath(cwd)}`);
|
|
1344
|
+
agent.followup(createUserMessage({
|
|
1345
|
+
content: [{
|
|
1346
|
+
type: "text",
|
|
1347
|
+
text: block
|
|
1348
|
+
}],
|
|
1349
|
+
source: LARK_SOURCE
|
|
1350
|
+
}));
|
|
1144
1351
|
this.failure = void 0;
|
|
1145
1352
|
return {
|
|
1146
1353
|
sessionId,
|
|
@@ -1150,9 +1357,14 @@ var SessionManager = class {
|
|
|
1150
1357
|
this.fail(error);
|
|
1151
1358
|
}
|
|
1152
1359
|
}
|
|
1153
|
-
/**
|
|
1154
|
-
|
|
1155
|
-
|
|
1360
|
+
/**
|
|
1361
|
+
* 判断会话是否是当前桥接会话。
|
|
1362
|
+
* @param session - 宿主的会话实例。
|
|
1363
|
+
* @returns 状态文件记录的就是该会话时为 true。
|
|
1364
|
+
*/
|
|
1365
|
+
async isBridgeSession(session) {
|
|
1366
|
+
const state = await this.deps.store.load();
|
|
1367
|
+
return state.sessionId !== null && state.sessionId === session.id;
|
|
1156
1368
|
}
|
|
1157
1369
|
};
|
|
1158
1370
|
//#endregion
|
|
@@ -1207,6 +1419,7 @@ var StateStore = class {
|
|
|
1207
1419
|
const parsed = JSON.parse(text);
|
|
1208
1420
|
this.cache = isState(parsed) ? {
|
|
1209
1421
|
...parsed,
|
|
1422
|
+
workspaceRoot: parsed.workspaceRoot === null ? null : normalizeWorkspacePath(parsed.workspaceRoot),
|
|
1210
1423
|
seen: trimSeen(parsed.seen, this.limit)
|
|
1211
1424
|
} : emptyState();
|
|
1212
1425
|
} catch {
|
|
@@ -1234,6 +1447,7 @@ var StateStore = class {
|
|
|
1234
1447
|
}, this.limit),
|
|
1235
1448
|
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1236
1449
|
};
|
|
1450
|
+
if (next.workspaceRoot !== null) next.workspaceRoot = normalizeWorkspacePath(next.workspaceRoot);
|
|
1237
1451
|
await this.write(next);
|
|
1238
1452
|
this.cache = next;
|
|
1239
1453
|
return next;
|
|
@@ -1282,14 +1496,6 @@ var StateStore = class {
|
|
|
1282
1496
|
return next;
|
|
1283
1497
|
});
|
|
1284
1498
|
}
|
|
1285
|
-
/** 清除会话标识,保留下一次消息重建。 */
|
|
1286
|
-
resetSession() {
|
|
1287
|
-
return this.patch({
|
|
1288
|
-
sessionId: null,
|
|
1289
|
-
workspaceRoot: null,
|
|
1290
|
-
title: null
|
|
1291
|
-
});
|
|
1292
|
-
}
|
|
1293
1499
|
/** 把写操作串到同一条队列,避免并发覆盖。 */
|
|
1294
1500
|
enqueue(action) {
|
|
1295
1501
|
const next = this.queue.then(action, action);
|
|
@@ -1307,9 +1513,22 @@ var StateStore = class {
|
|
|
1307
1513
|
//#endregion
|
|
1308
1514
|
//#region src/tools.ts
|
|
1309
1515
|
/**
|
|
1310
|
-
* `lark_notify` 工具:以 bot
|
|
1516
|
+
* `lark_notify` 工具:以 bot 身份向已绑定用户发送飞书消息,可选精确回复某条用户消息。
|
|
1311
1517
|
* 导出 NOTIFY_TOOL 与 sendNotification。
|
|
1312
1518
|
*/
|
|
1519
|
+
/** 读取可选的 `reply_to`;类型不对时返回错误。 */
|
|
1520
|
+
function readReplyTo(args) {
|
|
1521
|
+
const value = args["reply_to"];
|
|
1522
|
+
if (value === void 0) return {};
|
|
1523
|
+
if (typeof value !== "string" || value.trim() === "") return { error: {
|
|
1524
|
+
ok: false,
|
|
1525
|
+
error: {
|
|
1526
|
+
code: "invalid-reply-to",
|
|
1527
|
+
message: "reply_to 必须是非空字符串"
|
|
1528
|
+
}
|
|
1529
|
+
} };
|
|
1530
|
+
return { replyTo: value.trim() };
|
|
1531
|
+
}
|
|
1313
1532
|
/**
|
|
1314
1533
|
* 校验参数并发送通知。
|
|
1315
1534
|
* @param deps - 配置、CLI 与用户标识来源。
|
|
@@ -1324,7 +1543,8 @@ async function sendNotification(deps, args) {
|
|
|
1324
1543
|
message: "参数必须是对象"
|
|
1325
1544
|
}
|
|
1326
1545
|
};
|
|
1327
|
-
const
|
|
1546
|
+
const record = args;
|
|
1547
|
+
const text = record["text"];
|
|
1328
1548
|
if (typeof text !== "string" || text.trim() === "") return {
|
|
1329
1549
|
ok: false,
|
|
1330
1550
|
error: {
|
|
@@ -1332,57 +1552,70 @@ async function sendNotification(deps, args) {
|
|
|
1332
1552
|
message: "text 必须是非空字符串"
|
|
1333
1553
|
}
|
|
1334
1554
|
};
|
|
1555
|
+
const reply = readReplyTo(record);
|
|
1556
|
+
if (reply.error !== void 0) return reply.error;
|
|
1335
1557
|
const owner = deps.getOwner();
|
|
1336
1558
|
if (owner === void 0 || owner === "") return {
|
|
1337
1559
|
ok: false,
|
|
1338
1560
|
error: {
|
|
1339
1561
|
code: "owner-missing",
|
|
1340
|
-
message: "
|
|
1562
|
+
message: "尚未确定已绑定用户,请在终端登录后重新检测"
|
|
1341
1563
|
}
|
|
1342
1564
|
};
|
|
1343
1565
|
const parts = splitText(text, MAX_MESSAGE_CHARS);
|
|
1344
1566
|
const baseKey = `lark-notify-${randomUUID()}`;
|
|
1345
1567
|
let first;
|
|
1346
|
-
for (const [index, part] of parts.entries())
|
|
1347
|
-
const
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1568
|
+
for (const [index, part] of parts.entries()) {
|
|
1569
|
+
const replyTo = index === 0 ? reply.replyTo : void 0;
|
|
1570
|
+
const target = replyTo === void 0 ? ["--user-id", owner] : ["--message-id", replyTo];
|
|
1571
|
+
try {
|
|
1572
|
+
const value = await deps.getCli().json([
|
|
1573
|
+
"im",
|
|
1574
|
+
replyTo === void 0 ? "+messages-send" : "+messages-reply",
|
|
1575
|
+
"--as",
|
|
1576
|
+
"bot",
|
|
1577
|
+
...target,
|
|
1578
|
+
"--text",
|
|
1579
|
+
"-",
|
|
1580
|
+
"--idempotency-key",
|
|
1581
|
+
`${baseKey}-${index}`.slice(0, 50)
|
|
1582
|
+
], { input: part });
|
|
1583
|
+
const record = typeof value === "object" && value !== null ? value : {};
|
|
1584
|
+
first ??= typeof record["message_id"] === "string" ? record["message_id"] : void 0;
|
|
1585
|
+
} catch (error) {
|
|
1586
|
+
return {
|
|
1587
|
+
ok: false,
|
|
1588
|
+
error: {
|
|
1589
|
+
code: replyTo === void 0 ? "send-failed" : "reply-failed",
|
|
1590
|
+
message: describeError(error)
|
|
1591
|
+
}
|
|
1592
|
+
};
|
|
1593
|
+
}
|
|
1369
1594
|
}
|
|
1370
1595
|
return {
|
|
1371
1596
|
ok: true,
|
|
1372
1597
|
parts: parts.length,
|
|
1373
|
-
...first === void 0 ? {} : { messageId: first }
|
|
1598
|
+
...first === void 0 ? {} : { messageId: first },
|
|
1599
|
+
...reply.replyTo === void 0 ? {} : { replyTo: reply.replyTo }
|
|
1374
1600
|
};
|
|
1375
1601
|
}
|
|
1376
1602
|
/** 构造工具定义。 */
|
|
1377
1603
|
function buildNotifyTool(deps) {
|
|
1378
1604
|
return {
|
|
1379
1605
|
name: NOTIFY_TOOL_NAME,
|
|
1380
|
-
description: "
|
|
1381
|
-
parameters: {
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1606
|
+
description: "以飞书机器人身份给已绑定的用户发送消息。只发往用户与机器人的私聊,不接受其他接收目标。可选 reply_to 精确回复某条用户消息。",
|
|
1607
|
+
parameters: {
|
|
1608
|
+
text: {
|
|
1609
|
+
type: "string",
|
|
1610
|
+
description: "要发送给用户的文本;过长时插件自动按顺序拆分",
|
|
1611
|
+
required: true
|
|
1612
|
+
},
|
|
1613
|
+
reply_to: {
|
|
1614
|
+
type: "string",
|
|
1615
|
+
description: "要回复的用户消息 message_id;省略时直接发送",
|
|
1616
|
+
required: false
|
|
1617
|
+
}
|
|
1618
|
+
},
|
|
1386
1619
|
output: {
|
|
1387
1620
|
schema: {
|
|
1388
1621
|
type: "object",
|
|
@@ -1390,6 +1623,7 @@ function buildNotifyTool(deps) {
|
|
|
1390
1623
|
ok: { type: "boolean" },
|
|
1391
1624
|
parts: { type: "integer" },
|
|
1392
1625
|
messageId: { type: "string" },
|
|
1626
|
+
replyTo: { type: "string" },
|
|
1393
1627
|
error: {
|
|
1394
1628
|
type: "object",
|
|
1395
1629
|
properties: {
|
|
@@ -1405,7 +1639,7 @@ function buildNotifyTool(deps) {
|
|
|
1405
1639
|
const result = value;
|
|
1406
1640
|
if (result.ok) return [{
|
|
1407
1641
|
type: "text",
|
|
1408
|
-
text:
|
|
1642
|
+
text: `${result.replyTo === void 0 ? "已发送给用户" : "已回复给用户"}(${result.parts ?? 1} 条)`
|
|
1409
1643
|
}];
|
|
1410
1644
|
const error = result.error ?? {
|
|
1411
1645
|
code: "unknown",
|
|
@@ -1440,28 +1674,83 @@ function buildNotifyTool(deps) {
|
|
|
1440
1674
|
};
|
|
1441
1675
|
}
|
|
1442
1676
|
//#endregion
|
|
1677
|
+
//#region src/workspace.ts
|
|
1678
|
+
/** 保存最近一次有效解析,并用序号阻止旧结果覆盖新选择。 */
|
|
1679
|
+
var WorkspaceSelection = class {
|
|
1680
|
+
deps;
|
|
1681
|
+
revision = 0;
|
|
1682
|
+
selectedRoot = "";
|
|
1683
|
+
selectedWorkspace;
|
|
1684
|
+
constructor(deps) {
|
|
1685
|
+
this.deps = deps;
|
|
1686
|
+
}
|
|
1687
|
+
/** 当前配置是否与已解析的注册工作区一致。 */
|
|
1688
|
+
get valid() {
|
|
1689
|
+
return this.selectedWorkspace !== void 0 && sameWorkspacePath(this.selectedRoot, this.deps.getWorkspaceRoot());
|
|
1690
|
+
}
|
|
1691
|
+
/** 当前注册工作区 id。 */
|
|
1692
|
+
get currentId() {
|
|
1693
|
+
return this.valid && this.selectedWorkspace !== void 0 ? String(this.selectedWorkspace.id) : void 0;
|
|
1694
|
+
}
|
|
1695
|
+
/** 使当前缓存和未完成的解析失效。 */
|
|
1696
|
+
reset() {
|
|
1697
|
+
this.revision += 1;
|
|
1698
|
+
this.selectedRoot = "";
|
|
1699
|
+
this.selectedWorkspace = void 0;
|
|
1700
|
+
}
|
|
1701
|
+
/** 目标注册项删除时同步失效。 */
|
|
1702
|
+
invalidate(change) {
|
|
1703
|
+
if (typeof change !== "object" || change === null) return false;
|
|
1704
|
+
const record = change;
|
|
1705
|
+
if (record["domain"] !== "workspace" || record["table"] !== "workspaces" || record["operation"] !== "deleted" || record["key"] !== this.currentId) return false;
|
|
1706
|
+
this.reset();
|
|
1707
|
+
return true;
|
|
1708
|
+
}
|
|
1709
|
+
/** 解析当前配置;只有最新结果可以更新缓存。 */
|
|
1710
|
+
async resolve() {
|
|
1711
|
+
const revision = ++this.revision;
|
|
1712
|
+
const root = normalizeWorkspacePath(this.deps.getWorkspaceRoot());
|
|
1713
|
+
let workspace;
|
|
1714
|
+
if (root !== "") {
|
|
1715
|
+
const registry = this.deps.getRegistry();
|
|
1716
|
+
try {
|
|
1717
|
+
workspace = await registry?.resolveByPath(toHostWorkspacePath(root));
|
|
1718
|
+
} catch {
|
|
1719
|
+
workspace = void 0;
|
|
1720
|
+
}
|
|
1721
|
+
}
|
|
1722
|
+
const current = revision === this.revision && sameWorkspacePath(root, this.deps.getWorkspaceRoot());
|
|
1723
|
+
if (current) {
|
|
1724
|
+
this.selectedRoot = root;
|
|
1725
|
+
this.selectedWorkspace = workspace;
|
|
1726
|
+
}
|
|
1727
|
+
return {
|
|
1728
|
+
root,
|
|
1729
|
+
workspace,
|
|
1730
|
+
current
|
|
1731
|
+
};
|
|
1732
|
+
}
|
|
1733
|
+
};
|
|
1734
|
+
//#endregion
|
|
1443
1735
|
//#region src/index.ts
|
|
1444
|
-
/**
|
|
1445
|
-
* 插件入口:导出宿主约定的 name、inject、apply 与 Config。
|
|
1446
|
-
* 装配鉴权、事件桥、会话、通知工具与浏览器路由。
|
|
1447
|
-
*/
|
|
1448
1736
|
/** 插件名,与 cordis.patch.yml 的 id 一致。 */
|
|
1449
1737
|
const name = PLUGIN_LABEL;
|
|
1450
1738
|
/** 需要宿主注入的服务。 */
|
|
1451
1739
|
const inject = [
|
|
1452
1740
|
"tools",
|
|
1453
1741
|
"agents",
|
|
1454
|
-
"webServer"
|
|
1742
|
+
"webServer",
|
|
1743
|
+
"workspaceRegistry"
|
|
1455
1744
|
];
|
|
1456
1745
|
/**
|
|
1457
1746
|
* 插件启用时调用:读取配置、装配服务、注册工具与路由、启动鉴权检查。
|
|
1458
|
-
*
|
|
1747
|
+
* 配置字段均为热重载引用,保存后更新配置并重新检测。
|
|
1459
1748
|
*/
|
|
1460
1749
|
function apply(ctx, config) {
|
|
1461
1750
|
let current = readConfig(config);
|
|
1462
1751
|
ctx.logger.info(`[${PLUGIN_LABEL}] apply`);
|
|
1463
1752
|
const store = new StateStore(statePath());
|
|
1464
|
-
|
|
1753
|
+
const cli = new LarkCli();
|
|
1465
1754
|
let lastStage = "";
|
|
1466
1755
|
const sessions = new SessionManager({
|
|
1467
1756
|
ctx,
|
|
@@ -1469,26 +1758,43 @@ function apply(ctx, config) {
|
|
|
1469
1758
|
getConfig: () => current,
|
|
1470
1759
|
logger: ctx.logger
|
|
1471
1760
|
});
|
|
1761
|
+
const uninstallReminder = installReminderGuard({
|
|
1762
|
+
ctx,
|
|
1763
|
+
sessions,
|
|
1764
|
+
logger: ctx.logger
|
|
1765
|
+
});
|
|
1766
|
+
ctx.effect(() => () => uninstallReminder(), `${PLUGIN_LABEL}: reminder guard`);
|
|
1767
|
+
const selection = new WorkspaceSelection({
|
|
1768
|
+
getWorkspaceRoot: () => current.workspaceRoot,
|
|
1769
|
+
getRegistry: () => ctx.get("workspaceRegistry")
|
|
1770
|
+
});
|
|
1472
1771
|
let bridge;
|
|
1772
|
+
let reconcile;
|
|
1473
1773
|
const auth = new AuthManager({
|
|
1474
1774
|
getCli: () => cli,
|
|
1475
1775
|
logger: ctx.logger,
|
|
1476
1776
|
onChange: (snapshot) => {
|
|
1477
|
-
const
|
|
1478
|
-
if (
|
|
1479
|
-
lastStage =
|
|
1480
|
-
ctx.logger.info(`[${PLUGIN_LABEL}] auth
|
|
1777
|
+
const state = snapshot.ready ? "ready" : `${snapshot.cli}/${snapshot.bot}/${snapshot.user}`;
|
|
1778
|
+
if (state !== lastStage) {
|
|
1779
|
+
lastStage = state;
|
|
1780
|
+
ctx.logger.info(`[${PLUGIN_LABEL}] auth state: ${state}`);
|
|
1481
1781
|
}
|
|
1482
|
-
bridge.
|
|
1782
|
+
if (!snapshot.ready) bridge.stop();
|
|
1783
|
+
reconcile();
|
|
1483
1784
|
}
|
|
1484
1785
|
});
|
|
1485
1786
|
bridge = new EventBridge({
|
|
1486
1787
|
getCli: () => cli,
|
|
1487
1788
|
getAuth: () => auth.current,
|
|
1789
|
+
getWorkspaceReady: () => selection.valid,
|
|
1488
1790
|
store,
|
|
1489
1791
|
sessions,
|
|
1490
1792
|
logger: ctx.logger
|
|
1491
1793
|
});
|
|
1794
|
+
reconcile = async () => {
|
|
1795
|
+
if (!auth.current.ready) bridge.stop();
|
|
1796
|
+
if ((await selection.resolve()).current) bridge.sync(auth.current);
|
|
1797
|
+
};
|
|
1492
1798
|
const notifyTool = buildNotifyTool({
|
|
1493
1799
|
getCli: () => cli,
|
|
1494
1800
|
getOwner: () => auth.current.ownerOpenId
|
|
@@ -1504,11 +1810,7 @@ function apply(ctx, config) {
|
|
|
1504
1810
|
webServer,
|
|
1505
1811
|
...connection === void 0 ? {} : { connection },
|
|
1506
1812
|
auth,
|
|
1507
|
-
|
|
1508
|
-
store,
|
|
1509
|
-
getConfig: () => current,
|
|
1510
|
-
logger: ctx.logger,
|
|
1511
|
-
onAuthChanged: (snapshot) => bridge.sync(snapshot)
|
|
1813
|
+
logger: ctx.logger
|
|
1512
1814
|
});
|
|
1513
1815
|
}
|
|
1514
1816
|
ctx.effect(() => () => disposeRoutes?.(), `${PLUGIN_LABEL}: routes`);
|
|
@@ -1519,13 +1821,16 @@ function apply(ctx, config) {
|
|
|
1519
1821
|
ctx.logger.warn(`[${PLUGIN_LABEL}] auth check failed: ${describeError(error)}`);
|
|
1520
1822
|
});
|
|
1521
1823
|
};
|
|
1522
|
-
|
|
1824
|
+
runCheck();
|
|
1825
|
+
ctx.on("domain/changed", (change) => {
|
|
1826
|
+
if (!selection.invalidate(change)) return;
|
|
1827
|
+
reconcile();
|
|
1828
|
+
});
|
|
1523
1829
|
ctx.on("loader/volatile-update", () => {
|
|
1524
1830
|
try {
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
if (cliChanged) cli = new LarkCli(next.larkCli);
|
|
1831
|
+
current = readConfig(config);
|
|
1832
|
+
selection.reset();
|
|
1833
|
+
reconcile();
|
|
1529
1834
|
ctx.logger.info(`[${PLUGIN_LABEL}] config updated`);
|
|
1530
1835
|
runCheck();
|
|
1531
1836
|
} catch (error) {
|
|
@@ -1533,7 +1838,6 @@ function apply(ctx, config) {
|
|
|
1533
1838
|
}
|
|
1534
1839
|
});
|
|
1535
1840
|
ctx.effect(() => () => bridge.stop(), `${PLUGIN_LABEL}: event bridge`);
|
|
1536
|
-
ctx.effect(() => () => auth.cancelLogin(), `${PLUGIN_LABEL}: login`);
|
|
1537
1841
|
}
|
|
1538
1842
|
//#endregion
|
|
1539
1843
|
export { Config, apply, inject, name };
|