larkmate 0.1.10 → 0.1.11
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 +6 -0
- package/bin/larkmate.js +72 -3
- package/bin/os-delegate-helper.js +4 -1
- package/docs/agent-broker.md +1 -1
- package/package.json +1 -1
- package/proto/lark.proto +41 -0
- package/proto/todo-schema.json +1 -0
- package/skills/larkmate/SKILL.md +3 -2
- package/skills/larkmate/references/chats.md +8 -0
- package/skills/larkmate/references/tasks.md +22 -0
- package/src/agent-broker.js +8 -1
- package/src/feed-groups.js +82 -0
- package/src/gateway.js +12 -2
- package/src/sidebar-filters.js +80 -0
- package/src/tasks.js +112 -0
package/skills/larkmate/SKILL.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: larkmate
|
|
3
|
-
description: 使用 LarkMate
|
|
3
|
+
description: 使用 LarkMate 以当前飞书网页版用户身份管理会话、搜索与操作消息、收发文件及图片、管理群组和飞书任务,以及查询录制妙记、申请访问权限和导出文字记录。当用户要求使用 LarkMate 或需要执行上述个人飞书操作时使用;不负责飞书文档或日历。
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# LarkMate
|
|
@@ -15,8 +15,9 @@ description: 使用 LarkMate 以当前飞书网页版用户身份管理会话、
|
|
|
15
15
|
|
|
16
16
|
- 查找会话、搜索与导出消息、获取链接、下载资源,以及管理会话状态和标签: [会话与消息](references/chats.md)。
|
|
17
17
|
- 发送与管理消息、文件、图片、表情和收藏,管理群组及成员: [发送与群组](references/writes.md)。
|
|
18
|
+
- 查询和管理飞书任务、任务视图及成员: [飞书任务](references/tasks.md)。
|
|
18
19
|
- 查找录制妙记、导出文字记录、查询或申请访问权限: [录制妙记](references/minutes.md)。
|
|
19
20
|
|
|
20
21
|
命令输出 JSON:成功为 `ok: true`,失败为 `ok: false`,检查退出码和错误信息。飞书网页客户端数字 ID 与开放平台 ID 不同;按实际查询结果选定对象,名称相近时先消歧。列表和搜索有分页或扫描范围,无法读取的内容、缺失结果和权限错误应如实说明。
|
|
21
22
|
|
|
22
|
-
`chat-open`
|
|
23
|
+
`chat-open` 会打开或创建私聊;发送、修改消息、表情、收藏、群组、会话状态、任务及妙记权限申请等命令也会修改数据,请按用户的实际意图操作。写入返回 `EFFECT_UNKNOWN`、`submitted_unconfirmed` 或部分成功时,先查询实际状态,避免重复提交。不要将消息已发送当作对方已读。
|
|
@@ -7,6 +7,10 @@ larkmate search-messages --query '消息关键词' --cursor "$NEXT_CURSOR"
|
|
|
7
7
|
larkmate chats --limit 50
|
|
8
8
|
larkmate chats --cursor "$NEXT_CURSOR"
|
|
9
9
|
larkmate chats --parent "$BOX_ID"
|
|
10
|
+
larkmate group-query --group unread --pages 3
|
|
11
|
+
larkmate group-query --group at_me --query '关键词'
|
|
12
|
+
larkmate sidebar-list
|
|
13
|
+
larkmate sidebar-set --filter muted --visibility show --position 2
|
|
10
14
|
larkmate chat-info --chat "$CHAT_ID"
|
|
11
15
|
larkmate history --chat "$CHAT_ID" --limit 50 --pages 3
|
|
12
16
|
larkmate message-link --chat "$CHAT_ID" --message "$MESSAGE_ID"
|
|
@@ -43,3 +47,7 @@ larkmate label-remove --label "$LABEL_ID" --chat "$CHAT_ID"
|
|
|
43
47
|
```
|
|
44
48
|
|
|
45
49
|
`mark` 对应聊天右键菜单的旗帜“标记”。`read` 会推进到调用时最新可见位置并清除手动未读标记;`unread` 可能把已完成会话放回收件箱。标签创建、重命名和删除分别使用 `label-create`、`label-rename`、`label-delete`,会话成员调整仅支持手动标签。删除标签会删除整个个人标签。
|
|
50
|
+
|
|
51
|
+
`group-query` 支持消息、未读、免打扰、@我、单聊、群组、话题群、云文档、话题和已完成分组;可按名称筛选,使用 `nextCursor` 继续扫描。收纳盒需以 `--parent` 单独查询,`unknownState` 表示无法确定状态的数量。@我通过未读提及消息匹配会话,可能与飞书界面显示不同。标记和标签分别用 `marked`、`labels` 和 `label-chats` 查询。
|
|
52
|
+
|
|
53
|
+
`sidebar-set` 可以显示、隐藏或排序分组,并设置其在消息分组中的展示规则和 @所有人选项;使用 `larkmate sidebar-set --help` 查看参数。修改前先查询当前设置。
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# 飞书任务
|
|
2
|
+
|
|
3
|
+
`task-center` 查询任务中心及视图;`tasks-list` 支持 mine、followed、all、created、assigned 和 completed 视图。可按关键词搜索、读取、新建、编辑、完成、重开和删除任务。
|
|
4
|
+
|
|
5
|
+
`tasks-list` 使用返回的 `nextCursor` 继续分页;任务列表发生变化时需从头查询。注意 `missing` 和 `serverReportedAllTasks`,不要把服务端未返回的任务当成不存在。
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
larkmate task-center
|
|
9
|
+
larkmate tasks-list --scope mine --limit 50
|
|
10
|
+
larkmate tasks-list --scope mine --cursor "$NEXT_CURSOR"
|
|
11
|
+
larkmate task-search --query '关键词'
|
|
12
|
+
larkmate task-get --id "$TASK_ID"
|
|
13
|
+
larkmate task-create --title '任务标题' --description '说明' --due '2026-12-01T18:00:00+08:00' --assignee "$USER_ID" --follower "$FOLLOWER_ID"
|
|
14
|
+
larkmate task-update --id "$TASK_ID" --due '2026-12-02T18:00:00+08:00' --add-assignee "$USER_ID"
|
|
15
|
+
larkmate task-complete --id "$TASK_ID"
|
|
16
|
+
larkmate task-reopen --id "$TASK_ID"
|
|
17
|
+
larkmate task-delete --id "$TASK_ID"
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
开始和截止时间可用毫秒时间戳或 ISO 日期;更新时用 `0` 清除时间。创建支持全天、重复规则、所属清单和积分等选项,使用 `task-create --help` 查看。`--json` 可从调用方本地文件或标准输入读取完整 `todo_entities.InputTask` JSON,提供提醒、子任务、附件引用和自定义字段等高级配置;字段结构参照包内 `proto/todo-schema.json`。常用参数覆盖 JSON 中对应字段。更新支持标题、描述、时间、重复规则、里程碑、积分、负责人和关注人;`--commits-json` 接受高级字段的原生提交数组(`key`、`dataType`、Base64 编码的 `added`/`deleted`),结构参照同一协议文件。高级字段能否使用由飞书接口和当前用户权限决定。
|
|
21
|
+
|
|
22
|
+
写入返回 `EFFECT_UNKNOWN`、`submitted_unconfirmed`、部分成功或拒绝时,先重新读取任务并核对状态,不要盲目重试。任务创建、修改、完成和删除会改变飞书数据,只在用户授权范围内操作。
|
package/src/agent-broker.js
CHANGED
|
@@ -11,6 +11,12 @@ import { handleFileRequest, brokerUpload, brokerDownload } from './agent-files.j
|
|
|
11
11
|
// An explicit mapping prevents callers from reaching arbitrary object methods.
|
|
12
12
|
const routes = {
|
|
13
13
|
status: ['client', 'status', 'global'], search: ['client', 'search', 'global'],
|
|
14
|
+
'group-query': ['feeds', 'query', 'allChats'],
|
|
15
|
+
'task-center': ['tasks', 'center', 'global'], 'tasks-list': ['tasks', 'list', 'global'],
|
|
16
|
+
'task-search': ['tasks', 'search', 'global'], 'task-get': ['tasks', 'get', 'global'],
|
|
17
|
+
'task-create': ['tasks', 'create', 'global'], 'task-update': ['tasks', 'update', 'global'],
|
|
18
|
+
'task-complete': ['tasks', 'complete', 'global'], 'task-reopen': ['tasks', 'complete', 'global'], 'task-delete': ['tasks', 'delete', 'global'],
|
|
19
|
+
'sidebar-list': ['sidebar', 'list', 'global'], 'sidebar-set': ['sidebar', 'set', 'allChats'],
|
|
14
20
|
'search-messages': ['client', 'searchMessages', 'allChats'], chats: ['client', 'chats', 'allChats'],
|
|
15
21
|
pinned: ['controls', 'pinned', 'allChats'], marked: ['controls', 'marked', 'allChats'],
|
|
16
22
|
labels: ['controls', 'labels', 'allChats'], 'label-chats': ['controls', 'labelChats', 'allChats'],
|
|
@@ -44,7 +50,7 @@ const routes = {
|
|
|
44
50
|
const writes = new Set(['send', 'pin', 'unpin', 'mark', 'unmark', 'mute', 'unmute', 'done', 'inbox', 'box', 'unbox', 'read', 'unread',
|
|
45
51
|
'label-create', 'label-rename', 'label-delete', 'label-add', 'label-remove', 'chat-open', 'group-create', 'group-invite',
|
|
46
52
|
'group-update', 'group-dissolve', 'group-bot-protection', 'message-edit', 'message-forward', 'message-recall', 'favorite-add',
|
|
47
|
-
'favorite-remove', 'reaction-add', 'reaction-remove', 'minutes-request-access', 'send-file', 'send-image']);
|
|
53
|
+
'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']);
|
|
48
54
|
|
|
49
55
|
export function brokerCommands() {
|
|
50
56
|
return Object.entries(routes).map(([command, [, , scope]]) => ({ command,
|
|
@@ -116,6 +122,7 @@ export function authorize(policy, request) {
|
|
|
116
122
|
const args = request.args;
|
|
117
123
|
const chatAllowed = id => numeric(id) && (policy.allowAllChats || policy.chatIds.includes(id));
|
|
118
124
|
if (scope === 'global' && !policy.allowGlobal) denied();
|
|
125
|
+
if (['task-complete', 'task-reopen'].includes(request.command) && (args.length !== 1 || !object(args[0]) || args[0].completed !== (request.command === 'task-complete'))) denied();
|
|
119
126
|
if (['allChats', 'labelTrue', 'labelFalse', 'reactionAdd', 'reactionRemove'].includes(scope) && (!policy.allowGlobal || !policy.allowAllChats)) denied();
|
|
120
127
|
if (scope === 'allMinutes' && (!policy.allowGlobal || !policy.allowAllMinutes)) denied();
|
|
121
128
|
if (scope === 'file' && (args.length !== 1 || !only(args[0], method === 'download' ? ['chatId', 'messageId', 'key', 'position'] : ['chatId']) || !chatAllowed(args[0].chatId))) denied();
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { FeishuError } from './errors.js';
|
|
2
|
+
|
|
3
|
+
const valid = new Set(['messages', 'unread', 'muted', 'at_me', 'p2p', 'group', 'topic_group', 'docs', 'threads', 'done']);
|
|
4
|
+
const numeric = value => typeof value === 'string' && /^\d{1,19}$/.test(value);
|
|
5
|
+
const own = (o, k) => !!o && Object.hasOwn(o, k);
|
|
6
|
+
|
|
7
|
+
export class FeedGroups {
|
|
8
|
+
constructor(gateway) { this.gateway = gateway; }
|
|
9
|
+
async atMessages() {
|
|
10
|
+
const p = await this.gateway.call(96, 'PullUnreadAtMessageIdsRequest', {}, { operation: 'group-query' });
|
|
11
|
+
if (!own(p.packet, 'payload')) throw new FeishuError('INVALID_RESPONSE', 'Unread mention data was not returned.');
|
|
12
|
+
const ids = this.gateway.decode('PullUnreadAtMessageIdsResponse', p.packet.payload).messageIds;
|
|
13
|
+
const byChat = new Map(); let missing = 0;
|
|
14
|
+
for (let i = 0; i < ids.length; i += 100) {
|
|
15
|
+
const r = await this.gateway.call(8, 'PullMessagesByIdsRequest', { messageIds: ids.slice(i, i + 100) }, { operation: 'group-query' });
|
|
16
|
+
if (!own(r.packet, 'payload')) throw new FeishuError('INVALID_RESPONSE', 'Mention messages were not returned.');
|
|
17
|
+
const messages = this.gateway.decode('PullMessagesByIdsResponse', r.packet.payload).messages;
|
|
18
|
+
for (const id of ids.slice(i, i + 100)) {
|
|
19
|
+
const m = messages[id]; if (!m?.chatId) { missing++; continue; }
|
|
20
|
+
const list = byChat.get(m.chatId) || []; list.push(id); byChat.set(m.chatId, list);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return { byChat, missing, total: ids.length };
|
|
24
|
+
}
|
|
25
|
+
async page({ group, cursor, parent, limit }) {
|
|
26
|
+
const r = await this.gateway.call(1000, 'PullFeedCardsRequest', { type: group === 'done' ? 2 : 1,
|
|
27
|
+
pullType: cursor ? 2 : 1, count: limit, ...(cursor ? { cursor } : {}), ...(parent ? { parentCardId: parent } : {}) },
|
|
28
|
+
{ operation: 'group-query', version: '5.7.0' });
|
|
29
|
+
if (!own(r.packet, 'payload')) throw new FeishuError('INVALID_RESPONSE', 'Feed page was not returned.');
|
|
30
|
+
return this.gateway.decode('PullFeedCardsResponse', r.packet.payload);
|
|
31
|
+
}
|
|
32
|
+
async query({ group, query, limit = 100, pages = 20, cursor, parent } = {}) {
|
|
33
|
+
if (!valid.has(group) || !Number.isInteger(limit) || limit < 1 || limit > 100 || !Number.isInteger(pages) || pages < 1 || pages > 100 ||
|
|
34
|
+
(query != null && typeof query !== 'string') || (cursor != null && !numeric(cursor)) || (parent != null && !numeric(parent))) {
|
|
35
|
+
throw new FeishuError('INVALID_ARGUMENT', 'Invalid group query or pagination.');
|
|
36
|
+
}
|
|
37
|
+
const mention = group === 'at_me' ? await this.atMessages() : null;
|
|
38
|
+
let next = cursor, items = [], boxes = [], scanned = 0, unknown = 0; const seen = new Set();
|
|
39
|
+
for (let i = 0; i < pages; i++) {
|
|
40
|
+
const page = await this.page({ group, cursor: next, parent, limit });
|
|
41
|
+
const settings = {};
|
|
42
|
+
if (group === 'muted') {
|
|
43
|
+
const ids = page.cards.filter(c => c.type === 1).map(c => c.id);
|
|
44
|
+
if (ids.length) {
|
|
45
|
+
const r = await this.gateway.call(62, 'PullChatSettingsRequest', { chatIds: ids }, { operation: 'group-query' });
|
|
46
|
+
if (!own(r.packet, 'payload')) throw new FeishuError('INVALID_RESPONSE', 'Notification settings were not returned.');
|
|
47
|
+
Object.assign(settings, this.gateway.decode('PullChatSettingsResponse', r.packet.payload).chatSettings);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
for (const card of page.cards) {
|
|
51
|
+
if (card.type === 5) { boxes.push({ id: String(card.id) }); continue; }
|
|
52
|
+
const id = String(card.id), chat = page.chats[id], doc = page.docFeeds[id], thread = page.threads[id];
|
|
53
|
+
let item;
|
|
54
|
+
if (card.type === 1) {
|
|
55
|
+
const count = own(chat, 'newMessageCount') ? chat.newMessageCount : null;
|
|
56
|
+
const manual = card.feedCardField ? (card.feedCardField.markAsUnread?.unread ?? false) : null;
|
|
57
|
+
const unread = count > 0 || manual === true ? true : count === 0 && manual === false ? false : null;
|
|
58
|
+
item = { id, type: ({ 1: 'p2p', 2: 'group', 3: 'topic_group' })[chat?.type] || 'unknown', name: chat?.name || '', unread, unreadCount: count };
|
|
59
|
+
if (group === 'muted') item.muted = own(settings[id], 'isRemind') ? !settings[id].isRemind : null;
|
|
60
|
+
if (mention?.byChat.has(id)) item.atMessageIds = mention.byChat.get(id);
|
|
61
|
+
} else if (card.type === 3) item = { id, type: 'docs', name: doc?.title || '', unreadCount: own(doc, 'newMessageCount') ? doc.newMessageCount : null, url: doc?.url || null };
|
|
62
|
+
else if (card.type === 4) item = { id, type: 'threads', name: thread?.topic || '', chatId: thread?.channelId || null, unreadCount: own(thread, 'newMessageCount') ? thread.newMessageCount : null };
|
|
63
|
+
else continue;
|
|
64
|
+
scanned++;
|
|
65
|
+
if (group === 'unread') {
|
|
66
|
+
const state = item.type === 'docs' || item.type === 'threads' ? (item.unreadCount == null ? null : item.unreadCount > 0) : item.unread;
|
|
67
|
+
if (state == null) { unknown++; continue; } if (!state) continue;
|
|
68
|
+
} else if (group === 'muted') { if (item.muted == null) { unknown++; continue; } if (!item.muted) continue; }
|
|
69
|
+
else if (group === 'at_me') { if (!mention.byChat.has(id)) continue; }
|
|
70
|
+
else if (!['messages', 'done'].includes(group) && item.type !== group) continue;
|
|
71
|
+
if (query && !item.name.toLocaleLowerCase().includes(query.toLocaleLowerCase())) continue;
|
|
72
|
+
items.push(item);
|
|
73
|
+
}
|
|
74
|
+
const cursorValue = own(page, 'nextCursor') && String(page.nextCursor) !== '0' ? String(page.nextCursor) : null;
|
|
75
|
+
if (!cursorValue) { next = null; break; }
|
|
76
|
+
if (seen.has(cursorValue) || cursorValue === next) throw new FeishuError('PAGINATION_INCOMPLETE', 'Feed pagination repeated its cursor.');
|
|
77
|
+
seen.add(cursorValue); next = cursorValue;
|
|
78
|
+
}
|
|
79
|
+
return { group, items, boxes, scanned, unknownState: unknown, nextCursor: next ?? null, complete: next == null,
|
|
80
|
+
...(mention ? { mentionMessages: mention.total, unmappedMentionMessages: mention.missing } : {}) };
|
|
81
|
+
}
|
|
82
|
+
}
|
package/src/gateway.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { randomBytes, randomUUID } from 'node:crypto';
|
|
2
2
|
import { fileURLToPath } from 'node:url';
|
|
3
3
|
import protobuf from 'protobufjs';
|
|
4
|
+
import { readFile } from 'node:fs/promises';
|
|
4
5
|
import { FeishuError } from './errors.js';
|
|
5
6
|
|
|
6
7
|
const protoFile = fileURLToPath(new URL('../proto/lark.proto', import.meta.url));
|
|
8
|
+
const todoProtoFile = fileURLToPath(new URL('../proto/todo-schema.json', import.meta.url));
|
|
9
|
+
let todoProtoPromise;
|
|
7
10
|
const defaults = {
|
|
8
11
|
csrf: 'https://internal-api-lark-api.feishu.cn/accounts/csrf',
|
|
9
12
|
user: 'https://internal-api-lark-api.feishu.cn/accounts/web/user',
|
|
@@ -104,7 +107,7 @@ export class Gateway {
|
|
|
104
107
|
}
|
|
105
108
|
|
|
106
109
|
encode(name, data) {
|
|
107
|
-
const type = this.proto.lookupType(name);
|
|
110
|
+
const type = (name.startsWith('todo.') || name.startsWith('todo_entities.') ? this.todoProto : this.proto).lookupType(name);
|
|
108
111
|
const message = type.fromObject(data);
|
|
109
112
|
const error = type.verify(message);
|
|
110
113
|
if (error) throw new FeishuError('PROTOCOL_INPUT_INVALID', `Invalid ${name} payload.`);
|
|
@@ -112,7 +115,7 @@ export class Gateway {
|
|
|
112
115
|
}
|
|
113
116
|
|
|
114
117
|
decode(name, bytes) {
|
|
115
|
-
return this.proto.lookupType(name).decode(bytes);
|
|
118
|
+
return (name.startsWith('todo.') || name.startsWith('todo_entities.') ? this.todoProto : this.proto).lookupType(name).decode(bytes);
|
|
116
119
|
}
|
|
117
120
|
|
|
118
121
|
async uploadRequest(path, body, contentType) {
|
|
@@ -151,8 +154,15 @@ export class Gateway {
|
|
|
151
154
|
return { data, requestId };
|
|
152
155
|
}
|
|
153
156
|
|
|
157
|
+
async ensureTodoProto() {
|
|
158
|
+
todoProtoPromise ||= readFile(todoProtoFile, 'utf8').then(text => protobuf.Root.fromJSON(JSON.parse(text)));
|
|
159
|
+
this.todoProto = await todoProtoPromise;
|
|
160
|
+
return this.todoProto;
|
|
161
|
+
}
|
|
162
|
+
|
|
154
163
|
async call(command, requestType, body, { version = '2.7.0', mutating = false, operation } = {}) {
|
|
155
164
|
await this.authenticate();
|
|
165
|
+
if (requestType.startsWith('todo.')) await this.ensureTodoProto();
|
|
156
166
|
const requestId = randomUUID();
|
|
157
167
|
const packet = this.encode('Packet', {
|
|
158
168
|
payloadType: 1, cmd: command, cid: requestId,
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { FeishuError } from './errors.js';
|
|
2
|
+
|
|
3
|
+
export const SIDEBAR_FILTERS = Object.freeze({ at_me: 1, unread: 2, delayed: 3, docs: 4, p2p: 5, group: 6, bot: 7,
|
|
4
|
+
help_desk: 8, topic_group: 9, done: 10, crypto_chat: 11, muted: 12, labels: 13, team: 14, marked: 15,
|
|
5
|
+
threads: 16, unread_over_days: 17, calendar_meetings: 18, instant_meetings: 19, messages: 25, expired_fold: 26 });
|
|
6
|
+
const byId = Object.fromEntries(Object.entries(SIDEBAR_FILTERS).map(([name, id]) => [id, name]));
|
|
7
|
+
const rules = { always: 1, new: 2, never: 3 };
|
|
8
|
+
const msgTypes = { all: 1, at_me: 2, at_all: 3, star_contacts: 4 };
|
|
9
|
+
const invalid = () => { throw new FeishuError('INVALID_ARGUMENT', 'Invalid sidebar filter or settings.'); };
|
|
10
|
+
const idFor = input => typeof input === 'string' && Object.hasOwn(SIDEBAR_FILTERS, input) ? SIDEBAR_FILTERS[input] : /^\d+$/.test(String(input)) && Number(input) > 0 && Number(input) <= 2147483647 ? Number(input) : invalid();
|
|
11
|
+
|
|
12
|
+
export class SidebarFilters {
|
|
13
|
+
constructor(gateway) { this.gateway = gateway; }
|
|
14
|
+
async raw() {
|
|
15
|
+
const res = await this.gateway.call(7022, 'PullSidebarFilterSettingRequest', { needAllFilters: true }, { operation: 'sidebar-list' });
|
|
16
|
+
if (!res.packet.payload?.length) throw new FeishuError('INVALID_RESPONSE', 'No sidebar settings were returned.');
|
|
17
|
+
let p; try { p = this.gateway.decode('PullSidebarFilterSettingResponse', res.packet.payload); } catch { throw new FeishuError('INVALID_RESPONSE', 'Sidebar settings were unreadable.'); }
|
|
18
|
+
if (!p.setting || !Array.isArray(p.setting.usedFilters)) throw new FeishuError('INVALID_RESPONSE', 'Sidebar filter settings were absent.');
|
|
19
|
+
return p;
|
|
20
|
+
}
|
|
21
|
+
view(p) {
|
|
22
|
+
const used = p.setting.usedFilters.map(x => x.systemFilter);
|
|
23
|
+
const available = [...new Set([...used, ...p.allFilters.map(x => x.systemFilter)])].filter(x => Number.isInteger(x) && x > 0);
|
|
24
|
+
const display = p.setting.filterDisplayFeedRule || {};
|
|
25
|
+
return { items: available.map(id => ({ id, name: byId[id] || `unknown_${id}`, shown: used.includes(id),
|
|
26
|
+
position: used.includes(id) ? used.indexOf(id) + 1 : null,
|
|
27
|
+
displayRule: display[id] ? { mainRule: display[id].mainRule ?? null, msgTypes: display[id].msgTypes || [] } : null })),
|
|
28
|
+
showFilter: p.setting.showFilter ?? null, showMuteFilter: p.setting.showMuteFilter ?? null,
|
|
29
|
+
showAtAllInAtFilter: p.setting.showAtAllInAtFilter ?? null, flagSortingRule: p.setting.flagSortingRule ?? null, commonlyUsedFilters: p.setting.commonlyUsedFilters?.map(x => x.systemFilter) || [], version: p.setting.version?.toString() ?? null };
|
|
30
|
+
}
|
|
31
|
+
async list() { return this.view(await this.raw()); }
|
|
32
|
+
async set({ filter, visibility, position, display, messageTypes, atAll, showFilter, showMuteFilter, flagSortingRule, commonlyUsedFilters }) {
|
|
33
|
+
const id = idFor(filter);
|
|
34
|
+
if (visibility != null && !['show', 'hide'].includes(visibility)) invalid();
|
|
35
|
+
if (position != null && (!Number.isInteger(position) || position < 1)) invalid();
|
|
36
|
+
if (display != null && !Object.hasOwn(rules, display)) invalid();
|
|
37
|
+
if (messageTypes != null && (!Array.isArray(messageTypes) || messageTypes.some(x => !Object.hasOwn(msgTypes, x)) || new Set(messageTypes).size !== messageTypes.length)) invalid();
|
|
38
|
+
if (messageTypes != null && display == null) invalid();
|
|
39
|
+
if (atAll != null && typeof atAll !== 'boolean') invalid();
|
|
40
|
+
if (atAll != null && id !== SIDEBAR_FILTERS.at_me) invalid();
|
|
41
|
+
if ([showFilter, showMuteFilter].some(x => x != null && typeof x !== 'boolean')) invalid();
|
|
42
|
+
if (flagSortingRule != null && (!Number.isInteger(flagSortingRule) || flagSortingRule < 0 || flagSortingRule > 2147483647)) invalid();
|
|
43
|
+
if (commonlyUsedFilters != null && (!Array.isArray(commonlyUsedFilters) || new Set(commonlyUsedFilters.map(idFor)).size !== commonlyUsedFilters.length)) invalid();
|
|
44
|
+
if (visibility == null && position == null && display == null && atAll == null && showFilter == null && showMuteFilter == null && flagSortingRule == null && commonlyUsedFilters == null) invalid();
|
|
45
|
+
const before = await this.raw(), available = new Set([...before.allFilters, ...before.setting.usedFilters].map(x => x.systemFilter));
|
|
46
|
+
if (!available.has(id)) invalid();
|
|
47
|
+
let ids = before.setting.usedFilters.map(x => x.systemFilter);
|
|
48
|
+
if (new Set(ids).size !== ids.length) throw new FeishuError('INVALID_RESPONSE', 'Sidebar order contains duplicates.');
|
|
49
|
+
const fields = [], request = { clientSupportVersion: before.setting.version?.toString() || '0' };
|
|
50
|
+
if (visibility != null || position != null) {
|
|
51
|
+
if (visibility === 'hide') ids = ids.filter(x => x !== id);
|
|
52
|
+
if (visibility === 'show' && !ids.includes(id)) ids.push(id);
|
|
53
|
+
if (position != null) {
|
|
54
|
+
if (!ids.includes(id) || position > ids.length) invalid();
|
|
55
|
+
ids = ids.filter(x => x !== id); ids.splice(position - 1, 0, id);
|
|
56
|
+
}
|
|
57
|
+
request.usedFilters = ids.map(systemFilter => ({ systemFilter })); fields.push(2);
|
|
58
|
+
}
|
|
59
|
+
let selectedMessageTypes;
|
|
60
|
+
if (display != null) {
|
|
61
|
+
selectedMessageTypes = messageTypes ? messageTypes.map(x => msgTypes[x]) : [...(before.setting.filterDisplayFeedRule?.[id]?.msgTypes || [])];
|
|
62
|
+
request.filterDisplayFeedRule = { ...before.setting.filterDisplayFeedRule,
|
|
63
|
+
[id]: { mainRule: rules[display], msgTypes: selectedMessageTypes } }; fields.push(8);
|
|
64
|
+
}
|
|
65
|
+
if (atAll != null) { request.showAtAllInAtFilter = atAll; fields.push(5); }
|
|
66
|
+
if (showFilter != null) { request.showFilter = showFilter; fields.push(1); }
|
|
67
|
+
if (showMuteFilter != null) { request.showMuteFilter = showMuteFilter; fields.push(3); }
|
|
68
|
+
if (flagSortingRule != null) { request.flagSortingRule = flagSortingRule; fields.push(7); }
|
|
69
|
+
if (commonlyUsedFilters != null) { const common = commonlyUsedFilters.map(idFor); if (common.some(x => !available.has(x))) invalid(); request.commonlyUsedFilters = common.map(systemFilter => ({ systemFilter })); fields.push(6); }
|
|
70
|
+
request.updateFields = fields;
|
|
71
|
+
await this.gateway.call(7023, 'PutSidebarFilterSettingRequest', request, { mutating: true, operation: 'sidebar-set' });
|
|
72
|
+
let after; try { after = await this.raw(); } catch { return { status: 'submitted_unconfirmed', filter: id }; }
|
|
73
|
+
const view = this.view(after), item = view.items.find(x => x.id === id);
|
|
74
|
+
const orderOk = !fields.includes(2) || JSON.stringify(after.setting.usedFilters.map(x => x.systemFilter)) === JSON.stringify(ids);
|
|
75
|
+
const displayOk = display == null || (item?.displayRule?.mainRule === rules[display] && JSON.stringify(item.displayRule.msgTypes) === JSON.stringify(selectedMessageTypes));
|
|
76
|
+
const atAllOk = atAll == null || view.showAtAllInAtFilter === atAll;
|
|
77
|
+
const extraOk = (showFilter == null || view.showFilter === showFilter) && (showMuteFilter == null || view.showMuteFilter === showMuteFilter) && (flagSortingRule == null || view.flagSortingRule === flagSortingRule) && (commonlyUsedFilters == null || JSON.stringify(view.commonlyUsedFilters) === JSON.stringify(commonlyUsedFilters.map(idFor)));
|
|
78
|
+
return { status: orderOk && displayOk && atAllOk && extraOk ? 'updated' : 'submitted_unconfirmed', filter: item };
|
|
79
|
+
}
|
|
80
|
+
}
|
package/src/tasks.js
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
2
|
+
import { FeishuError } from './errors.js';
|
|
3
|
+
|
|
4
|
+
const invalid = message => { throw new FeishuError('INVALID_ARGUMENT', message); };
|
|
5
|
+
const scopes = { mine: '__container_owned_tasks', followed: '__container_followed_tasks', all: '__container_all_tasks', created: '__container_created_tasks', assigned: '__container_assigned_tasks', completed: '__container_completed_tasks' };
|
|
6
|
+
const id = value => { if (typeof value !== 'string' || !value || value.length > 256) invalid('A valid task ID is required.'); return value; };
|
|
7
|
+
const stamp = value => {
|
|
8
|
+
if (value == null || value === '') return '0';
|
|
9
|
+
if (typeof value !== 'string' && typeof value !== 'number') invalid('Invalid task time.');
|
|
10
|
+
const text = String(value); const n = /^\d+$/.test(text) ? Number(text) : Date.parse(text);
|
|
11
|
+
if (!Number.isSafeInteger(n) || n < 0) invalid('Task times must be milliseconds or an ISO date.');
|
|
12
|
+
return String(n);
|
|
13
|
+
};
|
|
14
|
+
const isObject = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
15
|
+
function validate(type, object, path = 'input') {
|
|
16
|
+
if (!isObject(object)) invalid(`${path} must be an object.`);
|
|
17
|
+
type.resolveAll();
|
|
18
|
+
for (const [key, value] of Object.entries(object)) {
|
|
19
|
+
const field = type.fields[key]; if (!field) invalid(`Unknown field ${path}.${key}.`);
|
|
20
|
+
const check = item => {
|
|
21
|
+
if (field.resolvedType?.fields) validate(field.resolvedType, item, `${path}.${key}`);
|
|
22
|
+
else if (field.resolvedType?.values && !(typeof item === 'string' && Object.hasOwn(field.resolvedType.values, item)) && !(Number.isInteger(item) && Object.values(field.resolvedType.values).includes(item))) invalid(`Invalid enum ${path}.${key}.`);
|
|
23
|
+
};
|
|
24
|
+
if (field.map) { if (!isObject(value)) invalid(`${path}.${key} must be an object.`); Object.values(value).forEach(check); }
|
|
25
|
+
else if (field.repeated) { if (!Array.isArray(value)) invalid(`${path}.${key} must be an array.`); value.forEach(check); }
|
|
26
|
+
else check(value);
|
|
27
|
+
}
|
|
28
|
+
const message = type.fromObject(object); const error = type.verify(message); if (error) invalid(`${path}: ${error}`);
|
|
29
|
+
}
|
|
30
|
+
export class Tasks {
|
|
31
|
+
constructor(gateway) { this.gateway = gateway; }
|
|
32
|
+
async call(command, request, data, response, write = false, operation = 'task') {
|
|
33
|
+
const result = await this.gateway.call(command, `todo.${request}`, data, { mutating: write, operation });
|
|
34
|
+
return result.packet.payload?.length ? this.gateway.decode(`todo.${response}`, result.packet.payload) : null;
|
|
35
|
+
}
|
|
36
|
+
async center() { const r = await this.call(1050400, 'GetTaskCenterRequest', {}, 'GetTaskCenterResponse'); if (!r) throw new FeishuError('INVALID_RESPONSE', 'Task center was not returned.'); return { containers: r.containers, views: r.views, sections: r.sections, taskContainerSectionData: r.taskContainerSectionData }; }
|
|
37
|
+
async get({ taskId }) { const task = (await this.call(1050007, 'MGetTodoByGuidRequest', { guids: [id(taskId)] }, 'MGetTodoByGuidResponse'))?.guidToTodo?.[taskId]; if (!task) throw new FeishuError('NOT_FOUND', 'Task was not found or is inaccessible.'); return { task }; }
|
|
38
|
+
async list({ scope = 'mine', container, limit = 50, cursor } = {}) {
|
|
39
|
+
if ((!container && !Object.hasOwn(scopes, scope)) || (container != null && (typeof container !== 'string' || !container)) || !Number.isInteger(limit) || limit < 1 || limit > 100) invalid('Invalid task list options.');
|
|
40
|
+
const center = await this.center(); const selected = center.containers.find(x => container ? x.guid === container : x.key === scopes[scope]);
|
|
41
|
+
if (!selected) throw new FeishuError('NOT_FOUND', 'Task container was not returned by task center.');
|
|
42
|
+
const view = center.views.find(x => x.containerGuid === selected.guid || x.containerKey === selected.key);
|
|
43
|
+
const response = await this.call(1051103, 'GetContainerGroupInfoRequest', { containerGuid: selected.guid,
|
|
44
|
+
...(view?.viewGroups ? { viewGroups: view.viewGroups } : {}), ...(view?.viewSorts ? { viewSorts: view.viewSorts } : {}),
|
|
45
|
+
...(view?.viewFilters ? { viewFilters: view.viewFilters } : {}), timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC', nextCount: 1 }, 'GetContainerGroupInfoResponse');
|
|
46
|
+
if (!response) throw new FeishuError('INVALID_RESPONSE', 'Task list was not returned.');
|
|
47
|
+
const entries = response.groupDataList.flatMap(group => group.taskSortedInfos.map(info => ({ guid: info.taskGuid || info.guid, groupId: String(group.groupId) }))).filter(x => x.guid);
|
|
48
|
+
const digest = createHash('sha256').update(JSON.stringify(entries.map(x => x.guid))).digest('base64url'); let offset = 0;
|
|
49
|
+
if (cursor) { let parsed; try { parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString()); } catch { invalid('Invalid task cursor.'); }
|
|
50
|
+
if (parsed.container !== selected.guid || parsed.digest !== digest || !Number.isSafeInteger(parsed.offset) || parsed.offset < 0 || parsed.offset > entries.length) throw new FeishuError('CURSOR_EXPIRED', 'Task list changed; restart pagination.'); offset = parsed.offset; }
|
|
51
|
+
const page = entries.slice(offset, offset + limit); const fetched = page.length ? await this.call(1051104, 'MGetServerContainerTasksRequest', { containerGuid: selected.guid, taskGuids: page.map(x => x.guid) }, 'MGetServerContainerTasksResponse') : { tasks: [] };
|
|
52
|
+
if (!fetched) throw new FeishuError('INVALID_RESPONSE', 'Task details were not returned.');
|
|
53
|
+
const byId = new Map(fetched.tasks.map(x => [x.task?.guid, x.task]));
|
|
54
|
+
return { container: selected, items: page.filter(x => byId.has(x.guid)).map(x => ({ task: byId.get(x.guid), groupId: x.groupId })), missing: page.filter(x => !byId.has(x.guid)).map(x => x.guid), total: entries.length,
|
|
55
|
+
groups: response.groupDataList.map(g => ({ id: String(g.groupId), info: g.groupInfos })), serverReportedAllTasks: response.isAllTask,
|
|
56
|
+
nextCursor: offset + page.length < entries.length ? Buffer.from(JSON.stringify({ container: selected.guid, digest, offset: offset + page.length })).toString('base64url') : null };
|
|
57
|
+
}
|
|
58
|
+
async search({ query, limit = 20, cursor } = {}) { if (typeof query !== 'string' || !query.trim() || !Number.isInteger(limit) || limit < 1 || limit > 100 || (cursor != null && typeof cursor !== 'string')) invalid('Invalid task search.');
|
|
59
|
+
const r = await this.call(1050031, 'SearchTaskRequest', { query, count: limit, ...(cursor ? { token: cursor } : {}) }, 'SearchTaskResponse');
|
|
60
|
+
if (!r || (r.hasMore && !r.token)) throw new FeishuError('INVALID_RESPONSE', 'Task search pagination was incomplete.'); return { items: r.todos, nextCursor: r.hasMore ? r.token : null }; }
|
|
61
|
+
rich(text) { if (typeof text !== 'string') invalid('Task text must be a string.'); const element = randomUUID(); return { richText: { elementIds: [element], innerText: text, elements: { dictionary: { [element]: { tag: 1, property: this.gateway.encode('TextProperty', { content: text }) } } } } }; }
|
|
62
|
+
async create({ input = {}, title, description, start, due, allDay, assignees, followers, repeat, lists, points } = {}) {
|
|
63
|
+
if (!isObject(input)) invalid('Task input must be an object.'); await this.gateway.authenticate(); await this.gateway.ensureTodoProto();
|
|
64
|
+
const task = { ...input, guid: input.guid || randomUUID() };
|
|
65
|
+
if (title != null) task.richSummary = this.rich(title); if (description != null) task.richDescription = this.rich(description);
|
|
66
|
+
if (!task.richSummary) invalid('A task title or richSummary is required.');
|
|
67
|
+
if (start != null) task.startMilliTime = stamp(start); if (due != null) task.dueMilliTime = stamp(due); if (allDay != null) task.isAllDay = allDay;
|
|
68
|
+
if (assignees?.length) task.assignees = assignees.map(memberId => ({ memberId: id(memberId), type: 1 }));
|
|
69
|
+
if (followers?.length) task.followers = followers.map(memberId => ({ memberId: id(memberId), type: 1 }));
|
|
70
|
+
if (repeat != null) task.rrule = repeat; if (lists?.length) task.taskListContainerRefs = lists.map(containerGuid => ({ containerGuid: id(containerGuid) })); if (points != null) task.points = points;
|
|
71
|
+
validate(this.gateway.todoProto.lookupType('todo_entities.InputTask'), task);
|
|
72
|
+
const result = await this.call(1050030, 'CreateTaskRequest', { tasks: [task] }, 'CreateTaskResponse', true, 'task-create');
|
|
73
|
+
if (!result) return { status: 'submitted_unconfirmed', taskId: task.guid };
|
|
74
|
+
return { status: result.success && result.tasks.some(x => x.guid === task.guid) ? 'created' : 'rejected_or_unconfirmed', taskId: task.guid, tasks: result.tasks, failReasons: result.failReasons, taskContainerRefReject: result.taskContainerRefReject };
|
|
75
|
+
}
|
|
76
|
+
async update({ taskId, patch = {}, commits = [] } = {}) {
|
|
77
|
+
id(taskId); if (!isObject(patch) || !Array.isArray(commits)) invalid('Invalid task update.');
|
|
78
|
+
const allowed = ['title','description','start','due','allDay','repeat','points','milestone','addAssignees','removeAssignees','addFollowers','removeFollowers'];
|
|
79
|
+
if (Object.keys(patch).some(k => !allowed.includes(k))) invalid('Unknown task update field.');
|
|
80
|
+
const current = (await this.get({ taskId })).task, user = await this.gateway.authenticate(), changes = [];
|
|
81
|
+
const add = (key, dataType, added, deleted) => changes.push({ key, dataType, ...(added ? { added } : {}), ...(deleted ? { deleted } : {}) });
|
|
82
|
+
for (const [name,key] of [['title',17],['description',18]]) if (patch[name] != null) add(key, 5, this.gateway.encode('todo_entities.RichContent', this.rich(patch[name])));
|
|
83
|
+
if (['start','due','allDay'].some(k => patch[k] != null)) add(34, 9, this.gateway.encode('todo_entities.Commit.DataTypeStartAndDueTime', { startTime: patch.start != null ? stamp(patch.start) : String(current.startTime || 0), dueTime: patch.due != null ? stamp(patch.due) : String(current.dueTime || 0), isAllDay: patch.allDay ?? current.isAllDay }));
|
|
84
|
+
for (const [name,key] of [['repeat',26],['points',37]]) if (patch[name] != null) { if (typeof patch[name] !== 'string') invalid('Task field must be a string.'); add(key, 3, this.gateway.encode('todo_entities.Commit.DataTypeString', { value: patch[name] })); }
|
|
85
|
+
if (patch.milestone != null) { if (typeof patch.milestone !== 'boolean') invalid('Milestone must be a boolean.'); add(35, 4, this.gateway.encode('todo_entities.Commit.DataTypeBool', { value: patch.milestone })); }
|
|
86
|
+
for (const [kind,key,type,prop] of [['Assignees',5,'TodoAssignee','assigneeId'],['Followers',20,'TodoFollower','followerId']]) {
|
|
87
|
+
const plus = patch[`add${kind}`] || [], minus = patch[`remove${kind}`] || []; if (!Array.isArray(plus) || !Array.isArray(minus)) invalid('Task members must be arrays.');
|
|
88
|
+
const values = plus.map(member => this.gateway.encode(`todo_entities.${type}`, kind === 'Assignees' ? { id: randomUUID(), assigneeId: id(member), type: 1, assignerId: user.id } : { followerId: id(member), type: 1, inviterId: user.id }));
|
|
89
|
+
const existing = current[kind.toLowerCase()] || []; const deleted = minus.map(member => { id(member); const item = existing.find(x => x[prop] === member); if (!item) invalid(`Member ${member} is not on the task.`); return this.gateway.encode(`todo_entities.${type}`, item); });
|
|
90
|
+
if (values.length || deleted.length) add(key, 6, values.length ? this.gateway.encode('todo_entities.Commit.DataTypeVec', { values }) : null, deleted.length ? this.gateway.encode('todo_entities.Commit.DataTypeVec', { values: deleted }) : null);
|
|
91
|
+
}
|
|
92
|
+
for (const change of commits) { if (!isObject(change) || Object.keys(change).some(k => !['key','dataType','added','deleted'].includes(k))) invalid('Advanced commits accept key, dataType, added and deleted.'); changes.push(change); }
|
|
93
|
+
if (!changes.length) invalid('No task changes were supplied.');
|
|
94
|
+
const enveloped = changes.map(change => ({ ...change, guid: randomUUID(), objType: 1, objGuid: taskId, clientMilliTime: String(Date.now()), platform: 6, ownerType: 1, ownerId: user.id, operationGuid: randomUUID() }));
|
|
95
|
+
for (const commit of enveloped) validate(this.gateway.todoProto.lookupType('todo_entities.Commit'), commit, 'commit');
|
|
96
|
+
let applied = 0, refused = 0, task = null;
|
|
97
|
+
for (const commit of enveloped) {
|
|
98
|
+
let result;
|
|
99
|
+
try { result = await this.call(1050032, 'UpdateTaskByCommitsRequest', { taskGuid: taskId, commits: [commit] }, 'UpdateTaskByCommitsResponse', true, 'task-update'); }
|
|
100
|
+
catch (error) { if (!applied) throw error; return { status: 'partially_applied_effect_unknown', taskId, applied, refused, error: { code: error.code || 'ERROR', message: error.message } }; }
|
|
101
|
+
if (!result) return { status: 'submitted_unconfirmed', taskId, applied, refused };
|
|
102
|
+
applied += result.appliedCommits.length; refused += result.refusedCommits.length; task = result.task || task;
|
|
103
|
+
if (result.refusedCommits.length || !result.appliedCommits.length) break;
|
|
104
|
+
}
|
|
105
|
+
return { status: refused ? 'partially_rejected' : applied === changes.length ? 'updated' : 'submitted_unconfirmed', taskId, applied, refused, task };
|
|
106
|
+
}
|
|
107
|
+
async complete({ taskId, completed, assignees = [] }) { id(taskId); if (typeof completed !== 'boolean' || !Array.isArray(assignees)) invalid('Invalid completion options.');
|
|
108
|
+
await this.call(1050103, 'UpdateTodoCompleteStatusRequest', { todoGuid: taskId, isCompleted: completed, assigneeIds: assignees.map(id) }, 'UpdateTodoCompleteStatusResponse', true, completed ? 'task-complete' : 'task-reopen');
|
|
109
|
+
try { const { task } = await this.get({ taskId }); return { status: (BigInt(String(task.completedMilliTime || 0)) > 0n) === completed ? 'updated' : 'submitted_unconfirmed', task }; } catch { return { status: 'submitted_unconfirmed', taskId }; } }
|
|
110
|
+
async delete({ taskId }) { id(taskId); await this.call(1050101, 'DeleteTodosRequest', { todoGuids: [taskId] }, 'DeleteTodosResponse', true, 'task-delete');
|
|
111
|
+
try { const { task } = await this.get({ taskId }); return { status: BigInt(String(task.deletedMilliTime || 0)) > 0n ? 'deleted' : 'submitted_unconfirmed', taskId }; } catch (e) { return { status: e.code === 'NOT_FOUND' ? 'deleted' : 'submitted_unconfirmed', taskId }; } }
|
|
112
|
+
}
|