mirror of
https://github.com/n8n-io/n8n.git
synced 2026-12-04 00:30:34 +00:00
fix(core): Preserve Slack Agent message text and links (#45548)
This commit is contained in:
1 parent
af0f0cc6a1
commit
5716a31b31
12 files changed
+367
-35
No files matched your search
@@ -4070,7 +4070,19 @@ describe('AgentChatBridge — Slack thread history', () => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('prepends prior thread messages as context on a new mention inside a real thread', async () => {
|
||||
it('prepends prior thread messages as context on a new mention inside a real thread', async ({
|
||||
onTestFinished,
|
||||
}) => {
|
||||
const chatSdk = await import('chat');
|
||||
const loadChatSdkSpy = vi.spyOn(esmLoader, 'loadChatSdk').mockResolvedValue(chatSdk);
|
||||
onTestFinished(() => {
|
||||
loadChatSdkSpy.mockRestore();
|
||||
});
|
||||
// AGENT-1680: The Slack SDK projects labelled links to plain text.
|
||||
const { SlackFormatConverter } = await import('@chat-adapter/slack');
|
||||
const formatted = new SlackFormatConverter().toAst(
|
||||
'See <https://example.com/folder?view=1|folder>, <http://example.com|example.com> and <https://example.com/video|video>.',
|
||||
);
|
||||
const { bot, handlers } = makeBot();
|
||||
bot.getAdapter.mockReturnValue({ botUserId: 'U_BOT' });
|
||||
// thread.messages yields newest-first; trigger first, then bob, then alice.
|
||||
@@ -4078,7 +4090,12 @@ describe('AgentChatBridge — Slack thread history', () => {
|
||||
[Symbol.asyncIterator]: () => {
|
||||
return (async function* () {
|
||||
yield { id: 'trigger', text: '@U_BOT help', author: { userId: 'u1', userName: 'alice' } };
|
||||
yield { id: 'm2', text: 'let me check', author: { userId: 'u2', userName: 'bob' } };
|
||||
yield {
|
||||
id: 'm2',
|
||||
text: chatSdk.toPlainText(formatted),
|
||||
formatted,
|
||||
author: { userId: 'u2', userName: 'bob' },
|
||||
};
|
||||
yield {
|
||||
id: 'm1',
|
||||
text: 'what should we do?',
|
||||
@@ -4114,10 +4131,12 @@ describe('AgentChatBridge — Slack thread history', () => {
|
||||
const call = agentExecutor.captured[0];
|
||||
expect(call.modelMessage).toContain('<slack_thread_history>');
|
||||
expect(call.modelMessage).toContain('[alice]: what should we do?');
|
||||
expect(call.modelMessage).toContain('[bob]: let me check');
|
||||
expect(call.modelMessage).toContain(
|
||||
'[bob]: See [folder](https://example.com/folder?view=1), [example.com](http://example.com) and [video](https://example.com/video).',
|
||||
);
|
||||
// Chronological order: alice's message (older) appears before bob's.
|
||||
expect(call.modelMessage.indexOf('[alice]: what should we do?')).toBeLessThan(
|
||||
call.modelMessage.indexOf('[bob]: let me check'),
|
||||
call.modelMessage.indexOf('[bob]: See [folder]'),
|
||||
);
|
||||
// Triggering message is excluded, and the mention text is appended after.
|
||||
expect(call.modelMessage).not.toContain('@U_BOT help');
|
||||
|
||||
@@ -12,6 +12,7 @@ import { loadSlackAdapter } from '../esm-loader';
|
||||
import { SlackIntegration } from '../platforms/slack/slack-integration';
|
||||
|
||||
vi.mock('../esm-loader', () => ({
|
||||
loadChatSdk: async () => await import('chat'),
|
||||
loadSlackAdapter: vi.fn(),
|
||||
}));
|
||||
|
||||
@@ -21,11 +22,12 @@ describe('SlackIntegration', () => {
|
||||
let integration: SlackIntegration;
|
||||
const adapterConstructor = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
integration = new SlackIntegration(mock<AgentRepository>(), mock());
|
||||
adapterConstructor.mockReset();
|
||||
mockedLoadSlackAdapter.mockReset();
|
||||
mockedLoadSlackAdapter.mockResolvedValue({
|
||||
...(await import('@chat-adapter/slack')),
|
||||
SlackAdapter: class {
|
||||
constructor(config: unknown) {
|
||||
adapterConstructor(config);
|
||||
|
||||
@@ -73,6 +73,7 @@ import { buildSuspendCardPayload } from './agent-chat-suspension-cards';
|
||||
import { CallbackStore, type CallbackMetadata } from './callback-store';
|
||||
import type { ComponentMapper, ShortenCallback } from './component-mapper';
|
||||
import { loadChatSdk } from './esm-loader';
|
||||
import { getInboundMessageText } from './inbound-message-text';
|
||||
import { IntegrationMessageContextService } from './integration-message-context.service';
|
||||
import { resolveEpisodicScopeDecision } from './episodic-scope-resolver';
|
||||
import { buildIntegrationOrigin, recordIntegrationOriginNames } from './integration-origin';
|
||||
@@ -881,7 +882,7 @@ export class AgentChatBridge {
|
||||
): Promise<InboundMessage | null> {
|
||||
const platformAgentContext = this.getPlatformAgentContext();
|
||||
const text = this.prepareInboundText(
|
||||
await this.getInboundText(message),
|
||||
await getInboundMessageText(message, { preserveCode: this.integration.type === 'slack' }),
|
||||
platformAgentContext,
|
||||
).trim();
|
||||
// `?? []` guards rehydrated/serialized messages that predate the field.
|
||||
@@ -1541,22 +1542,6 @@ export class AgentChatBridge {
|
||||
return this.integrationImpl?.getPlatformAgentContext?.(this.chat) ?? {};
|
||||
}
|
||||
|
||||
/** Keep labelled-link URLs because the Chat SDK plain-text projection removes them. */
|
||||
private async getInboundText(message: Message): Promise<string> {
|
||||
if (!message.formatted) return message.text;
|
||||
const { isLinkNode, text, toPlainText, walkAst } = await loadChatSdk();
|
||||
// Keep raw platform markdown when the adapter does not use the SDK projection.
|
||||
if (toPlainText(message.formatted) !== message.text) return message.text;
|
||||
const formatted = walkAst(structuredClone(message.formatted), (node) => {
|
||||
if (!isLinkNode(node)) return node;
|
||||
const label = toPlainText({ type: 'root', children: [node] });
|
||||
// Keep GFM autolinks because their labels already contain the URL.
|
||||
if ([label, `http://${label}`, `mailto:${label}`].includes(node.url)) return node;
|
||||
return text(`[${label}](${node.url})`);
|
||||
});
|
||||
return toPlainText(formatted);
|
||||
}
|
||||
|
||||
private prepareInboundText(text: string | undefined, context: PlatformAgentContext): string {
|
||||
const trimmed = text?.trim() ?? '';
|
||||
return this.integrationImpl?.prepareInboundText?.(trimmed, context) ?? trimmed;
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { Message } from 'chat';
|
||||
|
||||
import { loadChatSdk } from './esm-loader';
|
||||
|
||||
/** Keep links and, for Slack, code delimiters that the SDK plain-text projection removes. */
|
||||
export async function getInboundMessageText(
|
||||
message: Message<unknown>,
|
||||
{ preserveCode = false } = {},
|
||||
): Promise<string> {
|
||||
if (!message.formatted) return message.text;
|
||||
const { isLinkNode, paragraph, root, stringifyMarkdown, text, toPlainText, walkAst } =
|
||||
await loadChatSdk();
|
||||
// Keep the supplied text when the adapter does not use the SDK projection.
|
||||
if (toPlainText(message.formatted) !== message.text) return message.text;
|
||||
const formatted = walkAst(structuredClone(message.formatted), (node) => {
|
||||
if (preserveCode && node.type === 'code') {
|
||||
return text(stringifyMarkdown(root([node])).trimEnd());
|
||||
}
|
||||
if (preserveCode && node.type === 'inlineCode') {
|
||||
return text(stringifyMarkdown(root([paragraph([node])])).trimEnd());
|
||||
}
|
||||
if (!isLinkNode(node)) return node;
|
||||
const label = toPlainText(root([node]));
|
||||
if (node.url === label || node.url === `mailto:${label}`) return node;
|
||||
// Outside Slack, GFM supplies the scheme for bare www links.
|
||||
if (!preserveCode && node.url === `http://${label}`) return node;
|
||||
return text(`[${label}](${node.url})`);
|
||||
});
|
||||
return toPlainText(formatted);
|
||||
}
|
||||
+77
-2
@@ -14,13 +14,18 @@ import {
|
||||
SLACK_STREAMING_OPTIONS,
|
||||
} from '../../slack/slack-bridge-behavior';
|
||||
import { SlackIntegration } from '../../slack/slack-integration';
|
||||
import { createSlackSourceAdapter } from '../../slack/slack-adapter';
|
||||
|
||||
vi.mock('../../../esm-loader', () => ({
|
||||
loadSlackAdapter: async () => await import('@chat-adapter/slack'),
|
||||
loadChatSdk: async () => await import('chat'),
|
||||
}));
|
||||
|
||||
async function makeSlackContext(topLevel: boolean, resume = false) {
|
||||
const threadTs = topLevel ? '1719000001.000100' : '1719000000.000100';
|
||||
const { createSlackAdapter } = await import('@chat-adapter/slack');
|
||||
const { createMemoryState } = await import('@chat-adapter/state-memory');
|
||||
const { ThreadImpl } = await import('chat');
|
||||
const adapter = createSlackAdapter({
|
||||
const adapter = await createSlackSourceAdapter({
|
||||
botToken: 'xoxb-test-token',
|
||||
botUserId: 'U_BOT',
|
||||
signingSecret: 'test-signing-secret',
|
||||
@@ -65,6 +70,76 @@ async function makeSlackContext(topLevel: boolean, resume = false) {
|
||||
describe('Slack stream delivery', () => {
|
||||
afterEach(() => nock.cleanAll());
|
||||
|
||||
// AGENT-1629: Slack rewrites bullets when it renders markdown_text.
|
||||
it.each([false, true])(
|
||||
'preserves literal Slack text when the bullet arrives late: %s',
|
||||
async (lateBullet) => {
|
||||
const plain = '*This* is math: 𝑎*b*c and `a*b*c`.';
|
||||
const literal = ': a*b*c • <!channel> & List<String> ';
|
||||
const code = ' a*b*c • y < z\n ```';
|
||||
const list = '- Check the example\n- Review the result';
|
||||
const url = 'https://example.com/?a=1&b=2';
|
||||
const markdown = [
|
||||
list,
|
||||
'',
|
||||
`**Math**${literal}[docs](${url}) and ` + '``a`b • c``',
|
||||
'',
|
||||
'````lean',
|
||||
code,
|
||||
'````',
|
||||
].join('\n');
|
||||
const bodies: Record<string, unknown>[] = [];
|
||||
const ts = '1719000999.000100';
|
||||
nock('https://slack.com')
|
||||
.persist()
|
||||
.post(/\/api\/.+/)
|
||||
.reply(200, (uri, body: string | Record<string, unknown>) => {
|
||||
if (uri === '/api/chat.postMessage' || uri === '/api/chat.update') {
|
||||
bodies.push(
|
||||
typeof body === 'string' ? Object.fromEntries(new URLSearchParams(body)) : body,
|
||||
);
|
||||
}
|
||||
return { ok: true, ts, message: { ts } };
|
||||
});
|
||||
const { thread } = await makeSlackContext(false);
|
||||
const reply = await thread.post({ markdown: lateBullet ? plain : markdown });
|
||||
await reply.edit({ markdown });
|
||||
|
||||
expect(bodies).toHaveLength(2);
|
||||
expect(bodies[0]).toHaveProperty('thread_ts', '1719000000.000100');
|
||||
expect(bodies[1]).toHaveProperty('ts', ts);
|
||||
if (lateBullet) {
|
||||
expect(bodies[0]).toHaveProperty('markdown_text', '*This* is math: 𝑎\\*b\\*c and `a*b*c`.');
|
||||
expect(bodies[0]).not.toHaveProperty('blocks');
|
||||
}
|
||||
for (const body of bodies.slice(lateBullet ? 1 : 0)) {
|
||||
expect(body).not.toHaveProperty('markdown_text');
|
||||
expect(body.text).toContain('<!channel> & List<String>');
|
||||
expect(body.text).toContain('docs (https://example.com/?a=1&b=2)');
|
||||
const blocks = typeof body.blocks === 'string' ? JSON.parse(body.blocks) : body.blocks;
|
||||
expect(blocks).toEqual([
|
||||
{ type: 'markdown', text: list },
|
||||
{
|
||||
type: 'rich_text',
|
||||
elements: [
|
||||
{
|
||||
type: 'rich_text_section',
|
||||
elements: [
|
||||
{ type: 'text', text: 'Math', style: { bold: true } },
|
||||
{ type: 'text', text: literal },
|
||||
{ type: 'link', text: 'docs', url },
|
||||
{ type: 'text', text: ' and ' },
|
||||
{ type: 'text', text: 'a`b • c', style: { code: true } },
|
||||
],
|
||||
},
|
||||
{ type: 'rich_text_preformatted', elements: [{ type: 'text', text: code }] },
|
||||
],
|
||||
},
|
||||
]);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ name: 'threaded stream', topLevel: false, textEnd: true, ending: 'reply' },
|
||||
{ name: 'top-level reply', topLevel: true, textEnd: true, ending: 'reply' },
|
||||
|
||||
+22
@@ -140,6 +140,28 @@ describe('Slack channel integration scenarios', () => {
|
||||
},
|
||||
);
|
||||
|
||||
// AGENT-1629: Keep code delimiters, indentation, and literal asterisks.
|
||||
it('passes literal asterisks and code to the Agent unchanged', async () => {
|
||||
const text =
|
||||
'a * b * c, 𝑎*b*c, and `*x* @U_BOT <https://example.com> <!channel> <https://example.com/literal>`\n\n```\n x = s • a\n a*b*c\n curl <https://example.com>\n```';
|
||||
const fixtures = slackReplayFixtures({
|
||||
mention: slackEventCallback({ event: { text: `<@U_BOT> ${text}`, thread_ts: undefined } }),
|
||||
});
|
||||
const ctx = await createSlackReplayContext(fixtures);
|
||||
try {
|
||||
await ctx.sendWebhook(fixtures.mention);
|
||||
expect(ctx.agentExecutor.executeForChatPublished).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
message: text
|
||||
.replaceAll('<https://example.com>', 'https://example.com')
|
||||
.replace('<https://example.com/literal>', '<https://example.com/literal>'),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
await ctx.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
it('handles Slack URL verification without an active connection', () => {
|
||||
const integration = new SlackIntegration(mock<AgentRepository>(), mock());
|
||||
|
||||
|
||||
@@ -1,12 +1,57 @@
|
||||
import type { SlackAdapter, SlackAdapterConfig } from '@chat-adapter/slack';
|
||||
import type { WebhookOptions } from 'chat';
|
||||
import type { AdapterPostableMessage, WebhookOptions } from 'chat';
|
||||
|
||||
import { loadSlackAdapter } from '../../esm-loader';
|
||||
import { loadChatSdk, loadSlackAdapter } from '../../esm-loader';
|
||||
import { renderSlackRichText } from './slack-rich-text';
|
||||
|
||||
export async function createSlackSourceAdapter(config: SlackAdapterConfig): Promise<SlackAdapter> {
|
||||
const { SlackAdapter } = await loadSlackAdapter();
|
||||
const [{ SlackAdapter, SlackFormatConverter }, { parseMarkdown, walkAst }] = await Promise.all([
|
||||
loadSlackAdapter(),
|
||||
loadChatSdk(),
|
||||
]);
|
||||
|
||||
function escapeLiteralAsterisks(markdown: string): string {
|
||||
const wordStars = new Set(
|
||||
Array.from(
|
||||
markdown.matchAll(/(?<=[\p{L}\p{N}])\*(?=[\p{L}\p{N}])/gu),
|
||||
(match) => match.index,
|
||||
),
|
||||
);
|
||||
if (wordStars.size < 2) return markdown;
|
||||
const markers = new Set<number>();
|
||||
walkAst(parseMarkdown(markdown), (node) => {
|
||||
if (node.type !== 'emphasis' || !node.position) return node;
|
||||
const { start, end } = node.position;
|
||||
if (start.offset === undefined || end.offset === undefined) return node;
|
||||
const close = end.offset - 1;
|
||||
if (wordStars.has(start.offset) && wordStars.has(close)) {
|
||||
markers.add(start.offset);
|
||||
markers.add(close);
|
||||
}
|
||||
return node;
|
||||
});
|
||||
return markdown.replace(/\*/g, (marker, offset) => (markers.has(offset) ? '\\*' : marker));
|
||||
}
|
||||
|
||||
class SlackSourceFormatConverter extends SlackFormatConverter {
|
||||
override toSlackPayload(message: AdapterPostableMessage) {
|
||||
if (typeof message === 'string' || !('markdown' in message)) {
|
||||
return super.toSlackPayload(message);
|
||||
}
|
||||
// CommonMark interprets unspaced multiplication such as a*b*c as emphasis.
|
||||
const markdown = escapeLiteralAsterisks(message.markdown);
|
||||
// Slack rewrites literal bullets in markdown_text, even in code blocks.
|
||||
if (markdown.includes('•')) {
|
||||
const payload = renderSlackRichText(parseMarkdown(markdown), markdown);
|
||||
if (payload) return payload;
|
||||
}
|
||||
return super.toSlackPayload({ ...message, markdown });
|
||||
}
|
||||
}
|
||||
|
||||
class SlackSourceAdapter extends SlackAdapter {
|
||||
protected override readonly formatConverter = new SlackSourceFormatConverter();
|
||||
|
||||
protected override processEventPayload(
|
||||
payload: Parameters<InstanceType<typeof SlackAdapter>['processEventPayload']>[0],
|
||||
options?: WebhookOptions,
|
||||
|
||||
+8
-6
@@ -12,6 +12,7 @@ import type {
|
||||
} from '../../agent-chat-integration';
|
||||
import type { ChatInstance } from '../../chat-integration.service';
|
||||
import type { ReplyExpectation } from '../../integration-tools';
|
||||
import { getInboundMessageText } from '../../inbound-message-text';
|
||||
|
||||
const SLACK_THINKING_STATUS = 'Thinking...';
|
||||
const SLACK_STATUS_RETRY_DELAY_MS = 750;
|
||||
@@ -365,7 +366,7 @@ async function fetchSlackThreadHistory(
|
||||
break;
|
||||
}
|
||||
|
||||
const text = typeof message.text === 'string' ? message.text.trim() : '';
|
||||
const text = (await getInboundMessageText(message, { preserveCode: true }))?.trim();
|
||||
if (!text) continue;
|
||||
|
||||
const line = formatSlackHistoryLine(message, text);
|
||||
@@ -469,11 +470,12 @@ function getSlackAssistantStatusAdapter(
|
||||
|
||||
function stripSlackSelfMention(text: string, userId: string): string {
|
||||
const escapedUserId = escapeRegExp(userId);
|
||||
return text
|
||||
.replace(new RegExp(`(^|\\s)<@!?${escapedUserId}(?:\\|[^>]+)?>`, 'gi'), '$1')
|
||||
.replace(new RegExp(`(^|\\s)@${escapedUserId}\\b`, 'gi'), '$1')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
const codeSpan = /(?<!`)(`+)(?!`)[\s\S]*?(?<!`)\1(?!`)/;
|
||||
const codeOrMention = new RegExp(
|
||||
String.raw`${codeSpan.source}|(?<!\S)(?:<@!?${escapedUserId}(?:\|[^>]+)?>|@${escapedUserId}\b)[ \t]*`,
|
||||
'gi',
|
||||
);
|
||||
return text.replace(codeOrMention, (match, delimiter) => (delimiter ? match : '')).trim();
|
||||
}
|
||||
|
||||
function isSlackAssistantStatusAdapter(value: unknown): value is SlackAssistantStatusAdapter {
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import type { Nodes, Root } from 'chat';
|
||||
|
||||
type Style = { bold?: true; italic?: true; strike?: true; code?: true };
|
||||
type Inline =
|
||||
| { type: 'text'; text: string; style?: Style }
|
||||
| { type: 'link'; url: string; text: string; style?: Style };
|
||||
type Section = { type: 'rich_text_section' | 'rich_text_preformatted'; elements: Inline[] };
|
||||
type Block = { type: 'rich_text'; elements: Section[] } | { type: 'markdown'; text: string };
|
||||
|
||||
function renderInline(node: Nodes, style?: Style): Inline | undefined {
|
||||
switch (node.type) {
|
||||
case 'text':
|
||||
case 'html':
|
||||
return { type: 'text', text: node.value, style };
|
||||
case 'inlineCode':
|
||||
return { type: 'text', text: node.value, style: { ...style, code: true } };
|
||||
case 'break':
|
||||
return { type: 'text', text: '\n', style };
|
||||
case 'link': {
|
||||
if (!/^(https?:\/\/|mailto:)/i.test(node.url) || !URL.canParse(node.url)) return;
|
||||
if (!node.children.every((child) => child.type === 'text')) return;
|
||||
return {
|
||||
type: 'link',
|
||||
url: node.url,
|
||||
text: node.children.map((child) => child.value).join(''),
|
||||
style,
|
||||
};
|
||||
}
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function renderInlines(nodes: Nodes[], style?: Style): Inline[] | undefined {
|
||||
const elements: Inline[] = [];
|
||||
for (const node of nodes) {
|
||||
const format = { emphasis: 'italic', strong: 'bold', delete: 'strike' } as const;
|
||||
if (node.type === 'emphasis' || node.type === 'strong' || node.type === 'delete') {
|
||||
const children = renderInlines(node.children, { ...style, [format[node.type]]: true });
|
||||
if (!children) return;
|
||||
elements.push(...children);
|
||||
} else {
|
||||
const element = renderInline(node, style);
|
||||
if (!element) return;
|
||||
const previous = elements.at(-1);
|
||||
if (
|
||||
element.type === 'text' &&
|
||||
previous?.type === 'text' &&
|
||||
previous.style === element.style
|
||||
) {
|
||||
previous.text += element.text;
|
||||
} else if (element.text) {
|
||||
elements.push(element);
|
||||
}
|
||||
}
|
||||
}
|
||||
return elements;
|
||||
}
|
||||
|
||||
function renderSection(node: Root['children'][number]): Section | undefined {
|
||||
if (node.type === 'code' && node.value) {
|
||||
return { type: 'rich_text_preformatted', elements: [{ type: 'text', text: node.value }] };
|
||||
}
|
||||
if (node.type === 'paragraph' || node.type === 'heading') {
|
||||
const elements = renderInlines(
|
||||
node.children,
|
||||
node.type === 'heading' ? { bold: true } : undefined,
|
||||
);
|
||||
if (elements?.length) return { type: 'rich_text_section', elements };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Use rich text for literal bullets, stars, and backticks. Keep other Markdown structures intact.
|
||||
export function renderSlackRichText(ast: Root, markdown: string) {
|
||||
const blocks: Block[] = [];
|
||||
const fallback: string[] = [];
|
||||
let hasRichText = false;
|
||||
for (const node of ast.children) {
|
||||
const previous = blocks.at(-1);
|
||||
const section = renderSection(node);
|
||||
if (section) {
|
||||
hasRichText = true;
|
||||
if (previous?.type === 'rich_text') previous.elements.push(section);
|
||||
else blocks.push({ type: 'rich_text', elements: [section] });
|
||||
fallback.push(
|
||||
section.elements
|
||||
.map((element) =>
|
||||
element.type === 'link' && element.text !== element.url
|
||||
? `${element.text} (${element.url})`
|
||||
: element.text,
|
||||
)
|
||||
.join(''),
|
||||
);
|
||||
} else {
|
||||
const start = node.position?.start.offset;
|
||||
const end = node.position?.end.offset;
|
||||
if (start === undefined || end === undefined) return;
|
||||
const text = markdown.slice(start, end);
|
||||
if (previous?.type === 'markdown') previous.text += `\n\n${text}`;
|
||||
else blocks.push({ type: 'markdown', text });
|
||||
fallback.push(text);
|
||||
}
|
||||
}
|
||||
if (!hasRichText || blocks.length > 50) return;
|
||||
const text = fallback
|
||||
.join('\n\n')
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>');
|
||||
return { text, blocks };
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
diff --git a/dist/chunk-6QHBXN7B.js b/dist/chunk-6QHBXN7B.js
|
||||
index 731c4889128120ca4a418495baf6da5a6f536bdd..4e6daf3d5050f19c4abdfab1f4481c91b0caf98b 100644
|
||||
--- a/dist/chunk-6QHBXN7B.js
|
||||
+++ b/dist/chunk-6QHBXN7B.js
|
||||
@@ -76,10 +76,28 @@ function convertSlackTokens(mrkdwn) {
|
||||
return markdown;
|
||||
}
|
||||
function convertMrkdwnText(mrkdwn) {
|
||||
- let markdown = convertSlackTokens(mrkdwn);
|
||||
- markdown = markdown.replace(/(?<![_*\\])\*([^*\n]+)\*(?![_*])/g, "**$1**");
|
||||
- markdown = markdown.replace(/(?<!~)~([^~\n]+)~(?!~)/g, "~~$1~~");
|
||||
- return markdown;
|
||||
+ // Backport the emphasis fix from vercel/chat#957. Mask code and Slack tokens
|
||||
+ // so emphasis can span them without changing the characters inside them.
|
||||
+ const opaque = /`[^`\r\n]*`|<[^<>\r\n]+>/g;
|
||||
+ const masked = mrkdwn.replace(opaque, (value) => "x".repeat(value.length));
|
||||
+ const wordStars = new Set(Array.from(masked.matchAll(/(?<=[\p{L}\p{N}])\*(?=[\p{L}\p{N}])/gu), (match) => match.index));
|
||||
+ const markers = new Map();
|
||||
+ for (const pattern of [
|
||||
+ /(?<![_*\\])\*([^\s*](?:[^*\n]*[^\s*])?)\*(?![_*])/g,
|
||||
+ /(?<!~)~([^\s~](?:[^~\n]*[^\s~])?)~(?!~)/g
|
||||
+ ]) {
|
||||
+ for (const match of masked.matchAll(pattern)) {
|
||||
+ const close = match.index + match[0].length - 1;
|
||||
+ const escape = wordStars.has(match.index) && wordStars.has(close);
|
||||
+ markers.set(match.index, escape);
|
||||
+ markers.set(close, escape);
|
||||
+ }
|
||||
+ }
|
||||
+ const markdown = mrkdwn.replace(/[*~]/g, (marker, index) => {
|
||||
+ if (!markers.has(index)) return marker;
|
||||
+ return markers.get(index) ? `\\${marker}` : marker.repeat(2);
|
||||
+ });
|
||||
+ return markdown.replace(opaque, convertSlackTokens);
|
||||
}
|
||||
function convertMrkdwnWithCodeFences(mrkdwn) {
|
||||
let result = "";
|
||||
Generated
+3
-2
@@ -1159,6 +1159,7 @@ overrides:
|
||||
'@langchain/langgraph-checkpoint': 1.1.6
|
||||
|
||||
patchedDependencies:
|
||||
'@chat-adapter/slack@4.39.0': e84522568840661c950855d13926184bc980f9aafb088d3900624e88b660e5b5
|
||||
'@chat-adapter/teams@4.39.0': aae12484e0d48fa7c4ebc9bd6db97f17587ae4c458dd6b186fdf748cad60a9af
|
||||
'@chat-adapter/whatsapp@4.39.0': bdf07d60cf43691d7f5bff5111d1205d36f62849bea742680713771330455cc7
|
||||
'@confluentinc/kafka-javascript@1.9.1': c597d3e3d9d6d0d33588b7dc1e88d55f270ba155721aad464bd7fb03e28f5003
|
||||
@@ -5160,7 +5161,7 @@ importers:
|
||||
version: 4.39.0(ai@7.0.150(zod@3.25.76))(graphql@16.11.0)(supports-color@8.1.1)(zod@3.25.76)
|
||||
'@chat-adapter/slack':
|
||||
specifier: 'catalog:'
|
||||
version: 4.39.0(ai@7.0.150(zod@3.25.76))(bufferutil@4.0.9)(debug@4.4.3(supports-color@8.1.1))(supports-color@8.1.1)(utf-8-validate@5.0.10)(zod@3.25.76)
|
||||
version: 4.39.0(patch_hash=e84522568840661c950855d13926184bc980f9aafb088d3900624e88b660e5b5)(ai@7.0.150(zod@3.25.76))(bufferutil@4.0.9)(debug@4.4.3(supports-color@8.1.1))(supports-color@8.1.1)(utf-8-validate@5.0.10)(zod@3.25.76)
|
||||
'@chat-adapter/state-memory':
|
||||
specifier: 'catalog:'
|
||||
version: 4.39.0(ai@7.0.150(zod@3.25.76))(supports-color@8.1.1)(zod@3.25.76)
|
||||
@@ -31002,7 +31003,7 @@ snapshots:
|
||||
- workflow
|
||||
- zod
|
||||
|
||||
'@chat-adapter/slack@4.39.0(ai@7.0.150(zod@3.25.76))(bufferutil@4.0.9)(debug@4.4.3(supports-color@8.1.1))(supports-color@8.1.1)(utf-8-validate@5.0.10)(zod@3.25.76)':
|
||||
'@chat-adapter/slack@4.39.0(patch_hash=e84522568840661c950855d13926184bc980f9aafb088d3900624e88b660e5b5)(ai@7.0.150(zod@3.25.76))(bufferutil@4.0.9)(debug@4.4.3(supports-color@8.1.1))(supports-color@8.1.1)(utf-8-validate@5.0.10)(zod@3.25.76)':
|
||||
dependencies:
|
||||
'@chat-adapter/shared': 4.39.0(ai@7.0.150(zod@3.25.76))(supports-color@8.1.1)(zod@3.25.76)
|
||||
'@slack/socket-mode': 2.0.7(bufferutil@4.0.9)(debug@4.4.3(supports-color@8.1.1))(supports-color@8.1.1)(utf-8-validate@5.0.10)
|
||||
|
||||
@@ -566,6 +566,8 @@ patchedDependencies:
|
||||
'@langchain/google-common@2.1.24': patches/@langchain__google-common@2.1.24.patch
|
||||
'@confluentinc/kafka-javascript@1.9.1': patches/@confluentinc__kafka-javascript@1.9.1.patch
|
||||
imapflow@1.7.1: patches/imapflow@1.7.1.patch
|
||||
# Preserve literal asterisks and code without bumping the whole Chat SDK.
|
||||
'@chat-adapter/slack@4.39.0': patches/@chat-adapter__slack@4.39.0.patch
|
||||
'@chat-adapter/teams@4.39.0': patches/@chat-adapter__teams@4.39.0.patch
|
||||
'@chat-adapter/whatsapp@4.39.0': patches/@chat-adapter__whatsapp@4.39.0.patch
|
||||
pdf-parse@2.4.5: patches/pdf-parse@2.4.5.patch
|
||||
|
||||
Reference in new issue
Block a user