larkmate 0.1.14 → 0.1.15

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
@@ -35,11 +35,16 @@ npx --registry=https://registry.npmjs.org/ skills add NWYLZW/larkmate --skill la
35
35
  - [x] 查询、置顶和取消置顶会话
36
36
  - [x] 查询、标记和取消标记会话
37
37
  - [x] 标记已读或未读、设置免打扰
38
+ - [x] 设置 @所有人提醒和消息自动翻译
39
+ - [x] 查询和修改联系人备注名及纯文本备注描述
38
40
  - [x] 移入或移出已完成、会话收纳
39
41
  - [x] 按未读、免打扰、@我、单聊、群组等分组查询
40
42
  - [x] 配置侧边栏分组的显示、隐藏、顺序和展示规则
41
43
  - [x] 创建、重命名和删除标签,管理手动标签下的会话
42
44
  - [ ] 修改自动规则标签的会话成员
45
+ - [ ] 配置会话菜单和翻译助手的完整选项
46
+ - [x] 清空聊天记录
47
+ - [ ] 管理联系人备注图片及富文本
43
48
  - 消息
44
49
  - [x] 分页读取指定会话的历史消息
45
50
  - [x] 在已扫描的历史消息中按关键词、发送者和时间筛选
@@ -54,12 +59,14 @@ npx --registry=https://registry.npmjs.org/ skills add NWYLZW/larkmate --skill la
54
59
  - [x] 获取消息链接
55
60
  - 群聊
56
61
  - [x] 查询群信息、成员、管理员和入退群记录
62
+ - [x] 修改群名称、描述、头像和本人群昵称
57
63
  - [x] 邀请、移除成员,退出或解散群聊
58
64
  - [x] 管理员设置和群主转让
59
65
  - [x] 查询和调整入群审批、发言、邀请及其他群设置
60
66
  - [x] 创建群邀请链接,查询和处理入群申请
61
67
  - [x] 查询群公告、查询和设置机器人的移除限制
62
68
  - [ ] 修改群公告
69
+ - [ ] 管理群机器人及其配置
63
70
  - 飞书任务
64
71
  - [x] 查询任务中心与任务视图,按关键词搜索任务
65
72
  - [x] 新建、编辑、完成、重开和删除任务
package/bin/larkmate.js CHANGED
@@ -18,7 +18,7 @@ import { GroupManagement, groupSettingsSchema } from '../src/group-management.js
18
18
 
19
19
  const defaultTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
20
20
  const program = new Command();
21
- program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.14');
21
+ program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.15');
22
22
  program.option('--credentials-file <path>', 'read LarkMate credentials.json');
23
23
  program.option('--broker <path>', 'use a restricted local broker socket (or LARKMATE_BROKER)');
24
24
  program.option('--broker-token-file <path>', 'read the agent token (or LARKMATE_BROKER_TOKEN_FILE)');
@@ -278,6 +278,13 @@ for (const [command, enabled] of [['label-add', true], ['label-remove', false]])
278
278
  }
279
279
  program.command('chat-state').description('Read pin, flag, notification and read state for a conversation.')
280
280
  .requiredOption('--chat <id>', 'numeric chat ID').action(async o => output(await (await controls()).state(o.chat)));
281
+ program.command('chat-preferences').description('Read conversation notification and translation preferences.').requiredOption('--chat <id>')
282
+ .action(async o => output(await (await controls()).preferences(o.chat)));
283
+ program.command('chat-preferences-set').description('Update conversation notification and translation preferences.').requiredOption('--chat <id>')
284
+ .option('--mute-at-all <bool>', 'suppress @all notifications: true or false').option('--auto-translate <bool>', 'automatically translate messages: true or false')
285
+ .action(async o => { const parse = value => { if (value === undefined) return undefined; if (!['true','false'].includes(value)) throw new FeishuError('INVALID_ARGUMENT', 'Use true or false.'); return value === 'true'; }; output(await (await controls()).setPreference({ chatId:o.chat, muteAtAll:parse(o.muteAtAll), autoTranslate:parse(o.autoTranslate) })); });
286
+ program.command('chat-clear-history').description('Clear this conversation history through its current last message.').requiredOption('--chat <id>')
287
+ .action(async o => output(await (await client()).clearChatHistory({ chatId: o.chat })));
281
288
  for (const [command, method, enabled, description] of [
282
289
  ['pin', 'pin', true, 'Pin a conversation.'], ['unpin', 'pin', false, 'Unpin a conversation.'],
283
290
  ['mark', 'mark', true, 'Flag a conversation.'], ['unmark', 'mark', false, 'Remove a conversation flag.'],
@@ -476,6 +483,19 @@ program.command('group-update').description('Change a group name or description.
476
483
  chatId: options.chat, name: options.name, description: options.description,
477
484
  })));
478
485
 
486
+ program.command('contact-alias').description('Read your personal alias for a contact.').requiredOption('--user <id>')
487
+ .action(async o => output(await (await client()).contactAlias({ userId: o.user })));
488
+ program.command('contact-alias-set').description('Set or clear your personal alias for a contact.').requiredOption('--user <id>').requiredOption('--alias <text>', 'use an empty string to clear')
489
+ .action(async o => output(await (await client()).setContactAlias({ userId: o.user, alias: o.alias })));
490
+ program.command('contact-note').description('Read your personal note for a contact.').requiredOption('--user <id>')
491
+ .action(async o => output(await (await client()).contactNote({ userId: o.user })));
492
+ program.command('contact-note-set').description('Set or clear the plain-text note for a contact.').requiredOption('--user <id>').requiredOption('--description <text>', 'use an empty string to clear')
493
+ .action(async o => output(await (await client()).setContactNote({ userId: o.user, description: o.description })));
494
+ program.command('group-nickname-set').description('Set your nickname in a group.').requiredOption('--chat <id>').requiredOption('--nickname <text>', 'use an empty string to clear')
495
+ .action(async o => output(await (await client()).setGroupNickname({ chatId: o.chat, nickname: o.nickname })));
496
+ program.command('group-avatar-set').description('Set a group avatar from an image.').requiredOption('--chat <id>').requiredOption('--file <path>')
497
+ .action(async o => output(await (await client()).setGroupAvatar({ chatId: o.chat, path: o.file })));
498
+
479
499
  program.command('group-dissolve').description('Dissolve a group as its owner.')
480
500
  .requiredOption('--chat <id>', 'numeric group ID')
481
501
  .action(async options => output(await (await client()).dissolveGroup(options.chat)));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "larkmate",
3
- "version": "0.1.14",
3
+ "version": "0.1.15",
4
4
  "description": "A small, user-identity Feishu CLI with a modular gateway client",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
package/proto/lark.proto CHANGED
@@ -285,6 +285,7 @@ message PullChatsByIdsResponse {
285
285
  message PatchGroupChatRequest {
286
286
  optional int64 chatId = 1;
287
287
  optional string name = 2;
288
+ optional string iconData = 3;
288
289
  optional string description = 4;
289
290
  optional string announcement = 5;
290
291
  optional int64 ownerId = 6;
@@ -300,6 +301,7 @@ message PatchGroupChatRequest {
300
301
  enum UpdateFields {
301
302
  UPDATE_FIELDS_UNSPECIFIED = 0;
302
303
  NAME = 1;
304
+ ICON_KEY = 2;
303
305
  DESCRIPTION = 3;
304
306
  ANNOUNCEMENT = 4;
305
307
  OWNER_ID = 5;
@@ -348,6 +350,7 @@ message Chat {
348
350
  optional ChatTypeEnum type = 2;
349
351
  optional string lastMessageId = 3;
350
352
  optional string name = 4;
353
+ optional ChatImage avatar = 5;
351
354
  optional string ownerId = 6;
352
355
  optional int32 newMessageCount = 7;
353
356
  optional int64 updateTime = 9;
@@ -387,6 +390,7 @@ message Chat {
387
390
  optional string docUrl = 4;
388
391
  }
389
392
  }
393
+ message ChatImage { optional string key = 1; }
390
394
 
391
395
  // --- Search (cmd=11021) ---
392
396
 
@@ -623,7 +627,20 @@ message PullFeedCardsByIdsRequest { repeated string cardIds = 1; repeated FeedId
623
627
  message PullFeedCardsByIdsResponse { map<string, InboxCard> cards = 1; }
624
628
  message PatchFeedCardUnreadRequest { optional FeedIdentity card = 1; optional bool markAsUnread = 2; optional int64 readPos = 3; }
625
629
  message PatchFeedCardUnreadResponse { optional InboxCard card = 1; }
626
- message ChatSetting { optional bool isRemind = 1; }
630
+ message ChatSetting {
631
+ optional bool isRemind = 1;
632
+ optional bool isAutoTranslate = 4;
633
+ optional bool isMuteAtAll = 8;
634
+ }
635
+ message PutGroupNicknameRequest { optional int64 chatId = 1; optional string nickname = 2; }
636
+ message CleanUserChatMessageRequest { optional int64 chatId = 1; optional int32 position = 2; }
637
+ message PutUserAliasRequest { optional int64 targetId = 1; optional string name = 2; }
638
+ message PullContactProfileV2Request { optional int32 scene = 1; optional string userId = 2; optional string chatId = 4; optional bool useNewLayout = 12; }
639
+ message PullContactProfileV2Response { optional ContactProfile profile = 1; optional ContactChatMeta chatChatter = 3; }
640
+ message ContactChatMeta { optional int64 chatId = 1; optional int64 chatterId = 2; optional string groupNickname = 4; }
641
+ message ContactProfile { repeated ContactProfileField fields = 3; }
642
+ message ContactProfileField { optional string key = 1; optional bool visible = 3; optional int32 fieldValueType = 5; optional bytes fieldVal = 6; optional string strFieldVal = 7; optional bool editable = 8; }
643
+ message PatchUserMemoRequest { optional string targetUserId = 1; optional string memoText = 3; }
627
644
  message PullChatSettingsRequest { repeated string chatIds = 1; }
628
645
  message PullChatSettingsResponse { map<string, ChatSetting> chatSettings = 1; }
629
646
  message PatchChatSettingRequest { optional string chatId = 1; optional ChatSetting chatSetting = 2; repeated int32 updateChatSettingField = 3; }
@@ -34,6 +34,12 @@ larkmate messages-export --chat "$CHAT_ID" --sender "$MEMBER_ID" --after 1700000
34
34
  larkmate pinned
35
35
  larkmate marked
36
36
  larkmate chat-state --chat "$CHAT_ID"
37
+ larkmate chat-preferences --chat "$CHAT_ID"
38
+ larkmate chat-preferences-set --chat "$CHAT_ID" --mute-at-all true --auto-translate false
39
+ larkmate contact-alias --user "$USER_ID"
40
+ larkmate contact-alias-set --user "$USER_ID" --alias '备注名'
41
+ larkmate contact-note --user "$USER_ID"
42
+ larkmate contact-note-set --user "$USER_ID" --description '备注描述'
37
43
  larkmate pin --chat "$CHAT_ID" # 取消置顶:unpin
38
44
  larkmate mark --chat "$CHAT_ID" # 取消旗帜标记:unmark
39
45
  larkmate unread --chat "$CHAT_ID" # 标为已读:read
@@ -48,6 +54,10 @@ larkmate label-remove --label "$LABEL_ID" --chat "$CHAT_ID"
48
54
 
49
55
  `mark` 对应聊天右键菜单的旗帜“标记”。`read` 会推进到调用时最新可见位置并清除手动未读标记;`unread` 可能把已完成会话放回收件箱。标签创建、重命名和删除分别使用 `label-create`、`label-rename`、`label-delete`,会话成员调整仅支持手动标签。删除标签会删除整个个人标签。
50
56
 
57
+ `chat-clear-history --chat "$CHAT_ID"` 清空当前用户的聊天记录,范围截止于调用时读取到的最后消息位置。该操作不可轻率调用,须有用户明确意图;返回 `submitted_unconfirmed` 时先检查记录,不盲目重试。
58
+
59
+ 联系人备注仅对当前用户生效。`contact-note-set` 修改纯文本描述;备注包含图片或复杂格式时拒绝修改,以保护现有内容。传入空字符串可清除备注名或描述。`--mute-at-all` 控制是否屏蔽 @所有人提醒,`--auto-translate` 控制消息自动翻译,两者均使用 `true` 或 `false`。
60
+
51
61
  `group-query` 支持消息、未读、免打扰、@我、单聊、群组、话题群、云文档、话题和已完成分组;可按名称筛选,使用 `nextCursor` 继续扫描。收纳盒需以 `--parent` 单独查询,`unknownState` 表示无法确定状态的数量。@我通过未读提及消息匹配会话,可能与飞书界面显示不同。标记和标签分别用 `marked`、`labels` 和 `label-chats` 查询。
52
62
 
53
63
  `sidebar-set` 可以显示、隐藏或排序分组,并设置其在消息分组中的展示规则和 @所有人选项;使用 `larkmate sidebar-set --help` 查看参数。修改前先查询当前设置。
@@ -35,12 +35,17 @@ larkmate group-requests --chat "$CHAT_ID"
35
35
  larkmate group-create --name '群名称' --member "$MEMBER_ID"
36
36
  larkmate group-invite --chat "$CHAT_ID" --member "$MEMBER_ID"
37
37
  larkmate group-update --chat "$CHAT_ID" --name '新名称'
38
+ larkmate group-update --chat "$CHAT_ID" --description '新描述'
39
+ larkmate group-avatar-set --chat "$CHAT_ID" --file ./avatar.png
40
+ larkmate group-nickname-set --chat "$CHAT_ID" --nickname '群昵称'
38
41
  larkmate group-bot-info --chat "$CHAT_ID" --bot "$BOT_ID"
39
42
  larkmate group-bot-protection --chat "$CHAT_ID" --bot "$BOT_ID" --allow-member-removal
40
43
  larkmate group-dissolve --chat "$CHAT_ID"
41
44
  ```
42
45
 
43
- `--member` 可重复指定。创建或邀请机器人默认限制普通成员移除,`--allow-member-removal` 可关闭该限制。`verified` 只表示机器人移除限制已读回。遇到 `GROUP_CREATED_PARTIAL` 或 `INVITE_PARTIAL` 时,先检查已产生的群或成员变化,不要盲目重复操作。
46
+ `--member` 可重复指定。创建或邀请机器人默认限制普通成员移除,`--allow-member-removal` 可关闭该限制。机器人邀请结果中的 `verified` 表示移除限制已读回。遇到 `GROUP_CREATED_PARTIAL` 或 `INVITE_PARTIAL` 时,先检查已产生的群或成员变化,不要盲目重复操作。
47
+
48
+ 群头像支持 PNG、JPEG 和 WebP 格式,文件大小上限为 10 MiB。通过委托或代理调用时,图片由调用方读取,并受目标会话及文件大小授权限制。群昵称传入空字符串可清除。
44
49
 
45
50
  `group-settings` 可读取群主、公告、发言和群权限设置;`group-settings-schema` 列出可修改的字段与值。使用 `group-settings-set --chat "$CHAT_ID" --json <文件>` 修改所需字段,`--json -` 从标准输入读取。它会按字段更新,并可配置入群审批、邀请、@全体、历史消息可见性及受限模式等;修改前先读取当前设置。群公告暂不支持修改。
46
51
 
@@ -32,6 +32,11 @@ const routes = {
32
32
  favorites: ['client', 'favorites', 'allChats'],
33
33
  'chat-open': ['client', 'openChat', 'allChats'],
34
34
  'chat-info': ['client', 'chatInfo', 'chatArg'], 'chat-state': ['controls', 'state', 'chatArg'],
35
+ 'chat-preferences': ['controls', 'preferences', 'chatArg'], 'chat-preferences-set': ['controls', 'setPreference', 'chatObject'],
36
+ 'chat-clear-history': ['client', 'clearChatHistory', 'chatObject'],
37
+ 'contact-alias': ['client', 'contactAlias', 'global'], 'contact-alias-set': ['client', 'setContactAlias', 'global'],
38
+ 'contact-note': ['client', 'contactNote', 'global'], 'contact-note-set': ['client', 'setContactNote', 'global'],
39
+ 'group-nickname-set': ['client', 'setGroupNickname', 'chatObject'],
35
40
  history: ['client', 'historyPages', 'chatObject'], 'messages-export': ['client', 'historyPages', 'chatObject'],
36
41
  'group-link': ['groups','link','chatObject'], 'group-requests': ['groups','requests','chatObject'], 'group-request-approve': ['groups','reviewRequest','chatObject'], 'group-request-reject': ['groups','reviewRequest','chatObject'], 'group-post-users': ['groups','postUsers','chatObject'],
37
42
  'group-settings': ['groups','info','chatObject'], 'group-settings-set': ['groups','setSettings','chatObject'],
@@ -56,9 +61,10 @@ const routes = {
56
61
  'minutes-list': ['minutes', 'list', 'allMinutes'], 'minutes-export': ['minutes', 'transcript', 'minute'],
57
62
  'minutes-access-info': ['minutes', 'accessInfo', 'minute'], 'minutes-request-access': ['minutes', 'requestAccess', 'minute'],
58
63
  'send-file': ['files', 'upload', 'file'], 'send-image': ['files', 'upload', 'file'],
64
+ 'group-avatar-set': ['files', 'upload', 'file'],
59
65
  'download-file': ['files', 'download', 'file'],
60
66
  };
61
- const writes = new Set(['send', 'pin', 'unpin', 'mark', 'unmark', 'mute', 'unmute', 'done', 'inbox', 'box', 'unbox', 'read', 'unread',
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',
62
68
  'label-create', 'label-rename', 'label-delete', 'label-add', 'label-remove', 'chat-open', 'group-create', 'group-invite',
63
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',
64
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']);
@@ -154,7 +160,9 @@ export function authorize(policy, request) {
154
160
  : method === 'historyPages' ? ['chatId', 'limit', 'start', 'pages', 'query', 'sender', 'after', 'before']
155
161
  : method === 'members' ? ['chatId', 'cursor', 'offset', 'limit']
156
162
  : method === 'updateGroup' ? ['chatId', 'name', 'description']
157
- : method === 'info' || method === 'admins' || method === 'postUsers' ? ['chatId']
163
+ : method === 'setPreference' ? ['chatId', 'muteAtAll', 'autoTranslate']
164
+ : method === 'setGroupNickname' ? ['chatId', 'nickname']
165
+ : method === 'info' || method === 'admins' || method === 'postUsers' || method === 'clearChatHistory' ? ['chatId']
158
166
  : method === 'link' ? ['chatId','days','unlimited']
159
167
  : method === 'requests' ? ['chatId','cursor']
160
168
  : method === 'reviewRequest' ? ['chatId','userId','approve']
@@ -281,7 +289,7 @@ export async function brokerCall(socketPath, request, tokenFile) {
281
289
  export function brokerProxy(socketPath, service, getCommand, tokenFile) {
282
290
  return new Proxy({}, { get(_target, method) {
283
291
  if (method === 'then' || typeof method !== 'string') return undefined;
284
- if (service === 'client' && ['sendFile', 'sendImage'].includes(method)) return options => brokerUpload(socketPath, tokenFile, getCommand(), options);
292
+ if (service === 'client' && ['sendFile', 'sendImage', 'setGroupAvatar'].includes(method)) return options => brokerUpload(socketPath, tokenFile, getCommand(), options);
285
293
  if (service === 'client' && method === 'downloadFile') return options => brokerDownload(socketPath, tokenFile, options);
286
294
  return (...args) => brokerCall(socketPath, { command: getCommand(), service, method, args }, tokenFile);
287
295
  } });
@@ -24,12 +24,12 @@ export async function handleFileRequest({ req, res, policy, getServices, authori
24
24
  let meta;
25
25
  try { meta = JSON.parse(Buffer.from(req.headers['x-larkmate-file'], 'base64url').toString('utf8')); } catch { bad(); }
26
26
  command = meta?.command;
27
- const upload = command === 'send-file' || command === 'send-image';
27
+ const upload = ['send-file', 'send-image', 'group-avatar-set'].includes(command);
28
28
  if (!only(meta, upload ? ['command', 'chatId', 'name', 'size'] : ['command', 'chatId', 'messageId', 'key', 'position']) || (!upload && command !== 'download-file')) bad();
29
29
  authorize(policy, { command, service: 'files', method: upload ? 'upload' : 'download', args: [{ chatId: meta.chatId }] });
30
30
  requireInt64Id(meta.chatId, 'chat ID');
31
31
  if (upload) {
32
- if (!safeName(meta.name) || !Number.isSafeInteger(meta.size) || meta.size < 1 || meta.size > policy.maxFileBytes || (command === 'send-image' && meta.size > 10 * 1024 * 1024)) bad();
32
+ if (!safeName(meta.name) || !Number.isSafeInteger(meta.size) || meta.size < 1 || meta.size > policy.maxFileBytes || (['send-image', 'group-avatar-set'].includes(command) && meta.size > 10 * 1024 * 1024)) bad();
33
33
  dir = await mkdtemp(join(tmpdir(), 'larkmate-transfer-'));
34
34
  const path = join(dir, meta.name);
35
35
  const file = await open(path, 'wx', 0o600);
@@ -45,7 +45,7 @@ export async function handleFileRequest({ req, res, policy, getServices, authori
45
45
  const { client } = await getServices();
46
46
  if (res.destroyed) return;
47
47
  dispatched = true;
48
- const data = await client[command === 'send-file' ? 'sendFile' : 'sendImage']({ chatId: meta.chatId, path });
48
+ const data = await client[command === 'send-file' ? 'sendFile' : command === 'send-image' ? 'sendImage' : 'setGroupAvatar']({ chatId: meta.chatId, path });
49
49
  answer(200, { ok: true, data });
50
50
  } else {
51
51
  requireInt64Id(meta.messageId, 'message ID');
package/src/client.js CHANGED
@@ -3,6 +3,7 @@ import { FeishuError, requireNumericId, requireInt64Id, requireText } from './er
3
3
  import { shortId } from './gateway.js';
4
4
  import { downloadFile } from './download.js';
5
5
  import { randomUUID } from 'node:crypto';
6
+ import { open } from 'node:fs/promises';
6
7
 
7
8
  function ids(values, label) {
8
9
  if (!Array.isArray(values)) throw new FeishuError('INVALID_ARGUMENT', `${label} must be a list.`);
@@ -24,6 +25,99 @@ function decodedPayload(gateway, response, type, operation) {
24
25
  export class LarkMateClient {
25
26
  constructor(gateway) { this.gateway = gateway; }
26
27
 
28
+ async contactAlias({ userId }) {
29
+ requireInt64Id(userId, 'user ID');
30
+ const r = await this.gateway.call(5031, 'PullContactProfileV2Request', { scene: 1, userId, useNewLayout: true }, { operation: 'contact-alias' });
31
+ const p = this.gateway.decode('PullContactProfileV2Response', r.packet.payload);
32
+ if (!p.profile || !Array.isArray(p.profile.fields)) throw new FeishuError('STATE_UNAVAILABLE', 'Contact profile was not returned.');
33
+ const field = p.profile.fields.find(x => x.fieldValueType === 50 && x.key === 'B-ALIAS');
34
+ if (!field) return { userId, alias: '' };
35
+ try { const alias = JSON.parse(field.strFieldVal).text.default_val; if (typeof alias !== 'string') throw new Error(); return { userId, alias }; }
36
+ catch { throw new FeishuError('INVALID_RESPONSE', 'Contact alias was unreadable.'); }
37
+ }
38
+
39
+ async contactNote({ userId }) {
40
+ requireInt64Id(userId, 'user ID');
41
+ const r = await this.gateway.call(5031, 'PullContactProfileV2Request', { scene: 1, userId, useNewLayout: true }, { operation: 'contact-note' });
42
+ const p = this.gateway.decode('PullContactProfileV2Response', r.packet.payload);
43
+ if (!p.profile || !Array.isArray(p.profile.fields)) throw new FeishuError('STATE_UNAVAILABLE', 'Contact profile was not returned.');
44
+ const field = p.profile.fields.find(x => x.fieldValueType === 105 && x.key === 'B-MEMO-DESCRIPTION');
45
+ if (!field) return { userId, description: '', hasImages: false, hasRichText: false };
46
+ try {
47
+ const note = JSON.parse(field.strFieldVal);
48
+ const elements = Object.values(note.memo_text_v2?.elements?.dictionary || {});
49
+ return { userId, description: note.memo_text ?? note.memo_text_v2?.inner_text ?? '',
50
+ hasImages: !!note.memo_picture || !!note.memo_picture_v2?.length,
51
+ hasRichText: elements.some(x => x.tag !== 1) };
52
+ } catch { throw new FeishuError('INVALID_RESPONSE', 'Contact note was unreadable.'); }
53
+ }
54
+
55
+ async setContactNote({ userId, description }) {
56
+ requireInt64Id(userId, 'user ID');
57
+ if (typeof description !== 'string' || Buffer.byteLength(description) > 65536) throw new FeishuError('INVALID_ARGUMENT', 'Description must be a string up to 64 KiB.');
58
+ const before = await this.contactNote({ userId });
59
+ if (before.hasImages || before.hasRichText) throw new FeishuError('UNSUPPORTED_NOTE_CONTENT', 'The note contains images or rich text; use Feishu to preserve them.');
60
+ if (before.description === description) return { status: 'already_set', userId, description };
61
+ const r = await this.gateway.call(5036, 'PatchUserMemoRequest', { targetUserId: userId, memoText: description }, { mutating: true, operation: 'contact-note-set' });
62
+ try { const after = await this.contactNote({ userId }); return { status: after.description === description ? 'verified' : 'submitted_unconfirmed', userId, requestId: r.requestId }; }
63
+ catch { return { status: 'submitted_unconfirmed', userId, requestId: r.requestId }; }
64
+ }
65
+
66
+ async setContactAlias({ userId, alias }) {
67
+ requireInt64Id(userId, 'user ID');
68
+ if (typeof alias !== 'string' || Buffer.byteLength(alias) > 1024) throw new FeishuError('INVALID_ARGUMENT', 'Alias must be a string up to 1024 bytes.');
69
+ const before = await this.contactAlias({ userId });
70
+ if (before.alias === alias) return { status: 'already_set', userId, alias };
71
+ const r = await this.gateway.call(5400, 'PutUserAliasRequest', { targetId: userId, name: alias }, { mutating: true, operation: 'contact-alias-set' });
72
+ try { const after = await this.contactAlias({ userId }); return { status: after.alias === alias ? 'verified' : 'submitted_unconfirmed', userId, requestId: r.requestId }; }
73
+ catch { return { status: 'submitted_unconfirmed', userId, requestId: r.requestId }; }
74
+ }
75
+
76
+ async setGroupNickname({ chatId, nickname }) {
77
+ requireInt64Id(chatId, 'chat ID');
78
+ if (typeof nickname !== 'string' || Buffer.byteLength(nickname) > 1024) throw new FeishuError('INVALID_ARGUMENT', 'Nickname must be a string up to 1024 bytes.');
79
+ const r = await this.gateway.call(5401, 'PutGroupNicknameRequest', { chatId, nickname }, { mutating: true, operation: 'group-nickname-set' });
80
+ try {
81
+ const me = await this.gateway.authenticate();
82
+ const p = await this.gateway.call(5031, 'PullContactProfileV2Request', { scene: 1, userId: me.id, chatId, useNewLayout: true }, { operation: 'group-nickname-read' });
83
+ const meta = this.gateway.decode('PullContactProfileV2Response', p.packet.payload).chatChatter;
84
+ return { status: String(meta?.chatId) === chatId && meta.groupNickname === nickname ? 'verified' : 'submitted_unconfirmed', chatId, requestId: r.requestId };
85
+ } catch { return { status: 'submitted_unconfirmed', chatId, requestId: r.requestId }; }
86
+ }
87
+
88
+ async clearChatHistory({ chatId }) {
89
+ requireInt64Id(chatId, 'chat ID');
90
+ const info = await this.chatInfo(chatId);
91
+ if (!Number.isInteger(info.lastMessagePosition) || info.lastMessagePosition < 0) throw new FeishuError('POSITION_UNAVAILABLE', 'The last message position is unavailable.');
92
+ if (!info.lastMessagePosition) return { status: 'already_empty', chatId };
93
+ const r = await this.gateway.call(900011, 'CleanUserChatMessageRequest', { chatId, position: info.lastMessagePosition }, { mutating: true, operation: 'chat-clear-history' });
94
+ return { status: 'submitted_unconfirmed', chatId, throughPosition: info.lastMessagePosition, requestId: r.requestId };
95
+ }
96
+
97
+ async setGroupAvatar({ chatId, path }) {
98
+ requireInt64Id(chatId, 'chat ID');
99
+ let file, dispatched = false;
100
+ try {
101
+ file = await open(path, 'r'); const stat = await file.stat();
102
+ if (!stat.isFile() || stat.size < 1 || stat.size > 10 * 1024 * 1024) throw new FeishuError('FILE_INVALID', 'Use an image up to 10 MiB.');
103
+ const b = await file.readFile();
104
+ let mime;
105
+ if (b.subarray(0,8).equals(Buffer.from('89504e470d0a1a0a','hex'))) mime = 'image/png';
106
+ else if (b.length >= 3 && b[0] === 255 && b[1] === 216 && b[2] === 255) mime = 'image/jpeg';
107
+ else if (b.subarray(0,4).toString() === 'RIFF' && b.subarray(8,12).toString() === 'WEBP') mime = 'image/webp';
108
+ else throw new FeishuError('FILE_INVALID', 'Use a PNG, JPEG or WebP image.');
109
+ const getAvatar = async () => { const x = await this.gateway.call(64, 'PullChatsByIdsRequest', { chatIds: [chatId] }, { operation: 'group-avatar-read' }); const chat = this.gateway.decode('PullChatsByIdsResponse', x.packet.payload).chats?.[chatId]; if (!chat || ![2, 3].includes(chat.type)) throw new FeishuError('NOT_FOUND', 'Group was not found.'); return chat.avatar?.key || null; };
110
+ const before = await getAvatar();
111
+ dispatched = true;
112
+ const r = await this.gateway.call(72, 'PatchGroupChatRequest', { chatId, iconData: `data:${mime};base64,${b.toString('base64')}`, updateFields: [2] }, { mutating: true, operation: 'group-avatar-set' });
113
+ const result = decodedPayload(this.gateway, r, 'PatchGroupChatResponse', 'group-avatar-set');
114
+ if (!result.chat?.id || String(result.chat.id) !== chatId) throw new FeishuError('EFFECT_UNKNOWN', 'Group avatar update was not confirmed.', { requestId: r.requestId });
115
+ try { const after = await getAvatar(); return { status: after && after !== before ? 'verified' : 'submitted_unconfirmed', chatId, requestId: r.requestId }; }
116
+ catch { return { status: 'submitted_unconfirmed', chatId, requestId: r.requestId }; }
117
+ } catch (e) { if (e instanceof FeishuError) throw e; throw new FeishuError(dispatched ? 'EFFECT_UNKNOWN' : 'FILE_UNAVAILABLE', dispatched ? 'The avatar update could not be confirmed; inspect before retrying.' : 'Cannot read the image or group.'); }
118
+ finally { await file?.close(); }
119
+ }
120
+
27
121
  async status() {
28
122
  return { status: 'ready', identity: 'user', user: await this.gateway.authenticate() };
29
123
  }
@@ -79,7 +79,7 @@ export function osDelegateProxy(owner, launcher, service, getCommand) {
79
79
  if (method === 'then' || typeof method !== 'string') return undefined;
80
80
  return (...args) => {
81
81
  const command = getCommand();
82
- if (service === 'client' && ['sendFile', 'sendImage'].includes(method)) {
82
+ if (service === 'client' && ['sendFile', 'sendImage', 'setGroupAvatar'].includes(method)) {
83
83
  const { chatId, path } = args[0];
84
84
  return callOsDelegate({ owner, launcher, request: { command, service: 'files', method: 'upload', args: [{ chatId }] }, inputPath: path });
85
85
  }
@@ -77,14 +77,14 @@ export async function checkDelegation({ profile, uid, request, file }) {
77
77
  }
78
78
 
79
79
  export async function invokeDelegated({ profile, uid, request, getServices, filePath }) {
80
- const fileOp = ['send-file', 'send-image', 'download-file'].includes(request?.command);
80
+ const fileOp = ['send-file', 'send-image', 'group-avatar-set', 'download-file'].includes(request?.command);
81
81
  if (fileOp && request.service !== 'files') noAccess();
82
82
  if (!fileOp && request.service === 'files') noAccess();
83
83
  let file;
84
- if (request.command === 'send-file' || request.command === 'send-image') {
84
+ if (['send-file', 'send-image', 'group-avatar-set'].includes(request.command)) {
85
85
  if (!filePath || !nameOk(request.fileName)) fail('INVALID_REQUEST', 'Invalid file transfer.');
86
86
  const info = await stat(filePath);
87
- if (!info.isFile() || info.size < 1 || info.size > profile.policy.maxFileBytes || (request.command === 'send-image' && info.size > 10 * 1024 * 1024)) fail('FILE_TOO_LARGE', 'The file exceeds the configured limit.');
87
+ if (!info.isFile() || info.size < 1 || info.size > profile.policy.maxFileBytes || (['send-image', 'group-avatar-set'].includes(request.command) && info.size > 10 * 1024 * 1024)) fail('FILE_TOO_LARGE', 'The file exceeds the configured limit.');
88
88
  const hash = createHash('sha256'); for await (const chunk of createReadStream(filePath)) hash.update(chunk);
89
89
  file = { name: request.fileName, size: info.size, sha256: hash.digest('hex') };
90
90
  }
@@ -106,7 +106,7 @@ export async function invokeDelegated({ profile, uid, request, getServices, file
106
106
  }
107
107
  const client = services.client, o = args[0];
108
108
  if (method === 'upload') {
109
- try { return { data: await client[rpc.command === 'send-file' ? 'sendFile' : 'sendImage']({ chatId: o.chatId, path: filePath }) }; }
109
+ try { return { data: await client[rpc.command === 'send-file' ? 'sendFile' : rpc.command === 'send-image' ? 'sendImage' : 'setGroupAvatar']({ chatId: o.chatId, path: filePath }) }; }
110
110
  catch (error) { if (!(error instanceof FeishuError)) fail('EFFECT_UNKNOWN', 'The delegated write could not be confirmed; inspect before retrying.'); throw error; }
111
111
  }
112
112
  return { download: true, client, options: o };
@@ -126,7 +126,7 @@ export async function serveOne({ input, output, uid, profile, getServices }) {
126
126
  try { request = JSON.parse(header.subarray(0, end).toString('utf8')); } catch { fail('INVALID_REQUEST', 'Invalid request.'); }
127
127
  data = header.subarray(end + 1); header = null;
128
128
  if (!only(request, ['command', 'service', 'method', 'args', 'fileName', 'size'])) fail('INVALID_REQUEST', 'Invalid request.');
129
- const upload = request.command === 'send-file' || request.command === 'send-image';
129
+ const upload = ['send-file', 'send-image', 'group-avatar-set'].includes(request.command);
130
130
  if (upload) {
131
131
  if (!nameOk(request.fileName) || !Number.isSafeInteger(request.size) || request.size < 1 || request.size > profile.policy.maxFileBytes || request.size > MAX_FILE) fail('FILE_TOO_LARGE', 'The file exceeds the configured limit.');
132
132
  const { size, fileName, ...rpc } = request;
@@ -198,6 +198,30 @@ export class SessionControls {
198
198
  return !x.isRemind;
199
199
  }
200
200
 
201
+ async preferences(chatId) {
202
+ numeric(chatId, 'chat ID');
203
+ const p = await this.read(62, 'PullChatSettingsRequest', { chatIds: [chatId] }, 'PullChatSettingsResponse');
204
+ const x = p.chatSettings?.[chatId];
205
+ if (!x) throw new FeishuError('STATE_UNAVAILABLE', 'Conversation settings were not returned.');
206
+ return { chatId, muteAtAll: own(x, 'isMuteAtAll') ? x.isMuteAtAll : null,
207
+ autoTranslate: own(x, 'isAutoTranslate') ? x.isAutoTranslate : null };
208
+ }
209
+
210
+ async setPreference({ chatId, muteAtAll, autoTranslate }) {
211
+ numeric(chatId, 'chat ID');
212
+ const settings = {}, fields = [];
213
+ for (const [name, value, field, id] of [['muteAtAll', muteAtAll, 'isMuteAtAll', 6], ['autoTranslate', autoTranslate, 'isAutoTranslate', 4]]) {
214
+ if (value !== undefined) {
215
+ if (typeof value !== 'boolean') throw new FeishuError('INVALID_ARGUMENT', `${name} must be a boolean.`);
216
+ settings[field] = value; fields.push(id);
217
+ }
218
+ }
219
+ if (!fields.length) throw new FeishuError('INVALID_ARGUMENT', 'Specify at least one preference.');
220
+ const result = await this.verified(() => this.write(60, 'PatchChatSettingRequest', { chatId, chatSetting: settings, updateChatSettingField: fields }),
221
+ async () => { const after = await this.preferences(chatId); return (muteAtAll === undefined || after.muteAtAll === muteAtAll) && (autoTranslate === undefined || after.autoTranslate === autoTranslate); });
222
+ return { ...result, chatId };
223
+ }
224
+
201
225
  async setMute(chatId, enabled) {
202
226
  const before = await this.muted(chatId);
203
227
  if (before === enabled) return { status: 'already_set', chatId, muted: enabled };