Skip to content

Commit 5bdda6b

Browse files
author
linyuan.yang
committed
整理 sendmessage sendfile
1 parent 59a84d9 commit 5bdda6b

8 files changed

Lines changed: 92 additions & 77 deletions

File tree

0 Bytes
Binary file not shown.

‎packages/chat-ui/src/components/MessageList.vue‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -518,6 +518,8 @@ function isEmbeddedTool(msg: StoredMessage): boolean {
518518
color: var(--chatui-fg-secondary);
519519
}
520520
:deep(.tool-result-content) { font-size: 12px; }
521+
/* Preserve whitespace so XML-like tool payloads keep indentation/newlines. */
522+
:deep(.tool-result-content p) { white-space: pre-wrap; }
521523
522524
/* Think toggle */
523525
.think-toggle {

‎packages/chat-ui/src/messageRender.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,30 @@ import type { DisplayPart, DisplayContent } from './types'
55

66
const pad2 = (n: number) => n.toString().padStart(2, '0')
77

8+
const KNOWN_HTML_TAGS = new Set([
9+
'a', 'abbr', 'address', 'article', 'aside', 'b', 'bdi', 'bdo', 'blockquote', 'br',
10+
'caption', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'details', 'dfn',
11+
'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'footer', 'h1', 'h2', 'h3',
12+
'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'i', 'img', 'input', 'ins', 'kbd',
13+
'li', 'main', 'mark', 'nav', 'ol', 'p', 'picture', 'pre', 'q', 'rp', 'rt',
14+
'ruby', 's', 'samp', 'section', 'small', 'source', 'span', 'strong', 'sub',
15+
'summary', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'time',
16+
'tr', 'u', 'ul', 'var', 'wbr',
17+
])
18+
19+
/**
20+
* Escape `<` of any tag whose name is not a known HTML element so XML-like
21+
* payloads (e.g. tool outputs containing `<channels>` or `<aaa />`) survive
22+
* marked + DOMPurify and render as literal text instead of being stripped.
23+
* Auto-link forms like `<https://x>` are left alone via the `[\s/>]` lookahead.
24+
*/
25+
function escapeUnknownHtmlTags(text: string): string {
26+
return text.replace(/<(\/?)([a-zA-Z][a-zA-Z0-9-]*)(?=[\s/>])/g, (match, slash, tagName) => {
27+
if (KNOWN_HTML_TAGS.has(tagName.toLowerCase())) return match
28+
return `&lt;${slash}${tagName}`
29+
})
30+
}
31+
832
function dataUrl(mime: string | undefined, base64: string | undefined): string | null {
933
if (!mime || !base64) return null
1034
return `data:${mime};base64,${base64}`
@@ -65,7 +89,7 @@ export function renderMd(content: DisplayContent | null | undefined): string {
6589
.map((c) => (typeof c === 'string' ? c : c?.type === 'text' ? (c.text ?? '') : ''))
6690
.filter(Boolean)
6791
.join('\n')
68-
const html = marked.parse(text) as string
92+
const html = marked.parse(escapeUnknownHtmlTags(text)) as string
6993
return DOMPurify.sanitize(html)
7094
}
7195

‎packages/sbot/prompts/tools/channel/list.txt‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,25 @@
11
Discover channels, sessions, and users known to this bot. Reads from the bot's local config / database — no platform API permission required.
22

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.
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.
3+
Always returns ALL configured channels nested as <channels><channel>...</channel></channels>. The `type` parameter controls which children are emitted directly under each <channel>:
74

8-
current="1" on a <session>/<user> means the entry lives on the same channel that THIS conversation is happening on — e.g. if the user is talking to you via Lark right now, every Lark session/user gets current="1". When the user mentions a name without specifying which channel and the name exists on multiple channels, prefer the current="1" entry — it's almost always what they meant.
5+
- type="channel": no children — channel metadata only.
6+
- type="session": <session> rows under each <channel>.
7+
- type="user": <user> rows under each <channel>.
8+
- type="session_and_user": both. Use when you don't yet know whether to address a session or a user.
99

10-
caps (only on <channel>) is a comma-separated capability set. Tokens:
10+
A <channel> with no matching children is rendered self-closing.
11+
12+
current="1" on a <channel> marks the channel that THIS conversation is happening on. When the user mentions a session/user name without specifying which channel and the name exists on multiple channels, prefer the entry under current="1" — it's almost always what they meant.
13+
14+
Each <session>/<user> exposes only `id` and `name`. Pass that `id` directly to channel_send_message / channel_send_file — it is globally unique across channels. The owning channel (and its caps) is whichever <channel> the row sits under.
15+
16+
caps (on <channel>) is a comma-separated capability set. Tokens:
1117
text — channel_send_message works on sessions of this channel
1218
file — channel_send_file works on sessions of this channel
1319
text_user — direct text to a user is supported on this channel
1420
file_user — direct file to a user is supported on this channel
1521
A token NOT listed means the corresponding call will fail; do not attempt it.
1622
Empty caps usually means the channel is configured but not currently running.
17-
A <session>/<user> inherits caps from its channel — list type="channel" first when you need to verify capability.
1823

1924
Note: sessions/users only include those the bot has actually interacted with (or that an admin has manually registered).
2025

‎packages/sbot/src/Channel/ChannelManager.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ export class ChannelManager {
238238
}
239239
}
240240

241-
async sendTextToDbUser(dbUserId: number, text: string): Promise<boolean> {
241+
async sendTextToUser(dbUserId: number, text: string): Promise<boolean> {
242242
try {
243243
const row = await database.findOne<ChannelUserRow>(database.channelUser, { where: { id: dbUserId } });
244244
if (!row) return false;
@@ -247,12 +247,12 @@ export class ChannelManager {
247247
await service.sendTextToUser(row.userId, text);
248248
return true;
249249
} catch (e) {
250-
logger.warn(`sendTextToDbUser(${dbUserId}) failed: ${e}`);
250+
logger.warn(`sendTextToUser(${dbUserId}) failed: ${e}`);
251251
return false;
252252
}
253253
}
254254

255-
async sendFileToDbUser(dbUserId: number, file: string | Buffer, fileName?: string): Promise<boolean> {
255+
async sendFileToUser(dbUserId: number, file: string | Buffer, fileName?: string): Promise<boolean> {
256256
try {
257257
const row = await database.findOne<ChannelUserRow>(database.channelUser, { where: { id: dbUserId } });
258258
if (!row) return false;
@@ -261,7 +261,7 @@ export class ChannelManager {
261261
await service.sendFileToUser(row.userId, file, fileName);
262262
return true;
263263
} catch (e) {
264-
logger.warn(`sendFileToDbUser(${dbUserId}) failed: ${e}`);
264+
logger.warn(`sendFileToUser(${dbUserId}) failed: ${e}`);
265265
return false;
266266
}
267267
}

‎packages/sbot/src/Tools/Channel/list.ts‎

Lines changed: 45 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
import { DynamicStructuredTool, type StructuredToolInterface } from '@langchain/core/tools';
22
import { z } from 'zod';
33
import { createTextContent, createErrorResult, createSuccessResult, type MCPToolResult } from 'scorpio.ai';
4-
import { channelDataService } from '../../Session/ChannelDataService';
4+
import { channelDataService, type ChannelSessionWithProfile } from '../../Session/ChannelDataService';
55
import { channelManager } from '../../Channel/ChannelManager';
66
import { config } from '../../Core/Config';
77
import { LoggerService } from '../../Core/LoggerService';
88
import { loadPrompt } from '../../Core/PromptLoader';
9+
import type { ChannelUserRow } from '../../Core/Database';
910
import { CHANNEL_LIST_TOOL_NAME, ChannelListType } from './index';
1011

1112
const logger = LoggerService.getLogger('Tools/Channel/list.ts');
@@ -14,78 +15,61 @@ function escapeAttr(s: string): string {
1415
return s.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
1516
}
1617

17-
function compilePattern(pattern: string | undefined): { matcher: (s: string) => boolean; error: string | null } {
18-
if (!pattern) return { matcher: () => true, error: null };
19-
try {
20-
const re = new RegExp(pattern, 'i');
21-
return { matcher: (s: string) => re.test(s ?? ''), error: null };
22-
} catch (e: any) {
23-
return { matcher: () => false, error: `Invalid name_pattern: ${e.message}` };
18+
function groupByChannel<T extends { channelId: string }>(items: T[]): Map<string, T[]> {
19+
const map = new Map<string, T[]>();
20+
for (const item of items) {
21+
const arr = map.get(item.channelId);
22+
if (arr) arr.push(item);
23+
else map.set(item.channelId, [item]);
2424
}
25-
}
26-
27-
async function buildSessionsBlock(scope: string, queryChannelId: string | undefined, matcher: (s: string) => boolean, currentChannelId?: string): Promise<string> {
28-
const sessions = await channelDataService.listSessions(queryChannelId);
29-
const filtered = sessions.filter(s => matcher(s.sessionName) || matcher(s.autoSessionName));
30-
const lines = filtered.map(s => {
31-
const name = s.sessionName || s.autoSessionName || '';
32-
const currentAttr = currentChannelId && s.channelId === currentChannelId ? ' current="1"' : '';
33-
return ` <session id="${s.id}"${currentAttr} name="${escapeAttr(name)}" />`;
34-
});
35-
return `<sessions channel_id="${scope}" count="${filtered.length}" total="${sessions.length}">\n${lines.join('\n')}\n</sessions>`;
36-
}
37-
38-
async function buildUsersBlock(scope: string, queryChannelId: string | undefined, matcher: (s: string) => boolean, currentChannelId?: string): Promise<string> {
39-
const users = await channelDataService.listChannelUsers(queryChannelId);
40-
const filtered = users.filter(u => matcher(u.userName ?? ''));
41-
const lines = filtered.map(u => {
42-
const currentAttr = currentChannelId && u.channelId === currentChannelId ? ' current="1"' : '';
43-
return ` <user id="${u.id}"${currentAttr} channel_id="${u.channelId}" user_id="${u.userId}" name="${escapeAttr(u.userName ?? '')}" />`;
44-
});
45-
return `<users channel_id="${scope}" count="${filtered.length}" total="${users.length}">\n${lines.join('\n')}\n</users>`;
25+
return map;
4626
}
4727

4828
export function createChannelListTool(currentChannelId?: string): StructuredToolInterface {
4929
return new DynamicStructuredTool({
5030
name: CHANNEL_LIST_TOOL_NAME,
5131
description: loadPrompt('tools/channel/list.txt'),
5232
schema: z.object({
53-
type: z.enum(ChannelListType).describe('What to list. "channel" ignores channel_id; "session_and_user" emits both blocks under the same filter.'),
54-
channel_id: z.string().optional().describe('Channel scope for type=session/user/session_and_user. Omit to query across all channels.'),
55-
name_pattern: z.string().optional().describe('JavaScript regex (case-insensitive) matched against the entry name. Omit to list all.'),
33+
type: z.enum(ChannelListType).describe('What to include under each <channel>: "channel" → no children; "session" → <session> rows; "user" → <user> rows; "session_and_user" → both.'),
5634
}) as any,
57-
func: async ({ type, channel_id, name_pattern }: any): Promise<MCPToolResult> => {
58-
const { matcher, error: patternError } = compilePattern(name_pattern);
59-
if (patternError) return createErrorResult(patternError);
60-
35+
func: async ({ type }: any): Promise<MCPToolResult> => {
6136
try {
62-
if (type === ChannelListType.Channel) {
63-
const all = Object.entries(config.settings.channels ?? {});
64-
const filtered = all.filter(([, c]) => matcher(c.name ?? ''));
65-
const lines = filtered.map(([id, c]) => {
66-
const caps = channelManager.getChannelCapabilities(id).join(',');
67-
return ` <channel id="${id}" type="${c.type}" name="${escapeAttr(c.name ?? '')}" caps="${caps}" />`;
68-
});
69-
return createSuccessResult(createTextContent(
70-
`<channels count="${filtered.length}" total="${all.length}">\n${lines.join('\n')}\n</channels>`
71-
));
72-
}
37+
const includeSessions = type === ChannelListType.Session || type === ChannelListType.SessionAndUser;
38+
const includeUsers = type === ChannelListType.User || type === ChannelListType.SessionAndUser;
7339

74-
const scope = channel_id || '*';
75-
const queryChannelId = scope === '*' ? undefined : scope;
76-
77-
if (type === ChannelListType.Session) {
78-
return createSuccessResult(createTextContent(await buildSessionsBlock(scope, queryChannelId, matcher, currentChannelId)));
79-
}
80-
if (type === ChannelListType.User) {
81-
return createSuccessResult(createTextContent(await buildUsersBlock(scope, queryChannelId, matcher, currentChannelId)));
82-
}
83-
// ChannelListType.SessionAndUser
84-
const [sessionsBlock, usersBlock] = await Promise.all([
85-
buildSessionsBlock(scope, queryChannelId, matcher, currentChannelId),
86-
buildUsersBlock(scope, queryChannelId, matcher, currentChannelId),
40+
const [allSessions, allUsers] = await Promise.all([
41+
includeSessions ? channelDataService.listSessions() : Promise.resolve([] as ChannelSessionWithProfile[]),
42+
includeUsers ? channelDataService.listChannelUsers() : Promise.resolve([] as ChannelUserRow[]),
8743
]);
88-
return createSuccessResult(createTextContent(`${sessionsBlock}\n${usersBlock}`));
44+
45+
const sessionsByChannel = groupByChannel(allSessions);
46+
const usersByChannel = groupByChannel(allUsers);
47+
48+
const channels = Object.entries(config.settings.channels ?? {});
49+
const channelBlocks = channels.map(([id, c]) => {
50+
const caps = channelManager.getChannelCapabilities(id).join(',');
51+
const currentAttr = currentChannelId === id ? ' current="1"' : '';
52+
const headAttrs = `id="${id}" type="${c.type}" name="${escapeAttr(c.name ?? '')}" caps="${caps}"${currentAttr}`;
53+
54+
const lines: string[] = [];
55+
if (includeSessions) {
56+
for (const s of sessionsByChannel.get(id) ?? []) {
57+
lines.push(` <session id="${s.id}" name="${escapeAttr(s.sessionName || s.autoSessionName || '')}" />`);
58+
}
59+
}
60+
if (includeUsers) {
61+
for (const u of usersByChannel.get(id) ?? []) {
62+
lines.push(` <user id="${u.id}" name="${escapeAttr(u.userName ?? '')}" />`);
63+
}
64+
}
65+
66+
if (lines.length === 0) return ` <channel ${headAttrs} />`;
67+
return ` <channel ${headAttrs}>\n${lines.join('\n')}\n </channel>`;
68+
});
69+
70+
return createSuccessResult(createTextContent(
71+
`<channels count="${channels.length}">\n${channelBlocks.join('\n')}\n</channels>`
72+
));
8973
} catch (e: any) {
9074
logger.error(`${CHANNEL_LIST_TOOL_NAME} failed: ${e.message}`);
9175
return createErrorResult(`Failed to list: ${e.message}`);

‎packages/sbot/src/Tools/Channel/sendFile.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,12 +26,12 @@ export function createChannelSendFileTool(): StructuredToolInterface {
2626
const name = file_name ?? path.basename(file_path);
2727
try {
2828
const ok = type === ChannelTargetType.User
29-
? await channelManager.sendFileToDbUser(id, file_path, name)
29+
? await channelManager.sendFileToUser(id, file_path, name)
3030
: await channelManager.sendFileToSession(id, file_path, name);
3131
if (!ok) {
3232
return createErrorResult(`Send failed: type=${type} id=${id} unreachable or capability not supported.`);
3333
}
34-
return createSuccessResult(createTextContent(`<send-file status="success" type="${type}" id="${id}" file_name="${name}" />`));
34+
return createSuccessResult(createTextContent('ok'));
3535
} catch (e: any) {
3636
logger.error(`${CHANNEL_SEND_FILE_TOOL_NAME} failed: ${e.message}`);
3737
return createErrorResult(`Send failed: ${e.message}`);

‎packages/sbot/src/Tools/Channel/sendMessage.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,12 @@ export function createChannelSendMessageTool(): StructuredToolInterface {
2323
}
2424
try {
2525
const ok = type === ChannelTargetType.User
26-
? await channelManager.sendTextToDbUser(id, content)
26+
? await channelManager.sendTextToUser(id, content)
2727
: await channelManager.sendTextToSession(id, content);
2828
if (!ok) {
2929
return createErrorResult(`Send failed: type=${type} id=${id} unreachable or capability not supported.`);
3030
}
31-
return createSuccessResult(createTextContent(`<send-message status="success" type="${type}" id="${id}" />`));
31+
return createSuccessResult(createTextContent('ok'));
3232
} catch (e: any) {
3333
logger.error(`${CHANNEL_SEND_MESSAGE_TOOL_NAME} failed: ${e.message}`);
3434
return createErrorResult(`Send failed: ${e.message}`);

0 commit comments

Comments
 (0)