Skip to content

Commit 329a014

Browse files
author
linyuan.yang
committed
整理 sendmessage sendfile
1 parent 0ff4e93 commit 329a014

22 files changed

Lines changed: 355 additions & 189 deletions

File tree

‎packages/channel.base/src/ChannelPlugin.ts‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,26 @@ import { type MessageContent } from "scorpio.ai";
22
import { ChannelSessionHandler } from "./ChannelSessionHandler";
33
import { SessionService } from "./SessionService";
44

5+
/** Capability tokens advertised by a running IChannelService instance. Mirrors which optional send methods are implemented. */
6+
export enum ChannelCapability {
7+
Text = 'text',
8+
File = 'file',
9+
TextUser = 'text_user',
10+
FileUser = 'file_user',
11+
}
12+
513
export interface IChannelService {
614
createSessionHandler(session: SessionService): ChannelSessionHandler;
7-
sendText(sessionId: string, text: string): Promise<void>;
8-
sendFile(sessionId: string, file: string | Buffer, fileName?: string): Promise<void>;
9-
sendNative(sessionId: string, payload: any): Promise<void>;
15+
/**
16+
* All four send methods are optional. Implement only what the underlying platform
17+
* actually supports — leave the rest off so callers (e.g. channel_list_data, Tools)
18+
* can advertise real capabilities and avoid silent no-ops.
19+
* `userId` in *ToUser variants is the channel-native id (e.g. open_id, qq, userid).
20+
*/
21+
sendTextToSession?(sessionId: string, text: string): Promise<void>;
22+
sendFileToSession?(sessionId: string, file: string | Buffer, fileName?: string): Promise<void>;
23+
sendTextToUser?(userId: string, text: string): Promise<void>;
24+
sendFileToUser?(userId: string, file: string | Buffer, fileName?: string): Promise<void>;
1025
dispose(): void;
1126
}
1227

‎packages/channel.lark/src/LarkService.ts‎

Lines changed: 8 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -96,19 +96,6 @@ export interface LarkHistoryMessage {
9696
content: MessageContent;
9797
}
9898

99-
export interface LarkChatListItem {
100-
chat_id: string;
101-
avatar?: string;
102-
name?: string;
103-
description?: string;
104-
owner_id?: string;
105-
owner_id_type?: string;
106-
external?: boolean;
107-
tenant_key?: string;
108-
labels?: string[];
109-
chat_status?: 'normal' | 'dissolved' | 'dissolved_save';
110-
}
111-
11299
export interface LarkServiceOptions {
113100
appId: string;
114101
appSecret: string;
@@ -161,17 +148,20 @@ export class LarkService implements IChannelService {
161148
return new LarkSessionHandler(session, this);
162149
}
163150

164-
async sendText(sessionId: string, text: string): Promise<void> {
151+
async sendTextToSession(sessionId: string, text: string): Promise<void> {
165152
await this.sendMarkdownMessage(LarkReceiveIdType.ChatId, sessionId, text);
166153
}
167154

168-
async sendFile(sessionId: string, file: string | Buffer, fileName?: string): Promise<void> {
155+
async sendFileToSession(sessionId: string, file: string | Buffer, fileName?: string): Promise<void> {
169156
await this.sendFileMessage(LarkReceiveIdType.ChatId, sessionId, file, fileName);
170157
}
171158

172-
async sendNative(sessionId: string, payload: any): Promise<void> {
173-
const content = typeof payload === 'string' ? payload : JSON.stringify(payload);
174-
await this.sendMessage(LarkReceiveIdType.ChatId, sessionId, 'interactive', content);
159+
async sendTextToUser(userId: string, text: string): Promise<void> {
160+
await this.sendMarkdownMessage(this.userIdType as unknown as LarkReceiveIdType, userId, text);
161+
}
162+
163+
async sendFileToUser(userId: string, file: string | Buffer, fileName?: string): Promise<void> {
164+
await this.sendFileMessage(this.userIdType as unknown as LarkReceiveIdType, userId, file, fileName);
175165
}
176166

177167
dispose() {
@@ -341,51 +331,6 @@ export class LarkService implements IChannelService {
341331
}
342332
}
343333

344-
/** https://open.feishu.cn/document/server-docs/group/chat/list */
345-
async getChatList(options?: {
346-
limit?: number;
347-
sortType?: 'ByCreateTimeAsc' | 'ByActiveTimeDesc';
348-
filter?: (chat: any) => boolean;
349-
}): Promise<{ items: LarkChatListItem[]; hasMore: boolean }> {
350-
const limit = options?.limit ?? 100;
351-
let currentPage: any;
352-
let currentItem: any;
353-
try {
354-
const iter = await this.larkClient.im.v1.chat.listWithIterator({
355-
params: {
356-
user_id_type: this.userIdType as any,
357-
sort_type: options?.sortType ?? 'ByActiveTimeDesc',
358-
},
359-
});
360-
const items: LarkChatListItem[] = [];
361-
for await (const page of iter) {
362-
currentPage = page;
363-
for (const item of page?.items ?? []) {
364-
currentItem = item;
365-
if (item.chat_status && item.chat_status !== 'normal') continue;
366-
if (options?.filter && !options.filter(item)) continue;
367-
items.push({
368-
chat_id: item.chat_id ?? '',
369-
avatar: item.avatar,
370-
name: item.name,
371-
description: item.description,
372-
owner_id: item.owner_id,
373-
owner_id_type: item.owner_id_type,
374-
external: item.external,
375-
tenant_key: item.tenant_key,
376-
labels: item.labels,
377-
chat_status: item.chat_status,
378-
});
379-
if (items.length >= limit) return { items, hasMore: true };
380-
}
381-
}
382-
return { items, hasMore: false };
383-
} catch (error: any) {
384-
this.logger?.error(`Error getting chat list: ${error.message}\n${error.stack}\ncurrentItem: ${JSON.stringify(currentItem, null, 2)}\ncurrentPage: ${JSON.stringify(currentPage, null, 2)}`);
385-
return { items: [], hasMore: false };
386-
}
387-
}
388-
389334
private async getTenantAccessToken(): Promise<string> {
390335
if (this.tenantAccessToken && NowDate() < this.tokenExpireTime) {
391336
return this.tenantAccessToken;

‎packages/channel.lark/src/LarkSessionHandler.ts‎

Lines changed: 1 addition & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { LarkChatType, LarkReceiveIdType, LarkService } from "./LarkService";
33
import { DynamicStructuredTool } from "@langchain/core/tools";
44
import { z } from "zod";
55
import {
6-
ChannelSessionHandler, ToolCallStatus, SessionService, createAskTool, createSendFileTool,
6+
ChannelSessionHandler, ToolCallStatus, SessionService, createAskTool,
77
GlobalLoggerService, AskQuestionType, summarizeMultimodal, AgentCancelledError, ToolApproval,
88
type StructuredToolInterface,
99
type ChannelMessageArgs, type ChatMessage, type ChatToolCall, type AskToolParams, type MessageType, type MessageContent,
@@ -224,55 +224,11 @@ Question types:
224224
- input: free-text entry with an optional placeholder
225225
226226
Returns a map of question label → answer (string for radio/input, string[] for checkbox).`;
227-
static readonly SEND_FILE_PROMPT = 'Send a local file to the current Lark conversation. Use this tool to deliver any generated or exported file (documents, archives, reports, images, etc.) directly to the user via Lark.';
228227

229228
buildAgentTools(args: ChannelMessageArgs): StructuredToolInterface[] {
230229
const { sessionId, userOpenId } = args as LarkMessageArgs;
231230
return [
232231
createAskTool((params: AskToolParams) => this.executeAsk(params), LarkSessionHandler.ASK_PROMPT, [AskQuestionType.Radio, AskQuestionType.Checkbox, AskQuestionType.Input]),
233-
createSendFileTool(LarkSessionHandler.SEND_FILE_PROMPT, async (filePath: string, fileName: string) => {
234-
await this.larkService.sendFileMessage(LarkReceiveIdType.ChatId, sessionId, filePath, fileName);
235-
}),
236-
new DynamicStructuredTool({
237-
name: '_send_message',
238-
description: 'Send a message to a Lark chat or user. By default sends to the current conversation. Can also target a different chat_id or user (by union_id).',
239-
schema: z.object({
240-
content: z.string().describe('The message content in Markdown format.'),
241-
receive_id: z.string().optional().describe('Target receive ID (chat_id or union_id). Defaults to the current chat.'),
242-
receive_id_type: z.enum(['chat_id', 'union_id']).optional().describe('Type of receive_id. Defaults to "chat_id".'),
243-
}),
244-
func: async ({ content, receive_id, receive_id_type }) => {
245-
const targetId = receive_id || sessionId;
246-
const idType = (receive_id_type || 'chat_id') as LarkReceiveIdType;
247-
try {
248-
await this.larkService.sendMarkdownMessage(idType, targetId, content);
249-
return `<send-message status="success" receive_id="${targetId}" receive_id_type="${idType}" />`;
250-
} catch (e: any) {
251-
return `<send-message status="failed" receive_id="${targetId}" receive_id_type="${idType}" error="${(e?.message ?? String(e)).replace(/"/g, '&quot;')}" />`;
252-
}
253-
},
254-
}),
255-
new DynamicStructuredTool({
256-
name: '_get_chat_list',
257-
description: 'List all Lark groups the bot has joined. Returns chat_id, name, description, and other metadata for each group. Useful for broadcasting or for the user to pick a target chat.',
258-
schema: z.object({
259-
limit: z.number().optional().describe('Max number of chats to return (default 100).'),
260-
sort_type: z.enum(['ByCreateTimeAsc', 'ByActiveTimeDesc']).optional().describe('Sort order. Defaults to "ByActiveTimeDesc".'),
261-
name_keyword: z.string().optional().describe('If set, only return chats whose name contains this substring (case-insensitive).'),
262-
}),
263-
func: async ({ limit, sort_type, name_keyword }) => {
264-
const kw = name_keyword?.toLowerCase();
265-
const { items, hasMore } = await this.larkService.getChatList({
266-
limit,
267-
sortType: sort_type,
268-
filter: kw ? (c) => (c.name ?? '').toLowerCase().includes(kw) : undefined,
269-
});
270-
const lines = items.map((c) =>
271-
`<chat id="${c.chat_id}" name="${c.name ?? ''}" external="${c.external ?? false}">${c.description ?? ''}</chat>`
272-
);
273-
return `<chat-list count="${items.length}" has_more="${hasMore}">\n${lines.join('\n')}\n</chat-list>`;
274-
},
275-
}),
276232
new DynamicStructuredTool({
277233
name: '_get_message_history',
278234
description: 'Retrieve message history from the current Lark chat in reverse chronological order (newest first). To paginate older messages, pass the previous response\'s "oldest_time" attribute as the next call\'s "end_time".',

‎packages/channel.lark/src/plugin.ts‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,7 @@ export const larkPlugin: ChannelPlugin = {
2626

2727
tools: [
2828
{ name: '_ask', label: '询问用户' },
29-
{ name: '_send_file', label: '发送文件' },
30-
{ name: '_send_message', label: '发送消息' },
3129
{ name: '_get_message_history', label: '获取消息历史' },
32-
{ name: '_get_chat_list', label: '获取群组列表' },
3330
],
3431

3532
async init(ctx: ChannelPluginContext): Promise<IChannelService | undefined> {

‎packages/channel.onebot/src/OnebotService.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,13 +56,13 @@ export class OnebotService implements IChannelService {
5656
return { userId: Number(parts[2]) };
5757
}
5858

59-
async sendText(sessionId: string, text: string): Promise<void> {
59+
async sendTextToSession(sessionId: string, text: string): Promise<void> {
6060
await this.sendTextMessage(this.parseSessionTarget(sessionId), text);
6161
}
6262

63-
async sendFile(_sessionId: string, _file: string | Buffer, _fileName?: string): Promise<void> {}
64-
65-
async sendNative(_sessionId: string, _payload: any): Promise<void> {}
63+
async sendTextToUser(userId: string, text: string): Promise<void> {
64+
await this.sendTextMessage({ userId: Number(userId) }, text);
65+
}
6666

6767
dispose() {
6868
for (const ws of this.connections) {

‎packages/channel.slack/src/SlackService.ts‎

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -40,20 +40,10 @@ export class SlackService implements IChannelService {
4040
return new SlackSessionHandler(session, this);
4141
}
4242

43-
async sendText(sessionId: string, text: string): Promise<void> {
43+
async sendTextToSession(sessionId: string, text: string): Promise<void> {
4444
await this.sendMessage(sessionId, text);
4545
}
4646

47-
async sendFile(_sessionId: string, _file: string | Buffer, _fileName?: string): Promise<void> {}
48-
49-
async sendNative(sessionId: string, payload: any): Promise<void> {
50-
await this.app.client.chat.postMessage({
51-
channel: sessionId,
52-
text: payload.text ?? '',
53-
...(payload.blocks ? { blocks: payload.blocks } : {}),
54-
});
55-
}
56-
5747
dispose() {
5848
this.app.stop().catch(() => {});
5949
}

‎packages/channel.wechat/src/WechatService.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,16 +53,14 @@ export class WechatService implements IChannelService {
5353
return new WechatSessionHandler(session, this);
5454
}
5555

56-
async sendText(sessionId: string, text: string): Promise<void> {
56+
async sendTextToSession(sessionId: string, text: string): Promise<void> {
5757
await this.sendTextMessage(sessionId, text);
5858
}
5959

60-
async sendFile(sessionId: string, file: string | Buffer, fileName?: string): Promise<void> {
60+
async sendFileToSession(sessionId: string, file: string | Buffer, fileName?: string): Promise<void> {
6161
await this.sendFileMessage(sessionId, file, fileName);
6262
}
6363

64-
async sendNative(_sessionId: string, _payload: any): Promise<void> {}
65-
6664
dispose(): void {
6765
this._running = false;
6866
this._abortController?.abort();

‎packages/channel.wecom/src/WecomService.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,16 +58,20 @@ export class WecomService implements IChannelService {
5858
return new WecomSessionHandler(session, this);
5959
}
6060

61-
async sendText(sessionId: string, text: string): Promise<void> {
61+
async sendTextToSession(sessionId: string, text: string): Promise<void> {
6262
await this.sendMessage(sessionId, { msgtype: 'markdown', markdown: { content: text } } as any);
6363
}
6464

65-
async sendFile(sessionId: string, file: string | Buffer, fileName?: string): Promise<void> {
65+
async sendFileToSession(sessionId: string, file: string | Buffer, fileName?: string): Promise<void> {
6666
await this.sendFileMessage(sessionId, file, fileName);
6767
}
6868

69-
async sendNative(sessionId: string, payload: any): Promise<void> {
70-
await this.sendMessage(sessionId, payload);
69+
async sendTextToUser(userId: string, text: string): Promise<void> {
70+
await this.sendMessage(userId, { msgtype: 'markdown', markdown: { content: text } } as any);
71+
}
72+
73+
async sendFileToUser(userId: string, file: string | Buffer, fileName?: string): Promise<void> {
74+
await this.sendFileMessage(userId, file, fileName);
7175
}
7276

7377
dispose() {

‎packages/channel.xiaoai/src/XiaoaiService.ts‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,15 +43,13 @@ export class XiaoaiService implements IChannelService {
4343
return new XiaoaiSessionHandler(session, this);
4444
}
4545

46-
async sendText(_sessionId: string, text: string): Promise<void> {
46+
async sendTextToSession(_sessionId: string, text: string): Promise<void> {
4747
if (!this.authed || !this.deviceId) return;
4848
await speak(this.authed, this.deviceId, text, {
4949
chunkLimit: this.options.textChunkLimit,
5050
volume: this.options.volume,
5151
});
5252
}
53-
async sendFile(_sessionId: string, _file: string | Buffer, _fileName?: string): Promise<void> {}
54-
async sendNative(_sessionId: string, _payload: any): Promise<void> {}
5553

5654
getAuthedAccount(): AuthedAccount | undefined {
5755
return this.authed;
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
Discover channels, sessions, and users known to this bot. Reads from the bot's local config / database — no platform API permission required.
2+
3+
- type="channel": list all configured channels (id, type, name, caps). channel_id is ignored.
4+
- type="session": list sessions in channel_id; defaults to all channels. Entries with current="1" are on the same channel as the current conversation — prefer them when names collide.
5+
- type="user": list users in channel_id; defaults to all channels.
6+
- type="session_and_user": list both sessions and users (under the same channel_id / name_pattern filter) in a single call. Use when you don't yet know whether to address a session or a user.
7+
8+
caps (only on <channel>) is a comma-separated capability set. Tokens:
9+
text — channel_send_message works on sessions of this channel
10+
file — channel_send_file works on sessions of this channel
11+
text_user — direct text to a user is supported on this channel
12+
file_user — direct file to a user is supported on this channel
13+
A token NOT listed means the corresponding call will fail; do not attempt it.
14+
Empty caps usually means the channel is configured but not currently running.
15+
A <session>/<user> inherits caps from its channel — list type="channel" first when you need to verify capability.
16+
17+
Note: sessions/users only include those the bot has actually interacted with (or that an admin has manually registered).
18+
19+
Use this tool to discover ids to pass into channel_send_message / channel_send_file.

0 commit comments

Comments
 (0)