dsh-plugin-lark-bridge 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +45 -26
  2. package/cordis.patch.yml +2 -12
  3. package/dist/auth.d.ts +12 -47
  4. package/dist/auth.d.ts.map +1 -1
  5. package/dist/bridge.d.ts +6 -6
  6. package/dist/bridge.d.ts.map +1 -1
  7. package/dist/cli.d.ts +17 -21
  8. package/dist/cli.d.ts.map +1 -1
  9. package/dist/client/api.d.ts +9 -36
  10. package/dist/client/api.d.ts.map +1 -1
  11. package/dist/client/auth-overlay.d.ts +54 -6
  12. package/dist/client/auth-overlay.d.ts.map +1 -1
  13. package/dist/client/auth-panel.d.ts +17 -5
  14. package/dist/client/auth-panel.d.ts.map +1 -1
  15. package/dist/client/config-form.d.ts +2 -15
  16. package/dist/client/config-form.d.ts.map +1 -1
  17. package/dist/client/config-page.d.ts +32 -6
  18. package/dist/client/config-page.d.ts.map +1 -1
  19. package/dist/client/index.d.ts +2 -8
  20. package/dist/client/index.d.ts.map +1 -1
  21. package/dist/client/locales.d.ts +23 -55
  22. package/dist/client/locales.d.ts.map +1 -1
  23. package/dist/client/status-controller.d.ts +43 -0
  24. package/dist/client/status-controller.d.ts.map +1 -0
  25. package/dist/client/terminal-command.d.ts +11 -0
  26. package/dist/client/terminal-command.d.ts.map +1 -0
  27. package/dist/client.js +776 -835
  28. package/dist/config.d.ts +6 -28
  29. package/dist/config.d.ts.map +1 -1
  30. package/dist/constants.d.ts +2 -6
  31. package/dist/constants.d.ts.map +1 -1
  32. package/dist/index.d.ts +5 -1
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.mjs +434 -604
  35. package/dist/message.d.ts +27 -0
  36. package/dist/message.d.ts.map +1 -0
  37. package/dist/reminder.d.ts +33 -0
  38. package/dist/reminder.d.ts.map +1 -0
  39. package/dist/routes.d.ts +5 -15
  40. package/dist/routes.d.ts.map +1 -1
  41. package/dist/sessions.d.ts +12 -13
  42. package/dist/sessions.d.ts.map +1 -1
  43. package/dist/state.d.ts +0 -2
  44. package/dist/state.d.ts.map +1 -1
  45. package/dist/tools.d.ts +0 -2
  46. package/dist/tools.d.ts.map +1 -1
  47. package/dist/types.d.ts +2 -0
  48. package/dist/types.d.ts.map +1 -1
  49. package/dist/utils.d.ts +3 -1
  50. package/dist/utils.d.ts.map +1 -1
  51. package/dist/workspace-path.d.ts +8 -0
  52. package/dist/workspace-path.d.ts.map +1 -0
  53. package/dist/workspace.d.ts +32 -0
  54. package/dist/workspace.d.ts.map +1 -0
  55. package/locale/en.json +1 -1
  56. package/locale/zh.json +1 -1
  57. package/package.json +6 -5
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";
7
5
  import Schema from "@deepseek-ai/schemastery";
6
+ import { createUserMessage } from "@deepseek-ai/dsh-llm";
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,14 +13,24 @@ 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 date.toLocaleString("zh-CN", {
23
- hour12: false,
24
- timeZone
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("&", "&amp;").replaceAll("\"", "&quot;").replaceAll("<", "&lt;");
26
34
  }
27
35
  /** 解析毫秒时间戳字符串;非法值返回当前时间。 */
28
36
  function parseTimestamp(value) {
@@ -57,14 +65,6 @@ function splitText(text, limit) {
57
65
  parts.push(rest);
58
66
  return parts;
59
67
  }
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
68
  /** 压缩并截断一段用于日志的错误文本。 */
69
69
  function describeError(error, max = 500) {
70
70
  const text = error instanceof Error ? error.message : String(error);
@@ -73,8 +73,8 @@ function describeError(error, max = 500) {
73
73
  //#endregion
74
74
  //#region src/cli.ts
75
75
  /**
76
- * `lark-cli` 适配层:定位可执行文件、启动子进程、解析 JSON envelope。
77
- * 导出 LarkCli、CliError 与 resolveLarkCli。
76
+ * `lark-cli` 适配层:调用本机命令、管理子进程、解析 JSON envelope。
77
+ * 导出 LarkCli、CliError 与进程构造辅助函数。
78
78
  */
79
79
  /** CLI 调用失败。 */
80
80
  var CliError = class extends Error {
@@ -89,88 +89,45 @@ var CliError = class extends Error {
89
89
  this.exitCode = exitCode;
90
90
  }
91
91
  };
92
- const WINDOWS = process.platform === "win32";
93
- const TIMEOUT_DEFAULT = 12e4;
94
- const VIEWPORT = 10485760;
95
- /** 判断文件是否存在。 */
96
- function hasFile(path) {
97
- return existsSync(path);
98
- }
99
- /** 从包目录解析可执行文件或入口脚本。 */
100
- function fromPackageDir(dir, nodePath) {
101
- const bin = join(dir, "bin", WINDOWS ? "lark-cli.exe" : "lark-cli");
102
- if (hasFile(bin)) return {
103
- file: bin,
104
- args: []
92
+ /** Windows 命令字符串只允许不需要转义的安全 token。 */
93
+ const WINDOWS_SAFE_TOKEN = /^[A-Za-z0-9._:+-]+$/;
94
+ /** 构造进程参数;Windows 用安全 token 组成单一命令字符串。 */
95
+ function createSpawnSpec(command, args, platform = process.platform) {
96
+ const tokens = [
97
+ command.file,
98
+ ...command.args,
99
+ ...args
100
+ ];
101
+ if (platform !== "win32") return {
102
+ file: command.file,
103
+ args: [...command.args, ...args],
104
+ shell: false
105
105
  };
106
- const entry = join(dir, "scripts", "run.js");
107
- if (hasFile(entry)) return {
108
- file: nodePath,
109
- args: [entry]
106
+ for (const token of tokens) if (token === "" || !WINDOWS_SAFE_TOKEN.test(token)) throw new CliError("unsafe-arg", "lark-cli argument contains unsupported Windows characters");
107
+ return {
108
+ file: tokens.join(" "),
109
+ args: [],
110
+ shell: true
110
111
  };
111
112
  }
112
- /** 尝试解析依赖包;未安装时返回 undefined。 */
113
- function resolvePackage(nodePath) {
113
+ /** 启动 CLI 子进程,并把同步启动异常归一化为 CliError。 */
114
+ function createCliProcess(command, args, options, platform = process.platform, spawnFn = spawn) {
115
+ const spec = createSpawnSpec(command, args, platform);
114
116
  try {
115
- const manifest = createRequire(import.meta.url).resolve("@larksuite/cli/package.json");
116
- return fromPackageDir(dirname(manifest), nodePath);
117
- } catch {
118
- return;
119
- }
120
- }
121
- /**
122
- * 解析 lark-cli 命令。
123
- * 顺序:显式路径 → `LARK_CLI` → 已安装的 npm 包 → PATH 中的包目录 → `lark-cli`。
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;
117
+ return spec.shell ? spawnFn(spec.file, {
118
+ ...options,
119
+ shell: true
120
+ }) : spawnFn(spec.file, [...spec.args], {
121
+ ...options,
122
+ shell: false
123
+ });
124
+ } catch (error) {
125
+ throw new CliError("spawn-failed", describeError(error));
168
126
  }
169
- return {
170
- file: "lark-cli",
171
- args: []
172
- };
173
127
  }
128
+ const WINDOWS = process.platform === "win32";
129
+ const TIMEOUT_DEFAULT = 12e4;
130
+ const VIEWPORT = 10485760;
174
131
  /** 杀掉子进程及其后代。 */
175
132
  function killChildTree(child) {
176
133
  if (child.pid === void 0) {
@@ -194,9 +151,9 @@ function killChildTree(child) {
194
151
  }
195
152
  child.kill("SIGTERM");
196
153
  }
197
- /** 默认运行器:直接启动可执行文件,不经 shell。 */
154
+ /** 默认运行器:按平台安全调用本机命令。 */
198
155
  const defaultRunner = (command, args, options) => new Promise((resolvePromise, reject) => {
199
- const child = spawn(command.file, [...command.args, ...args], {
156
+ const child = createCliProcess(command, args, {
200
157
  windowsHide: true,
201
158
  stdio: [
202
159
  "pipe",
@@ -273,30 +230,19 @@ function parseJsonOutput(text) {
273
230
  }
274
231
  /** 面向插件的 CLI 封装。 */
275
232
  var LarkCli = class {
276
- /** 解析后的命令。 */
277
- command;
233
+ /** 固定的本机命令。 */
234
+ command = {
235
+ file: "lark-cli",
236
+ args: []
237
+ };
278
238
  runner;
279
- nodePath;
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);
239
+ /** @param runner - 运行器;测试注入。 */
240
+ constructor(runner = defaultRunner) {
288
241
  this.runner = runner;
289
242
  }
290
243
  /** 运行一次调用;非零退出码转为 CliError。 */
291
244
  async run(args, options = {}) {
292
- const env = this.command.file === this.nodePath ? {
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
- });
245
+ const result = await this.runner(this.command, args, options);
300
246
  if (result.code !== 0 && options.allowFailure !== true) {
301
247
  const detail = result.stderr.trim() !== "" ? result.stderr.trim() : result.stdout.trim() !== "" ? result.stdout.trim() : `exit ${result.code}`;
302
248
  throw new CliError("exit", `lark-cli ${args.join(" ")} failed: ${detail.slice(0, 800)}`, result.code);
@@ -313,69 +259,27 @@ var LarkCli = class {
313
259
  * @returns 子进程与 stdout/stderr 读取器。
314
260
  */
315
261
  spawn(args) {
316
- const env = this.command.file === this.nodePath ? {
317
- ...process.env,
318
- ELECTRON_RUN_AS_NODE: "1"
319
- } : process.env;
320
- return spawn(this.command.file, [...this.command.args, ...args], {
262
+ return createCliProcess(this.command, args, {
321
263
  windowsHide: true,
322
264
  stdio: [
323
265
  "pipe",
324
266
  "pipe",
325
267
  "pipe"
326
268
  ],
327
- env
269
+ env: process.env
328
270
  });
329
271
  }
330
272
  };
331
273
  //#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
- /** 插件专用 lark-cli 配置档案名。 */
339
- const DEFAULT_PROFILE = "dsh-lark-bridge";
340
- /** 桥接会话的默认标题。 */
341
- const DEFAULT_SESSION_TITLE = "飞书";
342
- /** 状态目录名,位于 DSH home 下。 */
343
- const STATE_DIR = "lark-bridge";
344
- /** 状态文件名。 */
345
- const STATE_FILE = "state.json";
346
- /** 单条飞书文本消息的最大字符数。 */
347
- const MAX_MESSAGE_CHARS = 15e3;
348
- /** 监听重启的初始与最大退避。 */
349
- const RESTART_MIN_MS = 2e3;
350
- const RESTART_MAX_MS = 6e4;
351
- //#endregion
352
274
  //#region src/auth.ts
353
275
  /**
354
- * lark-cli 鉴权状态机:探测 CLI、专用档案、bot 身份与用户授权。
355
- * 导出 AuthStage、AuthSnapshot、AuthManager 与 LoginFlow。
276
+ * lark-cli 连接状态机:独立探测 CLI、bot 身份与用户身份。
277
+ * 导出 AuthSnapshot 与 AuthManager。
356
278
  */
357
279
  /** 把未知值收窄为对象。 */
358
280
  function recordOf(value) {
359
281
  return typeof value === "object" && value !== null ? value : {};
360
282
  }
361
- /** 从 profile list 输出中找出目标档案。 */
362
- function findProfile(value, name) {
363
- return (Array.isArray(value) ? value : Array.isArray(recordOf(value)["profiles"]) ? recordOf(value)["profiles"] : []).map(recordOf).find((item) => item["name"] === name);
364
- }
365
- /** 读取设备码输出。 */
366
- function parseLoginFlow(value) {
367
- const record = recordOf(value);
368
- const url = record["verification_url"];
369
- const code = record["device_code"];
370
- const expires = Number(record["expires_in"]);
371
- if (typeof url !== "string" || url === "") throw new CliError("invalid-login", "lark-cli did not return a verification URL");
372
- if (typeof code !== "string" || code === "") throw new CliError("invalid-login", "lark-cli did not return a device code");
373
- return {
374
- verificationUrl: url,
375
- deviceCode: code,
376
- expiresAt: Date.now() + (Number.isFinite(expires) && expires > 0 ? expires : 600) * 1e3
377
- };
378
- }
379
283
  /** 读取 auth status 的身份信息。 */
380
284
  function statusIdentities(value) {
381
285
  const root = recordOf(value);
@@ -386,7 +290,6 @@ function statusIdentities(value) {
386
290
  appId: typeof root["appId"] === "string" ? root["appId"] : void 0,
387
291
  bot: typeof bot["status"] === "string" ? bot["status"] : void 0,
388
292
  user: {
389
- status: typeof user["status"] === "string" ? user["status"] : void 0,
390
293
  openId: typeof user["openId"] === "string" ? user["openId"] : void 0,
391
294
  name: typeof user["userName"] === "string" ? user["userName"] : void 0
392
295
  }
@@ -405,223 +308,82 @@ async function probeCli(cli) {
405
308
  return true;
406
309
  }
407
310
  }
408
- /** 鉴权检查与授权动作。 */
311
+ /** 构造检测完成后的基础快照。 */
312
+ function disconnected(checkedAt) {
313
+ return {
314
+ cli: "disconnected",
315
+ bot: "disconnected",
316
+ user: "disconnected",
317
+ ready: false,
318
+ checkedAt,
319
+ appId: void 0,
320
+ userName: void 0,
321
+ ownerOpenId: void 0,
322
+ detail: void 0
323
+ };
324
+ }
325
+ /** 完整检测与状态发布。 */
409
326
  var AuthManager = class {
410
327
  deps;
411
328
  snapshot;
412
329
  checking;
413
- flow;
414
- completing;
415
- cancelled = 0;
416
330
  constructor(deps) {
417
331
  this.deps = deps;
418
332
  this.snapshot = {
419
- stage: "cli-missing",
420
- ready: false,
421
- profile: deps.getConfig().profile,
422
- appId: void 0,
423
- botStatus: void 0,
424
- userName: void 0,
425
- ownerOpenId: void 0,
426
- checkedAt: 0,
427
- detail: void 0
333
+ ...disconnected(0),
334
+ cli: "checking",
335
+ bot: "checking",
336
+ user: "checking"
428
337
  };
429
338
  }
430
339
  /** 最近一次检测结果。 */
431
340
  get current() {
432
341
  return this.snapshot;
433
342
  }
434
- /** 当前已启动的授权流程。 */
435
- get pendingLogin() {
436
- return this.flow;
437
- }
438
- /** 重新检测;并发调用共享同一次检查。 */
439
- check(options = {}) {
343
+ /** 完整检测;并发调用共享同一次检查。 */
344
+ check() {
440
345
  if (this.checking !== void 0) return this.checking;
441
- this.checking = this.runCheck(options).finally(() => {
346
+ this.checking = this.runCheck().finally(() => {
442
347
  this.checking = void 0;
443
348
  });
444
349
  return this.checking;
445
350
  }
446
- async runCheck(options) {
447
- const config = this.deps.getConfig();
351
+ async runCheck() {
448
352
  const cli = this.deps.getCli();
449
- const base = {
450
- stage: "cli-missing",
451
- ready: false,
452
- profile: config.profile,
453
- appId: void 0,
454
- botStatus: void 0,
455
- userName: void 0,
456
- ownerOpenId: void 0,
457
- checkedAt: Date.now(),
458
- detail: void 0
459
- };
353
+ const base = disconnected(Date.now());
460
354
  let next;
461
355
  if (!await probeCli(cli)) next = base;
462
- else {
463
- let profiles;
464
- try {
465
- profiles = await cli.json(["profile", "list"], { timeoutMs: 3e4 });
466
- } catch (error) {
467
- next = {
468
- ...base,
469
- detail: describeError(error)
470
- };
471
- this.publish(next);
472
- return next;
473
- }
474
- if (findProfile(profiles, config.profile) === void 0) next = {
356
+ else try {
357
+ const identities = statusIdentities(await cli.json([
358
+ "auth",
359
+ "status",
360
+ "--json",
361
+ "--verify"
362
+ ], { timeoutMs: 6e4 }));
363
+ const owner = identities.user.openId;
364
+ const botReady = identities.bot === "ready";
365
+ const userReady = owner !== void 0 && owner !== "";
366
+ const ready = botReady && userReady;
367
+ next = {
475
368
  ...base,
476
- stage: "app-missing"
369
+ cli: "connected",
370
+ bot: botReady ? "connected" : "disconnected",
371
+ user: userReady ? "connected" : "disconnected",
372
+ ready,
373
+ appId: identities.appId,
374
+ userName: identities.user.name,
375
+ ownerOpenId: ready ? owner : void 0
376
+ };
377
+ } catch (error) {
378
+ next = {
379
+ ...base,
380
+ cli: "connected",
381
+ detail: describeError(error)
477
382
  };
478
- else try {
479
- const identities = statusIdentities(await cli.json([
480
- "--profile",
481
- config.profile,
482
- "auth",
483
- "status",
484
- "--json",
485
- ...options.verify === true ? ["--verify"] : []
486
- ], { timeoutMs: 6e4 }));
487
- const owner = config.ownerOpenId !== "" ? config.ownerOpenId : identities.user?.openId;
488
- if (identities.bot !== "ready") next = {
489
- ...base,
490
- stage: "bot-unavailable",
491
- appId: identities.appId
492
- };
493
- else if (owner === void 0 || owner === "") next = {
494
- ...base,
495
- stage: "user-missing",
496
- appId: identities.appId,
497
- botStatus: identities.bot,
498
- userName: identities.user?.name,
499
- detail: void 0
500
- };
501
- else next = {
502
- stage: "ready",
503
- ready: true,
504
- profile: config.profile,
505
- appId: identities.appId,
506
- botStatus: identities.bot,
507
- userName: identities.user?.name,
508
- ownerOpenId: owner,
509
- checkedAt: Date.now(),
510
- detail: void 0
511
- };
512
- } catch (error) {
513
- next = {
514
- ...base,
515
- stage: "bot-unavailable",
516
- detail: describeError(error)
517
- };
518
- }
519
383
  }
520
384
  this.publish(next);
521
385
  return next;
522
386
  }
523
- /**
524
- * 用 App ID 与 App Secret 创建或更新专用档案。
525
- * Secret 只写入子进程 stdin,不进入日志或配置。
526
- */
527
- async bindApp(appId, appSecret) {
528
- const config = this.deps.getConfig();
529
- const cli = this.deps.getCli();
530
- const id = appId.trim();
531
- const secret = appSecret.trim();
532
- if (!/^cli_[A-Za-z0-9]+$/.test(id)) throw new CliError("invalid-app-id", "App ID 应以 cli_ 开头");
533
- if (secret === "") throw new CliError("invalid-app-secret", "App Secret 不能为空");
534
- const input = `${secret}\n`;
535
- const add = [
536
- "profile",
537
- "add",
538
- "--name",
539
- config.profile,
540
- "--app-id",
541
- id,
542
- "--app-secret-stdin",
543
- "--brand",
544
- "feishu"
545
- ];
546
- try {
547
- await cli.run(add, {
548
- input,
549
- timeoutMs: 12e4
550
- });
551
- } catch (error) {
552
- const text = describeError(error);
553
- if (!/exist|duplicate|already/i.test(text)) throw error;
554
- this.deps.logger.warn(`lark-bridge: replacing existing profile "${config.profile}"`);
555
- await cli.run([
556
- "profile",
557
- "remove",
558
- config.profile
559
- ], { timeoutMs: 3e4 });
560
- await cli.run(add, {
561
- input,
562
- timeoutMs: 12e4
563
- });
564
- }
565
- return this.check({ verify: true });
566
- }
567
- /**
568
- * 启动设备码授权。
569
- * @returns 授权链接与设备码;完成后台轮询。
570
- */
571
- async startLogin() {
572
- const config = this.deps.getConfig();
573
- const cli = this.deps.getCli();
574
- const scope = this.deps.loginScope ?? "auth:user.id:read";
575
- const flow = parseLoginFlow(await cli.json([
576
- "--profile",
577
- config.profile,
578
- "auth",
579
- "login",
580
- "--no-wait",
581
- "--json",
582
- "--scope",
583
- scope
584
- ], { timeoutMs: 6e4 }));
585
- this.flow = flow;
586
- this.cancelled += 1;
587
- const generation = this.cancelled;
588
- this.deps.logger.info(`lark-bridge: device login started, expires at ${new Date(flow.expiresAt).toISOString()}`);
589
- this.completing = this.completeLogin(flow, generation);
590
- return flow;
591
- }
592
- /** 后台完成设备码授权;失败时记录并刷新状态。 */
593
- async completeLogin(flow, generation) {
594
- const cli = this.deps.getCli();
595
- const remaining = Math.max(3e4, flow.expiresAt - Date.now() + 15e3);
596
- try {
597
- await cli.run([
598
- "--profile",
599
- this.deps.getConfig().profile,
600
- "auth",
601
- "login",
602
- "--device-code",
603
- flow.deviceCode,
604
- "--json"
605
- ], { timeoutMs: remaining });
606
- if (generation !== this.cancelled) return this.snapshot;
607
- this.flow = void 0;
608
- return await this.check({ verify: true });
609
- } catch (error) {
610
- if (generation !== this.cancelled) return this.snapshot;
611
- this.flow = void 0;
612
- this.deps.logger.warn(`lark-bridge: device login failed: ${describeError(error)}`);
613
- return this.check();
614
- }
615
- }
616
- /** 等待后台授权结束;测试与关闭流程使用。 */
617
- async whenLoginSettled() {
618
- return this.completing === void 0 ? void 0 : this.completing;
619
- }
620
- /** 取消当前授权;后台轮询的结果会被丢弃。 */
621
- cancelLogin() {
622
- this.cancelled += 1;
623
- this.flow = void 0;
624
- }
625
387
  /** 更新快照并通知订阅者。 */
626
388
  publish(next) {
627
389
  this.snapshot = next;
@@ -629,22 +391,39 @@ var AuthManager = class {
629
391
  }
630
392
  };
631
393
  //#endregion
394
+ //#region src/constants.ts
395
+ /** 共享常量:插件标识、默认值、工具名与状态目录。 */
396
+ /** 插件标识,与包名、cordis.patch.yml 的 id 一致。 */
397
+ const PLUGIN_LABEL = "dsh-plugin-lark-bridge";
398
+ /** 工具名。 */
399
+ const NOTIFY_TOOL_NAME = "lark_notify";
400
+ /** 桥接会话的固定标题。 */
401
+ const SESSION_TITLE = "来自用户的飞书消息";
402
+ /** 状态目录名,位于 DSH home 下。 */
403
+ const STATE_DIR = "lark-bridge";
404
+ /** 状态文件名。 */
405
+ const STATE_FILE = "state.json";
406
+ /** 单条飞书文本消息的最大字符数。 */
407
+ const MAX_MESSAGE_CHARS = 15e3;
408
+ /** 监听重启的初始与最大退避。 */
409
+ const RESTART_MIN_MS = 2e3;
410
+ const RESTART_MAX_MS = 6e4;
411
+ //#endregion
632
412
  //#region src/bridge.ts
633
413
  /**
634
414
  * 飞书事件桥:消费 bot 身份事件、过滤与去重,并把消息注入桥接会话。
635
- * 导出 EventBridge 与 formatFeishuReminder。
415
+ * 导出 EventBridge 与 formatLarkMessage。
636
416
  */
637
- /** 把一条飞书消息渲染为注入正文。 */
638
- function formatFeishuReminder(event, senderName) {
417
+ /** 把一条飞书消息渲染为 `<lark-message>` 块。 */
418
+ function formatLarkMessage(event) {
639
419
  const time = formatTime(parseTimestamp(event.timestamp ?? event.create_time));
640
420
  const text = typeof event.content === "string" ? event.content.trim() : "";
641
421
  const type = String(event.message_type ?? event.msg_type ?? "text");
642
422
  const body = text === "" ? `[${type} 消息]` : text;
643
- const id = String(event.message_id ?? event.id ?? "");
644
- const header = ["飞书消息", `发送者:${senderName}`];
645
- if (time !== "") header.push(`时间:${time}`);
646
- if (id !== "") header.push(`消息 ID:${id}`);
647
- return `${header.join("\n")}\n\n${body}`;
423
+ const attributes = [`message_id="${escapeAttribute(String(event.message_id ?? event.id ?? ""))}"`];
424
+ if (time !== "") attributes.push(`time="${time}"`);
425
+ const safe = body.replaceAll("</lark-message>", "<\\/lark-message>");
426
+ return `<lark-message ${attributes.join(" ")}>\n${safe}\n</lark-message>`;
648
427
  }
649
428
  /** 返回事件的消息标识。 */
650
429
  function messageId(event) {
@@ -671,9 +450,9 @@ var EventBridge = class {
671
450
  get running() {
672
451
  return this.child !== void 0;
673
452
  }
674
- /** 鉴权就绪时启动;否则保持停止。 */
453
+ /** 鉴权与工作区均有效时启动;否则保持停止。 */
675
454
  start() {
676
- if (this.deps.getAuth().ready !== true) return;
455
+ if (this.deps.getAuth().ready !== true || !this.deps.getWorkspaceReady()) return;
677
456
  this.stopped = false;
678
457
  this.spawn();
679
458
  }
@@ -686,9 +465,9 @@ var EventBridge = class {
686
465
  this.child = void 0;
687
466
  if (child !== void 0) killChildTree(child);
688
467
  }
689
- /** 鉴权状态变化时同步监听。 */
468
+ /** 鉴权或工作区状态变化时同步监听。 */
690
469
  sync(snapshot) {
691
- if (snapshot.ready) {
470
+ if (snapshot.ready && this.deps.getWorkspaceReady()) {
692
471
  if (!this.running) this.start();
693
472
  return;
694
473
  }
@@ -697,13 +476,10 @@ var EventBridge = class {
697
476
  /** 启动一个消费者子进程。 */
698
477
  spawn() {
699
478
  if (this.stopped || this.child !== void 0) return;
700
- const config = this.deps.getConfig();
701
479
  const cli = this.deps.getCli();
702
480
  let child;
703
481
  try {
704
482
  child = cli.spawn([
705
- "--profile",
706
- config.profile,
707
483
  "event",
708
484
  "consume",
709
485
  "im.message.receive_v1",
@@ -774,17 +550,17 @@ var EventBridge = class {
774
550
  /** 处理一条事件:过滤、去重、格式化并注入。 */
775
551
  async handleEvent(event) {
776
552
  const auth = this.deps.getAuth();
777
- if (auth.ready !== true) return false;
778
- const owner = auth.ownerOpenId ?? this.deps.getConfig().ownerOpenId;
553
+ if (auth.ready !== true || !this.deps.getWorkspaceReady()) return false;
554
+ const owner = auth.ownerOpenId;
779
555
  if (owner === void 0 || owner === "") return false;
780
556
  if (!acceptEvent(event, owner)) return false;
781
557
  const id = messageId(event);
782
558
  if (id === "") return false;
783
559
  const time = parseTimestamp(event.timestamp ?? event.create_time);
784
560
  if (!await this.deps.store.markSeen(id, time)) return false;
785
- const body = formatFeishuReminder(event, auth.userName ?? owner);
561
+ const block = formatLarkMessage(event);
786
562
  try {
787
- const result = await this.deps.sessions.inject(body);
563
+ const result = await this.deps.sessions.inject(block);
788
564
  this.deps.logger.info(`lark-bridge: delivered ${id} to session ${result.sessionId} (created=${String(result.created)})`);
789
565
  return true;
790
566
  } catch (error) {
@@ -794,39 +570,56 @@ var EventBridge = class {
794
570
  }
795
571
  };
796
572
  //#endregion
573
+ //#region src/workspace-path.ts
574
+ /** 工作区路径:统一 Linux 风格表示、平台比较与 Host 原生路径转换。 */
575
+ /** 判断原始或归一化路径是否使用 Windows 语义。 */
576
+ function isWindowsPath(value) {
577
+ return /^(?:[A-Za-z]:[\\/]|\\\\|\/\/|\/[A-Za-z](?:\/|$))/.test(value);
578
+ }
579
+ /** 统一斜杠、末尾分隔符与 Windows 盘符,例如 `C:\work\demo` 转为 `/c/work/demo`。 */
580
+ function normalizeWorkspacePath(value) {
581
+ const slashed = value.trim().replaceAll("\\", "/");
582
+ if (slashed === "") return "";
583
+ const drive = /^([A-Za-z]):(?:\/+(.*))?$/.exec(slashed);
584
+ if (drive !== null) {
585
+ const rest = (drive[2] ?? "").replace(/\/{2,}/g, "/").replace(/\/+$/, "");
586
+ return `/${drive[1]?.toLowerCase()}${rest === "" ? "" : `/${rest}`}`;
587
+ }
588
+ const unc = slashed.startsWith("//");
589
+ const collapsed = slashed.replace(/\/{2,}/g, "/");
590
+ const withoutTrailing = collapsed.length > 1 ? collapsed.replace(/\/+$/, "") : collapsed;
591
+ return unc ? `/${withoutTrailing}` : withoutTrailing;
592
+ }
593
+ /** 比较工作区路径;Windows 忽略大小写,POSIX 保持大小写敏感。 */
594
+ function sameWorkspacePath(a, b) {
595
+ const left = normalizeWorkspacePath(a);
596
+ const right = normalizeWorkspacePath(b);
597
+ return isWindowsPath(a) || isWindowsPath(b) ? left.toLowerCase() === right.toLowerCase() : left === right;
598
+ }
599
+ /** 在 Host 边界把归一化路径转换为当前平台的原生形式。 */
600
+ function toHostWorkspacePath(value, platform = process.platform) {
601
+ const normalized = normalizeWorkspacePath(value);
602
+ if (platform !== "win32") return normalized;
603
+ const drive = /^\/([A-Za-z])(?:\/(.*))?$/.exec(normalized);
604
+ if (drive !== null) return `${drive[1]?.toUpperCase()}:${drive[2] === void 0 ? "/" : `/${drive[2]}`}`;
605
+ if (normalized.startsWith("//")) return `\\\\${normalized.slice(2).replaceAll("/", "\\")}`;
606
+ return normalized;
607
+ }
608
+ //#endregion
797
609
  //#region src/config.ts
798
- /**
799
- * 插件配置:schema、默认值与严格校验。
800
- * 导出 Config、PluginConfig、resolveConfig 与 readConfig。
801
- */
802
- /**
803
- * 配置 schema。`.volatile()` 字段修改后不重启插件,并出现在配置页。
804
- * schema 不拒绝未知键,严格校验由 resolveConfig 完成。
805
- */
806
- const Config = Schema.object({
807
- workspaceRoot: Schema.string().default("").volatile(),
808
- sessionTitle: Schema.string().default(DEFAULT_SESSION_TITLE).volatile(),
809
- profile: Schema.string().default(DEFAULT_PROFILE).pattern(/^[A-Za-z0-9._-]+$/).volatile(),
810
- larkCli: Schema.string().default("").volatile(),
811
- ownerOpenId: Schema.string().default("").volatile(),
812
- authCheckOnStartup: Schema.boolean().default(true).volatile()
813
- });
610
+ /** 插件配置:单工作区 schema、路径归一化、严格校验与旧键兼容。 */
611
+ /** 配置 schema;严格键校验由 resolveConfig 完成。 */
612
+ const Config = Schema.object({ workspaceRoot: Schema.string().default("").volatile() });
814
613
  /** 默认配置。 */
815
- const DEFAULT_CONFIG = Object.freeze({
816
- workspaceRoot: "",
817
- sessionTitle: DEFAULT_SESSION_TITLE,
818
- profile: DEFAULT_PROFILE,
819
- larkCli: "",
820
- ownerOpenId: "",
821
- authCheckOnStartup: true
822
- });
823
- /** 合法的配置键。出现其他键时报错。 */
824
- const CONFIG_KEYS = /* @__PURE__ */ new Set([
825
- "workspaceRoot",
826
- "sessionTitle",
614
+ const DEFAULT_CONFIG = Object.freeze({ workspaceRoot: "" });
615
+ /** 合法的当前配置键。 */
616
+ const CONFIG_KEYS = /* @__PURE__ */ new Set(["workspaceRoot"]);
617
+ /** 旧版本的配置键:接受并丢弃,避免升级后插件加载失败。 */
618
+ const LEGACY_KEYS = /* @__PURE__ */ new Set([
827
619
  "profile",
828
- "larkCli",
829
620
  "ownerOpenId",
621
+ "larkCli",
622
+ "sessionTitle",
830
623
  "authCheckOnStartup"
831
624
  ]);
832
625
  /** 把缺省或 null 的输入转为空对象。 */
@@ -835,59 +628,107 @@ function normalizeConfigInput(raw) {
835
628
  if (!isRecord(raw)) throw new Error(`${PLUGIN_LABEL}: config must be an object`);
836
629
  return raw;
837
630
  }
838
- /** 读取一个字符串字段并 trim;缺省或 null 用默认值。 */
839
- function stringField(input, key, fallback, validate) {
840
- const raw = input[key];
841
- if (raw === void 0 || raw === null) return fallback;
842
- if (typeof raw !== "string") throw new Error(`${PLUGIN_LABEL}: config ${key} must be a string`);
843
- const value = raw.trim();
844
- validate(value);
845
- return value;
846
- }
847
- /** 校验配置并与默认值合并,返回冻结的完整配置。 */
631
+ /** 校验配置并与默认值合并,工作区路径统一为 Linux 风格。 */
848
632
  function resolveConfig(raw) {
849
633
  const input = normalizeConfigInput(raw);
850
- for (const key of Object.keys(input)) if (!CONFIG_KEYS.has(key)) throw new Error(`${PLUGIN_LABEL}: unknown config key "${key}"`);
851
- const config = { ...DEFAULT_CONFIG };
852
- config.workspaceRoot = stringField(input, "workspaceRoot", DEFAULT_CONFIG.workspaceRoot, () => {});
853
- config.sessionTitle = stringField(input, "sessionTitle", DEFAULT_CONFIG.sessionTitle, (value) => {
854
- if (value === "") throw new Error(`${PLUGIN_LABEL}: config sessionTitle must not be empty`);
855
- });
856
- config.profile = stringField(input, "profile", DEFAULT_CONFIG.profile, (value) => {
857
- if (!/^[A-Za-z0-9._-]+$/.test(value)) throw new Error(`${PLUGIN_LABEL}: config profile must match [A-Za-z0-9._-]+`);
858
- });
859
- config.larkCli = stringField(input, "larkCli", DEFAULT_CONFIG.larkCli, () => {});
860
- config.ownerOpenId = stringField(input, "ownerOpenId", DEFAULT_CONFIG.ownerOpenId, (value) => {
861
- if (value !== "" && !value.startsWith("ou_")) throw new Error(`${PLUGIN_LABEL}: config ownerOpenId must start with "ou_"`);
862
- });
863
- const authCheck = input.authCheckOnStartup;
864
- if (authCheck !== void 0 && authCheck !== null) {
865
- if (typeof authCheck !== "boolean") throw new Error(`${PLUGIN_LABEL}: config authCheckOnStartup must be a boolean`);
866
- config.authCheckOnStartup = authCheck;
867
- }
868
- return Object.freeze(config);
634
+ 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}"`);
635
+ const value = input["workspaceRoot"];
636
+ if (value !== void 0 && value !== null && typeof value !== "string") throw new Error(`${PLUGIN_LABEL}: config workspaceRoot must be a string`);
637
+ return Object.freeze({ workspaceRoot: typeof value === "string" ? normalizeWorkspacePath(value) : DEFAULT_CONFIG.workspaceRoot });
869
638
  }
870
639
  /** 判断值是否是热重载引用。 */
871
640
  function isVolatileRef(value) {
872
641
  return isRecord(value) && typeof value.get === "function";
873
642
  }
874
- /** 读取宿主传入配置的当前值:展开热重载引用后交给 resolveConfig 校验。 */
643
+ /** 展开热重载引用后交给 resolveConfig 校验。 */
875
644
  function readConfig(config) {
876
645
  if (!isRecord(config)) return resolveConfig(config);
877
646
  const values = {};
878
647
  for (const [key, value] of Object.entries(config)) values[key] = isVolatileRef(value) ? value.get() : value;
879
648
  return resolveConfig(values);
880
649
  }
881
- /**
882
- * 解析插件状态文件路径。
883
- * @param home - DSH home;省略时读取 `DSH_HOME`,再回落到 `~/.dsh`。
884
- * @returns `state.json` 的绝对路径。
885
- */
650
+ /** 解析插件状态文件路径。 */
886
651
  function statePath(home) {
887
652
  const root = home ?? process.env["DSH_HOME"] ?? join(homedir(), ".dsh");
888
653
  return join(root, STATE_DIR, STATE_FILE);
889
654
  }
890
655
  //#endregion
656
+ //#region src/message.ts
657
+ /** 飞书消息块的来源标记。 */
658
+ const LARK_SOURCE = { kind: "lark-bridge" };
659
+ /** 桥接提醒的来源标记。 */
660
+ const REMINDER_SOURCE = {
661
+ kind: "lark-bridge",
662
+ reminder: true
663
+ };
664
+ /** 判断消息是否由本插件注入。 */
665
+ function isLarkMessage(message) {
666
+ return message.role === "user" && message.source.kind === "lark-bridge";
667
+ }
668
+ /** 判断消息是否是一条桥接提醒。 */
669
+ function isReminderMessage(message) {
670
+ if (!isLarkMessage(message)) return false;
671
+ return message.source.kind === "lark-bridge" && message.source.reminder === true;
672
+ }
673
+ //#endregion
674
+ //#region src/reminder.ts
675
+ /** 提醒正文;说明块含义与回复规则。 */
676
+ const BRIDGE_REMINDER = [
677
+ "<lark-message> 块是用户通过飞书远程发送的消息。",
678
+ "用户只能看到 lark_notify 发送的内容,看不到本会话的回复。",
679
+ "- 回复飞书消息时调用 lark_notify,把要发给用户的内容放进 text。",
680
+ "- 用户连续发来多条 <lark-message> 时只回复一次,用一次 lark_notify 覆盖全部内容。",
681
+ "- 会话里的 text 块用户看不到,尽量少输出,说明性文字也放进 lark_notify。",
682
+ "- 其他来源的用户消息按普通方式回复,不调用 lark_notify。"
683
+ ].join("\n");
684
+ /** 构造提醒消息。 */
685
+ function createReminderMessage() {
686
+ return createUserMessage({
687
+ content: [{
688
+ type: "text",
689
+ text: reminder(BRIDGE_REMINDER)
690
+ }],
691
+ source: REMINDER_SOURCE
692
+ });
693
+ }
694
+ /** 表层是否已有桥接提醒。 */
695
+ function surfaceHasReminder(session) {
696
+ for (const seq of session.surface.nodes) {
697
+ const event = session.eventAt(seq);
698
+ if (event?.type === "user/message" && isReminderMessage(event.data)) return true;
699
+ }
700
+ return false;
701
+ }
702
+ /**
703
+ * 注册 `agent/pre-step` 补注:桥接会话表层缺少提醒时,把它插到本批第一条块之前。
704
+ * @param deps - 上下文、会话判定与日志。
705
+ * @returns 注销函数。
706
+ */
707
+ function installReminderGuard(deps) {
708
+ return deps.ctx.on("agent/pre-step", async ({ agent, step }, next) => {
709
+ const decision = await next();
710
+ if (decision.kind === "reject") return decision;
711
+ if (step === 1 && decision.messages.length === 0) return decision;
712
+ const session = agent.session;
713
+ let bridge = false;
714
+ try {
715
+ bridge = await deps.sessions.isBridgeSession(session);
716
+ } catch (error) {
717
+ deps.logger.warn(`lark-bridge: cannot resolve reminder state: ${describeError(error)}`);
718
+ return decision;
719
+ }
720
+ if (!bridge) return decision;
721
+ if (surfaceHasReminder(session)) return decision;
722
+ if (decision.messages.some(isReminderMessage)) return decision;
723
+ const index = decision.messages.findIndex(isLarkMessage);
724
+ const messages = decision.messages.toSpliced(index === -1 ? 0 : index, 0, createReminderMessage());
725
+ return {
726
+ ...decision,
727
+ messages
728
+ };
729
+ });
730
+ }
731
+ //#endregion
891
732
  //#region src/errors.ts
892
733
  /** 插件可诊断错误:携带稳定错误码,供工具与路由返回。 */
893
734
  var BridgeError = class extends Error {
@@ -907,8 +748,6 @@ var BridgeError = class extends Error {
907
748
  //#region src/routes.ts
908
749
  /** 路由前缀。 */
909
750
  const ROUTE_PREFIX = "/lark-bridge";
910
- /** 请求体上限。 */
911
- const BODY_LIMIT = 65536;
912
751
  /** 写 JSON 响应。 */
913
752
  function send(res, status, body) {
914
753
  const text = JSON.stringify(body);
@@ -919,24 +758,6 @@ function send(res, status, body) {
919
758
  });
920
759
  res.end(text);
921
760
  }
922
- /** 读取并解析 JSON 请求体。 */
923
- async function readBody(req) {
924
- let size = 0;
925
- const chunks = [];
926
- for await (const chunk of req) {
927
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
928
- size += buffer.length;
929
- if (size > BODY_LIMIT) throw new BridgeError("body-too-large", "请求体超过 64 KiB");
930
- chunks.push(buffer);
931
- }
932
- const text = Buffer.concat(chunks).toString("utf8").trim();
933
- if (text === "") return {};
934
- try {
935
- return JSON.parse(text);
936
- } catch {
937
- throw new BridgeError("invalid-json", "请求体不是合法 JSON");
938
- }
939
- }
940
761
  /** 判断请求是否来自回环地址。 */
941
762
  function isLoopback(req) {
942
763
  const address = req.socket.remoteAddress ?? "";
@@ -958,95 +779,43 @@ function rejectReason(deps, req) {
958
779
  return describeError(error);
959
780
  }
960
781
  }
961
- /** 把当前状态投影为可发送的 JSON。 */
962
- async function projectStatus(deps) {
963
- const config = deps.getConfig();
782
+ /** 投影浏览器可读的笼统状态,排除内部身份与诊断信息。 */
783
+ function projectStatus(deps) {
964
784
  const snapshot = deps.auth.current;
965
- const state = await deps.store.load();
966
- const flow = deps.auth.pendingLogin;
967
785
  return {
968
- ...snapshot,
969
- workspaceRoot: config.workspaceRoot,
970
- sessionId: state.sessionId,
971
- sessionWorkspace: state.workspaceRoot,
972
- sessionTitle: state.title,
973
- error: deps.sessions.lastError,
974
- login: flow === void 0 ? null : {
975
- verificationUrl: flow.verificationUrl,
976
- expiresAt: flow.expiresAt
977
- }
786
+ cli: snapshot.cli,
787
+ bot: snapshot.bot,
788
+ user: snapshot.user,
789
+ ready: snapshot.ready,
790
+ checkedAt: snapshot.checkedAt
978
791
  };
979
792
  }
980
793
  /** 执行路由动作并生成响应。 */
981
- async function handle(deps, path, method, req) {
794
+ async function handle(deps, path, method) {
982
795
  if (method === "GET" && path === `/lark-bridge/status`) return {
983
796
  ok: true,
984
- data: await projectStatus(deps)
797
+ data: projectStatus(deps)
985
798
  };
986
799
  if (method !== "POST") throw new BridgeError("method-not-allowed", "只支持 GET 与 POST");
987
800
  if (path === `/lark-bridge/check`) {
988
- const snapshot = await deps.auth.check({ verify: true });
989
- deps.onAuthChanged?.(snapshot);
990
- return {
991
- ok: true,
992
- data: await projectStatus(deps)
993
- };
994
- }
995
- if (path === `/lark-bridge/app`) {
996
- const body = await readBody(req);
997
- const record = typeof body === "object" && body !== null ? body : {};
998
- const appId = typeof record["appId"] === "string" ? record["appId"] : "";
999
- const appSecret = typeof record["appSecret"] === "string" ? record["appSecret"] : "";
1000
- const snapshot = await deps.auth.bindApp(appId, appSecret);
801
+ const snapshot = await deps.auth.check();
1001
802
  deps.onAuthChanged?.(snapshot);
1002
- return {
1003
- ok: true,
1004
- data: await projectStatus(deps)
1005
- };
1006
- }
1007
- if (path === `/lark-bridge/auth/start`) {
1008
- const flow = await deps.auth.startLogin();
1009
- deps.auth.whenLoginSettled().then((snapshot) => {
1010
- if (snapshot !== void 0) deps.onAuthChanged?.(snapshot);
1011
- });
1012
803
  return {
1013
804
  ok: true,
1014
805
  data: {
1015
- verificationUrl: flow.verificationUrl,
1016
- expiresAt: flow.expiresAt
806
+ cli: snapshot.cli,
807
+ bot: snapshot.bot,
808
+ user: snapshot.user,
809
+ ready: snapshot.ready,
810
+ checkedAt: snapshot.checkedAt
1017
811
  }
1018
812
  };
1019
813
  }
1020
- if (path === `/lark-bridge/auth/cancel`) {
1021
- deps.auth.cancelLogin();
1022
- return {
1023
- ok: true,
1024
- data: await projectStatus(deps)
1025
- };
1026
- }
1027
- if (path === `/lark-bridge/session/reset`) {
1028
- await deps.sessions.reset();
1029
- return {
1030
- ok: true,
1031
- data: await projectStatus(deps)
1032
- };
1033
- }
1034
814
  throw new BridgeError("not-found", "未知的桥接接口");
1035
815
  }
1036
- /**
1037
- * 注册全部桥接路由。
1038
- * @param deps - 服务、存储与状态来源。
1039
- * @returns 注销全部路由的清理函数。
1040
- */
816
+ /** 注册桥接路由并返回清理函数。 */
1041
817
  function registerRoutes(deps) {
1042
- const paths = [
1043
- "status",
1044
- "check",
1045
- "app",
1046
- "auth/start",
1047
- "auth/cancel",
1048
- "session/reset"
1049
- ];
818
+ const paths = ["status", "check"];
1050
819
  const disposers = [];
1051
820
  for (const suffix of paths) {
1052
821
  const path = `${ROUTE_PREFIX}/${suffix}`;
@@ -1066,7 +835,7 @@ function registerRoutes(deps) {
1066
835
  return;
1067
836
  }
1068
837
  try {
1069
- send(res, 200, await handle(deps, path, req.method ?? "GET", req));
838
+ send(res, 200, await handle(deps, path, req.method ?? "GET"));
1070
839
  } catch (error) {
1071
840
  const code = error instanceof BridgeError ? error.code : "internal";
1072
841
  const message = describeError(error);
@@ -1092,8 +861,6 @@ function registerRoutes(deps) {
1092
861
  * 桥接会话:工作区校验、创建或恢复、标题、挂载、置顶与状态持久化。
1093
862
  * 导出 SessionManager。
1094
863
  */
1095
- /** 飞书来源的消息标记。 */
1096
- const SOURCE = { kind: "lark-bridge" };
1097
864
  /** 把路径解析为绝对路径。 */
1098
865
  function absolute(path) {
1099
866
  return resolve(path);
@@ -1118,16 +885,6 @@ function appendTitle(session, title) {
1118
885
  };
1119
886
  session.append.call(session, "session/title", data);
1120
887
  }
1121
- /** 构造用于注入的 system-reminder 用户消息。 */
1122
- function reminderMessage(text) {
1123
- return createUserMessage({
1124
- content: [{
1125
- type: "text",
1126
- text: reminder(text)
1127
- }],
1128
- source: SOURCE
1129
- });
1130
- }
1131
888
  /** 桥接会话的创建、恢复与注入。 */
1132
889
  var SessionManager = class {
1133
890
  deps;
@@ -1169,16 +926,15 @@ var SessionManager = class {
1169
926
  }
1170
927
  };
1171
928
  }
1172
- /** 把会话挂到其 cwd 对应的工作区。 */
1173
- async attach(sessionId, cwd) {
1174
- const registry = this.registry();
1175
- const workspace = await registry.resolveByPath(cwd) ?? await registry.create(cwd);
929
+ /** 把会话挂到已注册工作区。 */
930
+ async attach(sessionId, workspace) {
1176
931
  const id = SessionId(sessionId);
1177
932
  if (!workspace.sessionIds.includes(id)) await workspace.attachSession(id);
1178
933
  }
1179
934
  /** 恢复一个可用会话;失败返回 undefined。 */
1180
935
  async resume(sessionId) {
1181
936
  const id = SessionId(sessionId);
937
+ if (this.registry().archivedSessionIds.includes(id)) return void 0;
1182
938
  const live = this.ctx.agents.get(id);
1183
939
  if (live !== void 0) return live;
1184
940
  try {
@@ -1194,7 +950,7 @@ var SessionManager = class {
1194
950
  }
1195
951
  }
1196
952
  /** 新建会话,设置标题、挂到工作区并置顶。 */
1197
- async create(cwd, title) {
953
+ async create(cwd, title, workspace) {
1198
954
  const sessionId = randomUUID();
1199
955
  const handle = await this.ctx.agents.create({
1200
956
  sessionId: SessionId(sessionId),
@@ -1204,11 +960,11 @@ var SessionManager = class {
1204
960
  appendTitle(child.session, title);
1205
961
  }
1206
962
  });
1207
- await this.attach(sessionId, cwd);
963
+ await this.attach(sessionId, workspace);
1208
964
  await this.registry().pinSession(SessionId(sessionId));
1209
965
  await this.deps.store.patch({
1210
966
  sessionId,
1211
- workspaceRoot: cwd,
967
+ workspaceRoot: normalizeWorkspacePath(cwd),
1212
968
  title
1213
969
  });
1214
970
  this.deps.logger.info(`lark-bridge: created session ${sessionId} in ${cwd}`);
@@ -1235,38 +991,47 @@ var SessionManager = class {
1235
991
  * @returns 会话标识、会话实例与是否新建。
1236
992
  */
1237
993
  async ensure(workspaceRoot) {
1238
- const cwd = await assertWorkspace(workspaceRoot);
1239
- const config = this.deps.getConfig();
994
+ const cwd = toHostWorkspacePath(workspaceRoot);
995
+ await assertWorkspace(cwd);
996
+ const workspace = await this.registry().resolveByPath(cwd);
997
+ if (workspace === void 0) throw new BridgeError("workspace-unregistered", `工作区未注册:${normalizeWorkspacePath(cwd)}`);
1240
998
  const state = await this.deps.store.load();
1241
- if (state.sessionId !== null && state.workspaceRoot !== null && samePath(state.workspaceRoot, cwd)) {
999
+ if (state.sessionId !== null && state.workspaceRoot !== null && sameWorkspacePath(state.workspaceRoot, cwd)) {
1242
1000
  const agent = await this.resume(state.sessionId);
1243
1001
  if (agent !== void 0) {
1244
- await this.syncMeta(state.sessionId, agent, config.sessionTitle, state.title ?? config.sessionTitle);
1002
+ await this.syncMeta(state.sessionId, agent, SESSION_TITLE, state.title ?? "来自用户的飞书消息");
1245
1003
  return {
1246
1004
  sessionId: state.sessionId,
1247
1005
  agent,
1248
- created: false
1006
+ created: false,
1007
+ cwd
1249
1008
  };
1250
1009
  }
1251
1010
  }
1252
- const created = await this.create(cwd, config.sessionTitle);
1253
1011
  return {
1254
- sessionId: created.sessionId,
1255
- agent: created.agent,
1256
- created: true
1012
+ ...await this.create(cwd, SESSION_TITLE, workspace),
1013
+ created: true,
1014
+ cwd
1257
1015
  };
1258
1016
  }
1259
1017
  /**
1260
- * 把一段飞书文本注入桥接会话。
1261
- * @param text - 已格式化的提醒正文。
1018
+ * 把一段飞书消息块注入桥接会话。
1019
+ * @param block - 已格式化的 `<lark-message>` 块。
1262
1020
  * @returns 注入目标与会话是否新建。
1263
1021
  */
1264
- async inject(text) {
1022
+ async inject(block) {
1265
1023
  try {
1266
1024
  const config = this.deps.getConfig();
1267
1025
  if (config.workspaceRoot === "") throw new BridgeError("workspace-missing", "尚未配置桥接工作区");
1268
- const { sessionId, agent, created } = await this.ensure(config.workspaceRoot);
1269
- agent.followup(reminderMessage(text));
1026
+ const { sessionId, agent, created, cwd } = await this.ensure(config.workspaceRoot);
1027
+ if (await this.registry().resolveByPath(cwd) === void 0) throw new BridgeError("workspace-unregistered", `工作区未注册:${normalizeWorkspacePath(cwd)}`);
1028
+ agent.followup(createUserMessage({
1029
+ content: [{
1030
+ type: "text",
1031
+ text: block
1032
+ }],
1033
+ source: LARK_SOURCE
1034
+ }));
1270
1035
  this.failure = void 0;
1271
1036
  return {
1272
1037
  sessionId,
@@ -1276,9 +1041,14 @@ var SessionManager = class {
1276
1041
  this.fail(error);
1277
1042
  }
1278
1043
  }
1279
- /** 清除会话记录,下一次消息新建。 */
1280
- async reset() {
1281
- await this.deps.store.resetSession();
1044
+ /**
1045
+ * 判断会话是否是当前桥接会话。
1046
+ * @param session - 宿主的会话实例。
1047
+ * @returns 状态文件记录的就是该会话时为 true。
1048
+ */
1049
+ async isBridgeSession(session) {
1050
+ const state = await this.deps.store.load();
1051
+ return state.sessionId !== null && state.sessionId === session.id;
1282
1052
  }
1283
1053
  };
1284
1054
  //#endregion
@@ -1333,6 +1103,7 @@ var StateStore = class {
1333
1103
  const parsed = JSON.parse(text);
1334
1104
  this.cache = isState(parsed) ? {
1335
1105
  ...parsed,
1106
+ workspaceRoot: parsed.workspaceRoot === null ? null : normalizeWorkspacePath(parsed.workspaceRoot),
1336
1107
  seen: trimSeen(parsed.seen, this.limit)
1337
1108
  } : emptyState();
1338
1109
  } catch {
@@ -1360,6 +1131,7 @@ var StateStore = class {
1360
1131
  }, this.limit),
1361
1132
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1362
1133
  };
1134
+ if (next.workspaceRoot !== null) next.workspaceRoot = normalizeWorkspacePath(next.workspaceRoot);
1363
1135
  await this.write(next);
1364
1136
  this.cache = next;
1365
1137
  return next;
@@ -1408,14 +1180,6 @@ var StateStore = class {
1408
1180
  return next;
1409
1181
  });
1410
1182
  }
1411
- /** 清除会话标识,保留下一次消息重建。 */
1412
- resetSession() {
1413
- return this.patch({
1414
- sessionId: null,
1415
- workspaceRoot: null,
1416
- title: null
1417
- });
1418
- }
1419
1183
  /** 把写操作串到同一条队列,避免并发覆盖。 */
1420
1184
  enqueue(action) {
1421
1185
  const next = this.queue.then(action, action);
@@ -1463,17 +1227,14 @@ async function sendNotification(deps, args) {
1463
1227
  ok: false,
1464
1228
  error: {
1465
1229
  code: "owner-missing",
1466
- message: "尚未确定已绑定用户,请先在配置页完成鉴权"
1230
+ message: "尚未确定已绑定用户,请在终端登录后重新检测"
1467
1231
  }
1468
1232
  };
1469
- const config = deps.getConfig();
1470
1233
  const parts = splitText(text, MAX_MESSAGE_CHARS);
1471
1234
  const baseKey = `lark-notify-${randomUUID()}`;
1472
1235
  let first;
1473
1236
  for (const [index, part] of parts.entries()) try {
1474
1237
  const value = await deps.getCli().json([
1475
- "--profile",
1476
- config.profile,
1477
1238
  "im",
1478
1239
  "+messages-send",
1479
1240
  "--as",
@@ -1481,10 +1242,10 @@ async function sendNotification(deps, args) {
1481
1242
  "--user-id",
1482
1243
  owner,
1483
1244
  "--text",
1484
- part,
1245
+ "-",
1485
1246
  "--idempotency-key",
1486
1247
  `${baseKey}-${index}`.slice(0, 50)
1487
- ]);
1248
+ ], { input: part });
1488
1249
  const record = typeof value === "object" && value !== null ? value : {};
1489
1250
  first ??= typeof record["message_id"] === "string" ? record["message_id"] : void 0;
1490
1251
  } catch (error) {
@@ -1569,28 +1330,83 @@ function buildNotifyTool(deps) {
1569
1330
  };
1570
1331
  }
1571
1332
  //#endregion
1333
+ //#region src/workspace.ts
1334
+ /** 保存最近一次有效解析,并用序号阻止旧结果覆盖新选择。 */
1335
+ var WorkspaceSelection = class {
1336
+ deps;
1337
+ revision = 0;
1338
+ selectedRoot = "";
1339
+ selectedWorkspace;
1340
+ constructor(deps) {
1341
+ this.deps = deps;
1342
+ }
1343
+ /** 当前配置是否与已解析的注册工作区一致。 */
1344
+ get valid() {
1345
+ return this.selectedWorkspace !== void 0 && sameWorkspacePath(this.selectedRoot, this.deps.getWorkspaceRoot());
1346
+ }
1347
+ /** 当前注册工作区 id。 */
1348
+ get currentId() {
1349
+ return this.valid && this.selectedWorkspace !== void 0 ? String(this.selectedWorkspace.id) : void 0;
1350
+ }
1351
+ /** 使当前缓存和未完成的解析失效。 */
1352
+ reset() {
1353
+ this.revision += 1;
1354
+ this.selectedRoot = "";
1355
+ this.selectedWorkspace = void 0;
1356
+ }
1357
+ /** 目标注册项删除时同步失效。 */
1358
+ invalidate(change) {
1359
+ if (typeof change !== "object" || change === null) return false;
1360
+ const record = change;
1361
+ if (record["domain"] !== "workspace" || record["table"] !== "workspaces" || record["operation"] !== "deleted" || record["key"] !== this.currentId) return false;
1362
+ this.reset();
1363
+ return true;
1364
+ }
1365
+ /** 解析当前配置;只有最新结果可以更新缓存。 */
1366
+ async resolve() {
1367
+ const revision = ++this.revision;
1368
+ const root = normalizeWorkspacePath(this.deps.getWorkspaceRoot());
1369
+ let workspace;
1370
+ if (root !== "") {
1371
+ const registry = this.deps.getRegistry();
1372
+ try {
1373
+ workspace = await registry?.resolveByPath(toHostWorkspacePath(root));
1374
+ } catch {
1375
+ workspace = void 0;
1376
+ }
1377
+ }
1378
+ const current = revision === this.revision && sameWorkspacePath(root, this.deps.getWorkspaceRoot());
1379
+ if (current) {
1380
+ this.selectedRoot = root;
1381
+ this.selectedWorkspace = workspace;
1382
+ }
1383
+ return {
1384
+ root,
1385
+ workspace,
1386
+ current
1387
+ };
1388
+ }
1389
+ };
1390
+ //#endregion
1572
1391
  //#region src/index.ts
1573
- /**
1574
- * 插件入口:导出宿主约定的 name、inject、apply 与 Config。
1575
- * 装配鉴权、事件桥、会话、通知工具与浏览器路由。
1576
- */
1577
1392
  /** 插件名,与 cordis.patch.yml 的 id 一致。 */
1578
1393
  const name = PLUGIN_LABEL;
1579
1394
  /** 需要宿主注入的服务。 */
1580
1395
  const inject = [
1581
1396
  "tools",
1582
1397
  "agents",
1583
- "webServer"
1398
+ "webServer",
1399
+ "workspaceRegistry"
1584
1400
  ];
1585
1401
  /**
1586
1402
  * 插件启用时调用:读取配置、装配服务、注册工具与路由、启动鉴权检查。
1587
- * 配置字段均为热重载引用,保存后按新值重建 CLI 适配并重新检测。
1403
+ * 配置字段均为热重载引用,保存后更新配置并重新检测。
1588
1404
  */
1589
1405
  function apply(ctx, config) {
1590
1406
  let current = readConfig(config);
1591
1407
  ctx.logger.info(`[${PLUGIN_LABEL}] apply`);
1592
1408
  const store = new StateStore(statePath());
1593
- let cli = new LarkCli(current.larkCli);
1409
+ const cli = new LarkCli();
1594
1410
  let lastStage = "";
1595
1411
  const sessions = new SessionManager({
1596
1412
  ctx,
@@ -1598,32 +1414,46 @@ function apply(ctx, config) {
1598
1414
  getConfig: () => current,
1599
1415
  logger: ctx.logger
1600
1416
  });
1417
+ const uninstallReminder = installReminderGuard({
1418
+ ctx,
1419
+ sessions,
1420
+ logger: ctx.logger
1421
+ });
1422
+ ctx.effect(() => () => uninstallReminder(), `${PLUGIN_LABEL}: reminder guard`);
1423
+ const selection = new WorkspaceSelection({
1424
+ getWorkspaceRoot: () => current.workspaceRoot,
1425
+ getRegistry: () => ctx.get("workspaceRegistry")
1426
+ });
1601
1427
  let bridge;
1428
+ let reconcile;
1602
1429
  const auth = new AuthManager({
1603
- getConfig: () => current,
1604
1430
  getCli: () => cli,
1605
1431
  logger: ctx.logger,
1606
1432
  onChange: (snapshot) => {
1607
- const stage = snapshot.ready ? "ready" : snapshot.stage;
1608
- if (stage !== lastStage) {
1609
- lastStage = stage;
1610
- ctx.logger.info(`[${PLUGIN_LABEL}] auth stage: ${stage}`);
1433
+ const state = snapshot.ready ? "ready" : `${snapshot.cli}/${snapshot.bot}/${snapshot.user}`;
1434
+ if (state !== lastStage) {
1435
+ lastStage = state;
1436
+ ctx.logger.info(`[${PLUGIN_LABEL}] auth state: ${state}`);
1611
1437
  }
1612
- bridge.sync(snapshot);
1438
+ if (!snapshot.ready) bridge.stop();
1439
+ reconcile();
1613
1440
  }
1614
1441
  });
1615
1442
  bridge = new EventBridge({
1616
- getConfig: () => current,
1617
1443
  getCli: () => cli,
1618
1444
  getAuth: () => auth.current,
1445
+ getWorkspaceReady: () => selection.valid,
1619
1446
  store,
1620
1447
  sessions,
1621
1448
  logger: ctx.logger
1622
1449
  });
1450
+ reconcile = async () => {
1451
+ if (!auth.current.ready) bridge.stop();
1452
+ if ((await selection.resolve()).current) bridge.sync(auth.current);
1453
+ };
1623
1454
  const notifyTool = buildNotifyTool({
1624
- getConfig: () => current,
1625
1455
  getCli: () => cli,
1626
- getOwner: () => auth.current.ownerOpenId ?? (current.ownerOpenId === "" ? void 0 : current.ownerOpenId)
1456
+ getOwner: () => auth.current.ownerOpenId
1627
1457
  });
1628
1458
  const unregisterTool = ctx.tools.register(notifyTool);
1629
1459
  ctx.effect(() => () => unregisterTool(), `${PLUGIN_LABEL}: notify tool`);
@@ -1636,11 +1466,7 @@ function apply(ctx, config) {
1636
1466
  webServer,
1637
1467
  ...connection === void 0 ? {} : { connection },
1638
1468
  auth,
1639
- sessions,
1640
- store,
1641
- getConfig: () => current,
1642
- logger: ctx.logger,
1643
- onAuthChanged: (snapshot) => bridge.sync(snapshot)
1469
+ logger: ctx.logger
1644
1470
  });
1645
1471
  }
1646
1472
  ctx.effect(() => () => disposeRoutes?.(), `${PLUGIN_LABEL}: routes`);
@@ -1651,21 +1477,25 @@ function apply(ctx, config) {
1651
1477
  ctx.logger.warn(`[${PLUGIN_LABEL}] auth check failed: ${describeError(error)}`);
1652
1478
  });
1653
1479
  };
1654
- if (current.authCheckOnStartup) runCheck();
1480
+ runCheck();
1481
+ ctx.on("domain/changed", (change) => {
1482
+ if (!selection.invalidate(change)) return;
1483
+ bridge.stop();
1484
+ reconcile();
1485
+ });
1655
1486
  ctx.on("loader/volatile-update", () => {
1656
1487
  try {
1657
- const next = readConfig(config);
1658
- const cliChanged = next.larkCli !== current.larkCli;
1659
- current = next;
1660
- if (cliChanged) cli = new LarkCli(next.larkCli);
1661
- ctx.logger.info(`[${PLUGIN_LABEL}] config updated: profile=${current.profile}`);
1488
+ current = readConfig(config);
1489
+ selection.reset();
1490
+ bridge.stop();
1491
+ reconcile();
1492
+ ctx.logger.info(`[${PLUGIN_LABEL}] config updated`);
1662
1493
  runCheck();
1663
1494
  } catch (error) {
1664
1495
  ctx.logger.warn(`[${PLUGIN_LABEL}] config update ignored: ${String(error)}`);
1665
1496
  }
1666
1497
  });
1667
1498
  ctx.effect(() => () => bridge.stop(), `${PLUGIN_LABEL}: event bridge`);
1668
- ctx.effect(() => () => auth.cancelLogin(), `${PLUGIN_LABEL}: login`);
1669
1499
  }
1670
1500
  //#endregion
1671
1501
  export { Config, apply, inject, name };