larkmate 0.1.23 → 0.1.25

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 CHANGED
@@ -59,8 +59,10 @@ npx --registry=https://registry.npmjs.org/ skills add NWYLZW/larkmate --skill la
59
59
  - [x] 分页读取指定会话的历史消息
60
60
  - [x] 在已扫描的历史消息中按关键词、发送者和时间筛选
61
61
  - [x] 按会话、发送者和时间范围分页导出消息到本地文件
62
- - [x] 读取文本、富文本及部分图片和文件元数据
63
- - [x] 发送文本、引用回复、@ 用户或机器人、发送文件
62
+ - [x] 读取文本、链接、提及及部分图片和文件元数据
63
+ - [ ] 完整解析富文本中的图片、表情包和互动卡片
64
+ - [x] 发送文本、链接和带标题的消息,引用回复、@ 用户或所有人
65
+ - [x] 发送文件
64
66
  - [x] 全局搜索消息(分页)
65
67
  - [x] 编辑文本消息或撤回消息
66
68
  - [x] 转发或收藏消息
package/bin/larkmate.js CHANGED
@@ -24,8 +24,9 @@ import { createApiKey } from '../src/access-policy.js';
24
24
  import { startApiService } from '../src/api-service.js';
25
25
 
26
26
  const defaultTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
27
+ const { version } = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
27
28
  const program = new Command();
28
- program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.22');
29
+ program.name('larkmate').description('Operate Feishu as the logged-in user.').version(version);
29
30
  program.option('--credentials-file <path>', 'read LarkMate credentials.json');
30
31
  program.option('--broker <path>', 'use a restricted local broker socket (or LARKMATE_BROKER)');
31
32
  program.option('--broker-token-file <path>', 'read the agent token (or LARKMATE_BROKER_TOKEN_FILE)');
@@ -454,7 +455,7 @@ program.command('messages-export').description('Export a conversation to a local
454
455
  program.command('send').description('Send text once as the user; delivery remains unconfirmed.')
455
456
  .requiredOption('--chat <id>', 'numeric chat ID')
456
457
  .requiredOption('--text <text>', 'message text')
457
- .option('--mention <id:name>', 'mention a numeric user or bot ID; repeatable', collect, [])
458
+ .option('--mention <id:name>', 'mention a numeric user or bot ID, or all for everyone; repeatable', collect, [])
458
459
  .option('--reply-to <id>', 'reply to a numeric message ID')
459
460
  .option('--reply-root <id>', 'root ID when replying to an existing reply')
460
461
  .action(async options => {
@@ -466,6 +467,19 @@ program.command('send').description('Send text once as the user; delivery remain
466
467
  output(await (await client()).send({ chatId: options.chat, text: options.text, mentions, replyTo: options.replyTo, replyRoot: options.replyRoot }));
467
468
  });
468
469
 
470
+ program.command('send-rich').description('Send structured text, links and mentions from JSON.')
471
+ .requiredOption('--chat <id>', 'numeric chat ID')
472
+ .requiredOption('--json <path>', 'JSON file or - for standard input')
473
+ .option('--reply-to <id>', 'reply to a numeric message ID')
474
+ .option('--reply-root <id>', 'root ID when replying to an existing reply')
475
+ .action(async options => {
476
+ const input = await readJson(options.json);
477
+ if (!input || typeof input !== 'object' || Array.isArray(input) || Object.keys(input).some(k => !['segments', 'title'].includes(k))) {
478
+ throw new FeishuError('INVALID_ARGUMENT', 'JSON must contain segments and an optional title.');
479
+ }
480
+ output(await (await client()).sendRich({ chatId: options.chat, segments: input.segments, title: input.title, replyTo: options.replyTo, replyRoot: options.replyRoot }));
481
+ });
482
+
469
483
  program.command('send-file').description('Upload and send a local file as the user.')
470
484
  .requiredOption('--chat <id>', 'numeric chat ID')
471
485
  .requiredOption('--file <path>', 'local file path')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "larkmate",
3
- "version": "0.1.23",
3
+ "version": "0.1.25",
4
4
  "description": "A small, user-identity Feishu CLI with a modular gateway client",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
@@ -22,6 +22,8 @@ larkmate messages-export --chat "$CHAT_ID" --sender "$MEMBER_ID" --after 1700000
22
22
 
23
23
  `chats` 默认读取收件箱的一页,不是全部历史会话。`--type`、`--state` 只过滤当前页,`--scope done` 查询已完成分组;`boxes` 用 `--parent` 单独读取,`nextCursor` 用于翻页。`history` 每页最多 100 个位置,`--pages` 最多 100 页;`--query`、`--sender`、`--after`、`--before` 只过滤已扫描的位置,不是全量搜索。`omittedPositions` 是没有返回的位置数,不是消息数;部分消息类型可能没有可解析正文。
24
24
 
25
+ 历史消息的 `segments` 保留文本、提及用户和链接,`title` 是带标题消息的标题;`textIncomplete` 表示正文未能完整解析,汇总中的 `incompleteText` 是此类消息数。
26
+
25
27
  `search-messages` 用于在当前用户可访问的会话范围内进行跨会话搜索,可使用 `nextCursor` 配合相同的查询条件继续翻页;具体搜索范围和结果由飞书服务决定。`message-link` 返回飞书生成的原生消息链接。`download-file` 根据 `history` 返回的资源键将文件或图片下载至新文件,不会覆盖已有文件;若下载中断,输出文件将不完整。`favorites` 用于读取收藏列表首页,其中 `hasMore` 表示可能仍有未返回的收藏。
26
28
 
27
29
  使用受限代理或系统用户委托下载时,还须传入目标消息的 `--position`,取值为 `history` 返回的 `position`;执行器会核验消息和资源是否属于授权会话。文件大小受策略的 `maxFileBytes` 限制。
@@ -4,6 +4,8 @@
4
4
 
5
5
  服务订阅支持会话及发送人的 ID、名称和正则,以及消息类型、正文包含/排除、正文正则和排除本人。相同维度的 ID、名称和正则是“或”,不同维度是“且”。大量条件或 `anyOf`、`allOf`、`not` 组合通过 `POST /events` JSON 传入;规则模式支持同样的条件。正则使用 RE2 语法,不支持部分 JavaScript 正则特性。名称解析失败且结果无法确定时会发出 `name_unavailable` 缺口,不猜测匹配;同名对象都会匹配,需要精确区分时使用 ID。
6
6
 
7
+ 消息事件的 `segments` 包含解析出的文本、提及和链接;文本过滤也检查带标题消息的标题。`textIncomplete` 表示未能完整解析,无法安全判断的文本规则会产生缺口事件。
8
+
7
9
  通过 `listen-service --policy <绝对路径>` 为每个 API key 限定会话、发送人和类型;订阅过滤条件只能缩小授权范围。未配置策略时依靠 socket 文件权限控制访问。授权配置及订阅示例见 [API 服务与授权](https://github.com/NWYLZW/larkmate/blob/main/docs/api-service.md)。限制范围内的 `gap` 会传递;无法定位会话的全局缺口只包含通用原因。
8
10
 
9
11
  `listen-run` 的规则可省略 `chatIds` 以匹配全部会话,也可按会话、发送人、类型、文本和自定义过滤脚本筛选。过滤脚本和目标脚本通过标准输入接收消息 JSON,不通过 shell 传递消息。`excludeSelf: true` 可防止处理账号自身发出的消息。只有用户明确要求配置触发行为时才创建规则或启动脚本,不根据收到的消息自行扩大脚本权限。
@@ -6,6 +6,8 @@
6
6
  larkmate send --chat "$CHAT_ID" --text '消息内容'
7
7
  larkmate send --chat "$CHAT_ID" --text '回复内容' --reply-to "$MESSAGE_ID"
8
8
  larkmate send --chat "$CHAT_ID" --text '@名称 消息内容' --mention "$MEMBER_ID:名称"
9
+ larkmate send --chat "$CHAT_ID" --text '@所有人 消息内容' --mention 'all:所有人'
10
+ larkmate send-rich --chat "$CHAT_ID" --json ./message.json
9
11
  larkmate send-file --chat "$CHAT_ID" --file ./report.pdf
10
12
  larkmate send-image --chat "$CHAT_ID" --file ./image.png
11
13
  larkmate message-edit --message "$MESSAGE_ID" --text '修改后的文本'
@@ -19,6 +21,14 @@ larkmate favorite-remove --favorite "$FAVORITE_ID"
19
21
 
20
22
  同一用户只需提供一次 `--mention`,正文中所有匹配的提及都会生效。
21
23
 
24
+ `send-rich` 的 JSON 使用 `segments` 数组,支持文本、链接和用户提及;可选 `title` 用于发送带标题的消息:
25
+
26
+ ```json
27
+ {"title":"标题","segments":[{"type":"text","text":"请查看 "},{"type":"link","text":"参考链接","url":"https://example.com/"},{"type":"text","text":" "},{"type":"mention","text":"@名称","userId":"123"}]}
28
+ ```
29
+
30
+ `userId` 使用飞书网页数字 ID;`all` 表示 @所有人,受群权限限制。代理、系统用户委托或 API key 需允许 `send-rich`;在现有策略中,带提及或引用的发送还需要全部会话授权。
31
+
22
32
  文件须为非空普通文件且不超过 100 MiB。`accepted` 表示服务器返回相应 ID,`submitted_unconfirmed` 表示未可靠确认接收;不确定时先检查实际状态再决定是否重试。
23
33
 
24
34
  使用受限代理或系统用户委托发送文件或图片时,需要相应命令和目标会话的授权;文件由 Agent 自身读取,且还受策略 `maxFileBytes` 限制。
@@ -51,7 +51,7 @@ const routes = {
51
51
  'message-forward': ['client', 'forwardMessage', 'allChats'], 'message-recall': ['client', 'recallMessage', 'allChats'],
52
52
  'favorite-add': ['client', 'favoriteMessage', 'allChats'], 'favorite-remove': ['client', 'removeFavorite', 'allChats'],
53
53
  'reaction-add': ['client', 'reaction', 'reactionAdd'], 'reaction-remove': ['client', 'reaction', 'reactionRemove'],
54
- send: ['client', 'send', 'send'],
54
+ send: ['client', 'send', 'send'], 'send-rich': ['client', 'sendRich', 'send'],
55
55
  pin: ['controls', 'pin', 'chatTrue'], unpin: ['controls', 'pin', 'chatFalse'],
56
56
  mark: ['controls', 'mark', 'chatTrue'], unmark: ['controls', 'mark', 'chatFalse'],
57
57
  mute: ['controls', 'setMute', 'chatTrue'], unmute: ['controls', 'setMute', 'chatFalse'],
@@ -64,7 +64,7 @@ const routes = {
64
64
  'group-avatar-set': ['files', 'upload', 'file'],
65
65
  'download-file': ['files', 'download', 'file'],
66
66
  };
67
- const writes = new Set(['send', 'pin', 'unpin', 'mark', 'unmark', 'mute', 'unmute', 'done', 'inbox', 'box', 'unbox', 'read', 'unread', 'chat-preferences-set', 'chat-clear-history', 'contact-alias-set', 'contact-note-set', 'group-nickname-set', 'group-avatar-set',
67
+ const writes = new Set(['send', 'send-rich', 'pin', 'unpin', 'mark', 'unmark', 'mute', 'unmute', 'done', 'inbox', 'box', 'unbox', 'read', 'unread', 'chat-preferences-set', 'chat-clear-history', 'contact-alias-set', 'contact-note-set', 'group-nickname-set', 'group-avatar-set',
68
68
  'label-create', 'label-rename', 'label-delete', 'label-add', 'label-remove', 'chat-open', 'group-create', 'group-invite',
69
69
  'group-update', 'group-dissolve', 'group-bot-protection', 'group-settings-set', 'group-admin-add', 'group-admin-remove', 'group-remove', 'group-leave', 'group-owner', 'group-post-set', 'group-link', 'group-request-approve', 'group-request-reject', 'message-edit', 'message-forward', 'message-recall', 'favorite-add',
70
70
  'favorite-remove', 'reaction-add', 'reaction-remove', 'minutes-request-access', 'send-file', 'send-image', 'sidebar-set', 'task-create', 'task-update', 'task-complete', 'task-reopen', 'task-delete', 'event-create', 'event-update', 'event-delete', 'event-share', 'event-reply', 'calendar-create', 'calendar-update', 'calendar-delete', 'calendar-subscribe', 'calendar-unsubscribe']);
@@ -159,7 +159,7 @@ export function authorize(policy, request) {
159
159
  }
160
160
  if (scope === 'chatObject' || scope === 'send') {
161
161
  if (args.length !== 1 || !object(args[0]) || !chatAllowed(args[0].chatId)) denied();
162
- const keys = scope === 'send' ? ['chatId', 'text', 'mentions', 'replyTo', 'replyRoot']
162
+ const keys = scope === 'send' ? (method === 'sendRich' ? ['chatId', 'segments', 'title', 'replyTo', 'replyRoot'] : ['chatId', 'text', 'mentions', 'replyTo', 'replyRoot'])
163
163
  : method === 'historyPages' ? ['chatId', 'limit', 'start', 'pages', 'query', 'sender', 'after', 'before']
164
164
  : method === 'members' ? ['chatId', 'cursor', 'offset', 'limit']
165
165
  : method === 'updateGroup' ? ['chatId', 'name', 'description']
@@ -178,7 +178,8 @@ export function authorize(policy, request) {
178
178
  : method === 'history' ? ['chatId','cursor','count'] : ['chatId', 'botId'];
179
179
  if (!only(args[0], keys)) denied();
180
180
  // A reply ID may refer to another chat, and mentions can notify additional users.
181
- if (scope === 'send' && !policy.allowAllChats && (args[0].replyTo || args[0].replyRoot || (args[0].mentions?.length ?? 0) !== 0)) denied();
181
+ if (scope === 'send' && method === 'sendRich' && !Array.isArray(args[0].segments)) denied();
182
+ if (scope === 'send' && !policy.allowAllChats && (args[0].replyTo || args[0].replyRoot || (args[0].mentions?.length ?? 0) !== 0 || (args[0].segments?.some(segment => segment?.type === 'mention') ?? false))) denied();
182
183
  }
183
184
  if (scope === 'minute') {
184
185
  if (args.length < 1 || args.length > 2 || typeof args[0] !== 'string') denied();
package/src/client.js CHANGED
@@ -4,6 +4,7 @@ import { shortId } from './gateway.js';
4
4
  import { downloadFile } from './download.js';
5
5
  import { randomUUID } from 'node:crypto';
6
6
  import { open } from 'node:fs/promises';
7
+ import { buildRichText, readRichText } from './rich-text.js';
7
8
 
8
9
  function ids(values, label) {
9
10
  if (!Array.isArray(values)) throw new FeishuError('INVALID_ARGUMENT', `${label} must be a list.`);
@@ -300,12 +301,13 @@ export class LarkMateClient {
300
301
  catch { throw new FeishuError('INVALID_RESPONSE', 'The history page was unreadable.'); }
301
302
  const requested = new Set(positions);
302
303
  const items = Object.entries(data.messages || {}).filter(([position]) => requested.has(Number(position))).map(([position, message]) => {
303
- let text = null;
304
+ let text = null, title = null, segments = [], textIncomplete = ![2, 4].includes(message.type) || !message.content?.length;
304
305
  if (message.content?.length && (message.type === 4 || message.type === 2)) {
305
306
  try {
306
307
  const content = this.gateway.decode(message.type === 4 ? 'TextContent' : 'PostContent', message.content);
307
- text = content.richText?.innerText || content.text || null;
308
- } catch { /* Keep unsupported or undecodable content explicitly unknown. */ }
308
+ ({ text, segments, textIncomplete } = readRichText(this.gateway, content.richText, content.text));
309
+ if (message.type === 2) title = content.title || null;
310
+ } catch { textIncomplete = true; }
309
311
  }
310
312
  let resource = null;
311
313
  if (message.content?.length && (message.type === 3 || message.type === 5)) {
@@ -317,7 +319,7 @@ export class LarkMateClient {
317
319
  } catch { /* Leave unknown resources unparsed. */ }
318
320
  }
319
321
  return { id: String(message.id || ''), position: Number(position), rootId: message.rootId || null, parentId: message.parentId || null,
320
- senderId: message.fromId || '', type: message.type, text,
322
+ senderId: message.fromId || '', type: message.type, title, text, segments, textIncomplete,
321
323
  createTime: Object.hasOwn(message, 'createTime') ? String(message.createTime) : null, resource };
322
324
  }).sort((a, b) => a.position - b.position);
323
325
  return { items, requestedPositions: positions.length,
@@ -333,14 +335,15 @@ export class LarkMateClient {
333
335
  if (value != null && (!Number.isSafeInteger(value) || value < 0)) throw new FeishuError('INVALID_ARGUMENT', label + ' must be a Unix timestamp in seconds.');
334
336
  }
335
337
  if (after != null && before != null && after > before) throw new FeishuError('INVALID_ARGUMENT', 'after must not be later than before.');
336
- let next = start, pageLimit = limit, nextLimit = null, scanned = 0, omittedPositions = 0, missingTimestamps = 0, items = [];
338
+ let next = start, pageLimit = limit, nextLimit = null, scanned = 0, omittedPositions = 0, missingTimestamps = 0, incompleteText = 0, items = [];
337
339
  for (let i = 0; i < pages; i++) {
338
340
  const page = await this.history({ chatId, limit: pageLimit, start: next });
339
341
  scanned += page.requestedPositions || 0;
340
342
  omittedPositions += page.omittedPositions || 0;
341
343
  items.push(...page.items.filter(item => {
342
344
  if (sender && item.senderId !== sender) return false;
343
- if (query && !(item.text || '').includes(query)) return false;
345
+ if (item.textIncomplete) incompleteText++;
346
+ if (query && !(item.text || '').includes(query) && !(item.title || '').includes(query)) return false;
344
347
  if (after != null || before != null) {
345
348
  if (item.createTime == null) { missingTimestamps++; return false; }
346
349
  const time = Number(item.createTime);
@@ -355,7 +358,7 @@ export class LarkMateClient {
355
358
  if (next == null) break;
356
359
  }
357
360
  items.sort((a, b) => a.position - b.position);
358
- return { items, scannedPositions: scanned, omittedPositions, missingTimestamps, nextStart: next ?? null, nextLimit, filterScope: 'scanned_positions_only' };
361
+ return { items, scannedPositions: scanned, omittedPositions, missingTimestamps, incompleteText, nextStart: next ?? null, nextLimit, filterScope: 'scanned_positions_only' };
359
362
  }
360
363
 
361
364
  async sendFile({ chatId, path }) {
@@ -495,7 +498,7 @@ export class LarkMateClient {
495
498
  let text = null;
496
499
  if (m.content?.length && (m.type === 4 || m.type === 2)) {
497
500
  const body = this.gateway.decode(m.type === 4 ? 'TextContent' : 'PostContent', m.content);
498
- text = body.richText?.innerText || body.text || null;
501
+ text = readRichText(this.gateway, body.richText, body.text).text;
499
502
  }
500
503
  message = { id: m.id || null, chatId: m.chatId || null, senderId: m.fromId || null, type: m.type, text };
501
504
  } catch { /* Keep the favorite ID if its content type is not understood. */ }
@@ -518,7 +521,7 @@ export class LarkMateClient {
518
521
  const dictionary = {};
519
522
  const markers = new Map();
520
523
  for (const mention of mentions) {
521
- requireNumericId(mention.id, 'mention ID');
524
+ if (mention.id !== 'all') requireNumericId(mention.id, 'mention ID');
522
525
  const marker = `@${requireText(mention.name, 'mention name')}`;
523
526
  if (markers.has(marker) && markers.get(marker) !== mention.id) throw new FeishuError('INVALID_ARGUMENT', 'A mention name cannot identify multiple users.');
524
527
  markers.set(marker, mention.id);
@@ -557,6 +560,23 @@ export class LarkMateClient {
557
560
  return { status: 'submitted_unconfirmed', chatId, cid, requestId: response.requestId };
558
561
  }
559
562
 
563
+ async sendRich({ chatId, segments, title, replyTo, replyRoot }) {
564
+ requireInt64Id(chatId, 'chat ID');
565
+ if (title != null) requireText(title, 'title');
566
+ if (replyTo) requireInt64Id(replyTo, 'reply message ID');
567
+ if (replyRoot) requireInt64Id(replyRoot, 'reply root ID');
568
+ if (replyRoot && !replyTo) throw new FeishuError('INVALID_ARGUMENT', 'reply-root requires reply-to.');
569
+ await this.gateway.authenticate();
570
+ const richText = buildRichText(this.gateway, segments);
571
+ const cid = shortId();
572
+ const response = await this.gateway.call(5, 'PutMessageRequest', {
573
+ type: title == null ? 4 : 2, chatId, cid, isNotified: true, version: 1,
574
+ ...(replyTo ? { parentId: replyTo, rootId: replyRoot || replyTo } : {}),
575
+ content: { ...(title == null ? {} : { title }), richText },
576
+ }, { version: '8.5.0', mutating: true, operation: 'send-rich' });
577
+ return { status: 'submitted_unconfirmed', chatId, cid, requestId: response.requestId };
578
+ }
579
+
560
580
  async resolveMembers(memberIds) {
561
581
  if (!memberIds.length) return [];
562
582
  const response = await this.gateway.call(46, 'PullChattersByIdsRequest', {
@@ -1,6 +1,22 @@
1
1
  import { open } from 'node:fs/promises';
2
2
  import { FeishuError } from './errors.js';
3
3
 
4
+ function messageBody(item) {
5
+ let body = item.text ?? (item.resource ? JSON.stringify(item.resource) : `[无法解析的消息类型 ${item.type}]`);
6
+ if (!item.textIncomplete && item.segments?.some(segment => segment.type === 'link' && segment.url)) {
7
+ body = item.segments.map(segment => {
8
+ if (segment.type !== 'link' || !segment.url) return segment.text || '';
9
+ try {
10
+ const url = new URL(segment.url);
11
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) return segment.text || '';
12
+ const text = (segment.text || segment.url).replace(/[\\\[\]]/g, '\\$&');
13
+ return `[${text}](${segment.url.replace(/\)/g, '%29').replace(/\(/g, '%28').replace(/\s/g, '%20')})`;
14
+ } catch { return segment.text || ''; }
15
+ }).join('');
16
+ }
17
+ return item.title ? `${item.title}\n${body}` : body;
18
+ }
19
+
4
20
  // Stream newest pages first, so even very large conversations need only one page in memory.
5
21
  export async function exportMessages(client, { chatId, output, format = 'markdown', sender, query, after, before, start, maxPages, limit = 100 } = {}) {
6
22
  if (typeof output !== 'string' || !output) throw new FeishuError('INVALID_ARGUMENT', 'An output path is required.');
@@ -15,7 +31,7 @@ export async function exportMessages(client, { chatId, output, format = 'markdow
15
31
  try { handle = await open(output, 'wx', 0o600); }
16
32
  catch (error) { throw new FeishuError('EXPORT_WRITE_FAILED', error.code === 'EEXIST' ? 'Output file already exists; choose a new path.' : 'Could not create the output file.'); }
17
33
  const metadata = { chatId, sender: sender || null, query: query || null, after: after ?? null, before: before ?? null, start: start ?? null, order: 'newest_first' };
18
- let next = start, pages = 0, count = 0, scannedPositions = 0, omittedPositions = 0, missingTimestamps = 0;
34
+ let next = start, pages = 0, count = 0, scannedPositions = 0, omittedPositions = 0, missingTimestamps = 0, incompleteText = 0;
19
35
  try {
20
36
  await handle.writeFile(format === 'jsonl' ? `${JSON.stringify({ kind: 'metadata', ...metadata })}\n` : `# 消息导出\n\n筛选条件:\`${JSON.stringify(metadata)}\`\n\n`);
21
37
  do {
@@ -24,6 +40,7 @@ export async function exportMessages(client, { chatId, output, format = 'markdow
24
40
  scannedPositions += page.scannedPositions;
25
41
  omittedPositions += page.omittedPositions;
26
42
  missingTimestamps += page.missingTimestamps;
43
+ incompleteText += page.incompleteText || 0;
27
44
  const chunks = [];
28
45
  for (const item of page.items.reverse()) {
29
46
  count++;
@@ -31,7 +48,7 @@ export async function exportMessages(client, { chatId, output, format = 'markdow
31
48
  else {
32
49
  const timestamp = item.createTime != null && Number.isFinite(Number(item.createTime)) && Math.abs(Number(item.createTime)) < 8640000000000
33
50
  ? new Date(Number(item.createTime) * 1000).toISOString() : '时间未知';
34
- const body = item.text ?? (item.resource ? JSON.stringify(item.resource) : `[无法解析的消息类型 ${item.type}]`);
51
+ const body = messageBody(item);
35
52
  chunks.push(`## ${timestamp} · 发送者 ${item.senderId || '未知'}\n\n消息 ID:${item.id || '未知'} · 位置:${item.position}\n\n${String(body).split('\n').map(line => `> ${line}`).join('\n')}\n\n`);
36
53
  }
37
54
  }
@@ -39,7 +56,7 @@ export async function exportMessages(client, { chatId, output, format = 'markdow
39
56
  next = page.nextStart;
40
57
  limit = page.nextLimit;
41
58
  } while (next != null && (maxPages == null || pages < maxPages));
42
- const summary = { output, format, count, pages, scannedPositions, omittedPositions, missingTimestamps, reachedBeginning: next == null, nextStart: next ?? null, nextLimit: limit ?? null };
59
+ const summary = { output, format, count, pages, scannedPositions, omittedPositions, missingTimestamps, incompleteText, reachedBeginning: next == null, nextStart: next ?? null, nextLimit: limit ?? null };
43
60
  await handle.writeFile(format === 'jsonl' ? `${JSON.stringify({ kind: 'summary', ...summary })}\n` : `---\n\n导出统计:\`${JSON.stringify(summary)}\`\n`);
44
61
  return summary;
45
62
  } catch (error) {
@@ -48,16 +48,16 @@ export function filterMatches(f,event,selfId) {
48
48
  : f.chatNames.includes(event.chatName)||f.chatRegex.some(r=>typeof event.chatName==='string'&&r.test(event.chatName));
49
49
  const senderMatch=f.senderIds.includes(event.senderId) ? true : (f.senderNames.length||f.senderRegex.length) && !event.senderName ? null
50
50
  : f.senderNames.includes(event.senderName)||f.senderRegex.some(r=>typeof event.senderName==='string'&&r.test(event.senderName));
51
- const text=typeof event.text==='string'?event.text:'';
51
+ const texts=[event.text,event.title].filter(value=>typeof value==='string');
52
52
  const and=values=>values.includes(false)?false:values.includes(null)?null:true;
53
53
  const or=values=>values.includes(true)?true:values.includes(null)?null:false;
54
54
  const not=value=>value===null?null:!value;
55
55
  const incomplete=event.textIncomplete===true;
56
56
  return and([!chatSpecified?true:chatMatch,!senderSpecified?true:senderMatch,!f.types.length||f.types.includes(event.type),
57
57
  !f.excludeSelf||!!(selfId&&typeof event.senderId==='string'&&event.senderId!==selfId),
58
- !textSpecified?true:incomplete?null:f.contains.some(x=>text.includes(x))||f.textRegex.some(r=>r.test(text)),
59
- !f.excludeContains.length?true:incomplete?null:!f.excludeContains.some(x=>text.includes(x)),
60
- !f.excludeTextRegex.length?true:incomplete?null:!f.excludeTextRegex.some(r=>r.test(text)),
58
+ !textSpecified?true:incomplete?null:f.contains.some(x=>texts.some(text=>text.includes(x)))||f.textRegex.some(r=>texts.some(text=>r.test(text))),
59
+ !f.excludeContains.length?true:incomplete?null:!f.excludeContains.some(x=>texts.some(text=>text.includes(x))),
60
+ !f.excludeTextRegex.length?true:incomplete?null:!f.excludeTextRegex.some(r=>texts.some(text=>r.test(text))),
61
61
  !f.anyOf.length?true:or(f.anyOf.map(x=>filterMatches(x,event,selfId))),
62
62
  and(f.allOf.map(x=>filterMatches(x,event,selfId))),f.not?not(filterMatches(f.not,event,selfId)):true]);
63
63
  }
package/src/listen.js CHANGED
@@ -4,6 +4,7 @@ import { once } from 'node:events';
4
4
  import { setTimeout as delay } from 'node:timers/promises';
5
5
  import { FeishuError, requireInt64Id } from './errors.js';
6
6
  import { LarkMateClient } from './client.js';
7
+ import { readRichText } from './rich-text.js';
7
8
 
8
9
  const MAX_FRAME = 8 * 1024 * 1024;
9
10
  const asString = x => x == null ? null : String(x);
@@ -65,26 +66,16 @@ export function decodePush(gateway, bytes) {
65
66
  }
66
67
 
67
68
  function formatMessage(gateway, m) {
68
- let text = null, textIncomplete = false;
69
+ let text = null, title = null, segments = [], textIncomplete = ![2, 4].includes(m.type) || !m.content?.length;
69
70
  if (m.content?.length && [2, 4].includes(m.type)) {
70
71
  try {
71
72
  const c = gateway.decode(m.type === 4 ? 'TextContent' : 'PostContent', m.content);
72
- text = c.richText?.innerText || c.text || null;
73
- if (!text && c.richText?.elementIds?.length) {
74
- let pieces = [];
75
- for (const id of c.richText.elementIds) {
76
- const element = c.richText.elements?.dictionary?.[id];
77
- if (element && [1,5].includes(element.tag)) {
78
- const property = gateway.decode(element.tag === 1 ? 'TextProperty' : 'AtProperty', element.property);
79
- if (typeof property.content === 'string') pieces.push(property.content); else textIncomplete = true;
80
- } else textIncomplete = true;
81
- }
82
- text = pieces.join('') || null;
83
- }
73
+ ({ text, segments, textIncomplete } = readRichText(gateway, c.richText, c.text));
74
+ if (m.type === 2) title = c.title || null;
84
75
  } catch { textIncomplete = true; }
85
76
  }
86
77
  return { kind:'message', id:asString(m.id), chatId:asString(m.chatId), senderId:asString(m.fromId), position:Number.isInteger(m.position)?m.position:null,
87
- type:m.type, text, textIncomplete, createTime:asString(m.createTime), rootId:asString(m.rootId), parentId:asString(m.parentId) };
78
+ type:m.type, title, text, segments, textIncomplete, createTime:asString(m.createTime), rootId:asString(m.rootId), parentId:asString(m.parentId) };
88
79
  }
89
80
 
90
81
  export async function listen({ gateway, chatIds = [], output = process.stdout, log = process.stderr, signal, WebSocketImpl = WebSocket }) {
@@ -0,0 +1,77 @@
1
+ import { FeishuError, requireInt64Id, requireText } from './errors.js';
2
+ import { shortId } from './gateway.js';
3
+
4
+ const ownKeys = (value, allowed) => value && typeof value === 'object' && !Array.isArray(value)
5
+ && Object.keys(value).every(key => allowed.includes(key));
6
+
7
+ // RichText can contain nested paragraphs, and innerText can be empty even when
8
+ // the element dictionary contains readable text, mentions, or links.
9
+ export function readRichText(gateway, richText, fallback = null) {
10
+ const ids = richText?.elementIds || [];
11
+ const dictionary = richText?.elements?.dictionary || {};
12
+ const segments = [];
13
+ let incomplete = false, visited = 0;
14
+ const active = new Set();
15
+ function visit(id) {
16
+ if (++visited > 10000 || active.has(id)) { incomplete = true; return; }
17
+ const element = dictionary[id];
18
+ if (!element) { incomplete = true; return; }
19
+ active.add(id);
20
+ try {
21
+ if (element.tag === 3) {
22
+ const start = segments.length;
23
+ for (const child of element.childIds || []) visit(child);
24
+ if (segments.length > start && !segments.at(-1).text?.endsWith('\n')) segments.push({ type: 'text', text: '\n' });
25
+ } else if ([1, 5, 6].includes(element.tag)) {
26
+ const type = element.tag === 1 ? 'TextProperty' : element.tag === 5 ? 'AtProperty' : 'AnchorProperty';
27
+ const property = gateway.decode(type, element.property || new Uint8Array());
28
+ if (element.tag !== 6 && !Object.hasOwn(property, 'content')) { incomplete = true; return; }
29
+ if (element.tag === 6 && !property.href) incomplete = true;
30
+ const text = element.tag === 6 ? (property.textContent || property.content || property.href) : property.content;
31
+ if (typeof text !== 'string') { incomplete = true; return; }
32
+ if (element.tag === 1) segments.push({ type: 'text', text });
33
+ else if (element.tag === 5) segments.push({ type: 'mention', text, userId: property.userId || null });
34
+ else segments.push({ type: 'link', text, url: property.href || null });
35
+ } else {
36
+ incomplete = true;
37
+ for (const child of element.childIds || []) visit(child);
38
+ }
39
+ } catch { incomplete = true; }
40
+ finally { active.delete(id); }
41
+ }
42
+ for (const id of ids) visit(id);
43
+ let text = segments.map(s => s.text).join('');
44
+ if (text.endsWith('\n') && ids.length && dictionary[ids.at(-1)]?.tag === 3) text = text.slice(0, -1);
45
+ const original = richText?.innerText || fallback || null;
46
+ if (!ids.length) return { text: original, segments: [], textIncomplete: original == null };
47
+ // Preserve server text when unsupported elements are present, but never
48
+ // claim it is complete; filters use this flag to avoid unsafe decisions.
49
+ if (incomplete && original) text = original;
50
+ return { text: text || original, segments, textIncomplete: incomplete };
51
+ }
52
+
53
+ export function buildRichText(gateway, parts) {
54
+ if (!Array.isArray(parts) || parts.length === 0 || parts.length > 1000) throw new FeishuError('INVALID_ARGUMENT', 'segments must contain 1 to 1000 items.');
55
+ const elementIds = [], atIds = [], anchorIds = [], dictionary = {}, texts = [];
56
+ for (const part of parts) {
57
+ if (!ownKeys(part, ['type', 'text', 'userId', 'url'])) throw new FeishuError('INVALID_ARGUMENT', 'Invalid rich text segment.');
58
+ const text = part.text;
59
+ if (typeof text !== 'string' || text.length === 0) throw new FeishuError('INVALID_ARGUMENT', 'segment text must not be empty.');
60
+ const id = shortId();
61
+ let tag, property;
62
+ if (part.type === 'text' && ownKeys(part, ['type', 'text'])) {
63
+ tag = 1; property = gateway.encode('TextProperty', { content: text });
64
+ } else if (part.type === 'mention' && ownKeys(part, ['type', 'text', 'userId'])) {
65
+ requireText(text, 'mention text');
66
+ if (part.userId !== 'all') requireInt64Id(part.userId, 'mention user ID');
67
+ tag = 5; property = gateway.encode('AtProperty', { userId: part.userId, content: text }); atIds.push(id);
68
+ } else if (part.type === 'link' && ownKeys(part, ['type', 'text', 'url'])) {
69
+ requireText(text, 'link text');
70
+ let url; try { url = new URL(part.url); } catch { throw new FeishuError('INVALID_ARGUMENT', 'A link must have an HTTP or HTTPS URL.'); }
71
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new FeishuError('INVALID_ARGUMENT', 'A link must have an HTTP or HTTPS URL without credentials.');
72
+ tag = 6; property = gateway.encode('AnchorProperty', { href: part.url, content: text, textContent: text }); anchorIds.push(id);
73
+ } else throw new FeishuError('INVALID_ARGUMENT', 'Unsupported rich text segment.');
74
+ elementIds.push(id); dictionary[id] = { tag, property }; texts.push(text);
75
+ }
76
+ return { elementIds, innerText: texts.join(''), elements: { dictionary }, atIds, anchorIds };
77
+ }