Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

refactor(slack): use chat sdk block kit primitives (#210)

joshb33c6118b7dc
diff --git a/.changeset/lazy-donuts-cry.md b/.changeset/lazy-donuts-cry.md
new file mode 100644
index 000000000..19140670c
--- /dev/null
+++ b/.changeset/lazy-donuts-cry.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+use shared Chat SDK Block Kit primitives for Slack card rendering
diff --git a/packages/eve/package.json b/packages/eve/package.json
index 03fd61f38..8fbb72a00 100644
--- a/packages/eve/package.json
+++ b/packages/eve/package.json
@@ -293,8 +293,8 @@
"@ai-sdk/openai": "catalog:",
"@ai-sdk/otel": "catalog:",
"@ai-sdk/provider": "catalog:",
- "@chat-adapter/slack": "4.29.0",
- "@chat-adapter/state-memory": "4.29.0",
+ "@chat-adapter/slack": "4.31.0",
+ "@chat-adapter/state-memory": "4.31.0",
"@clack/core": "1.3.1",
"@nuxt/kit": "^4.0.0",
"@standard-schema/spec": "1.1.0",
@@ -313,7 +313,7 @@
"@workflow/world-local": "5.0.0-beta.19",
"ai": "catalog:",
"autoevals": "0.0.132",
- "chat": "4.29.0",
+ "chat": "4.31.0",
"chokidar": "5.0.0",
"commander": "14.0.3",
"emulate": "^0.6.0",
diff --git a/packages/eve/scripts/vendor-compiled/@chat-adapter/slack.mjs b/packages/eve/scripts/vendor-compiled/@chat-adapter/slack.mjs
index bdc543538..ec9b75606 100644
--- a/packages/eve/scripts/vendor-compiled/@chat-adapter/slack.mjs
+++ b/packages/eve/scripts/vendor-compiled/@chat-adapter/slack.mjs
@@ -66,8 +66,21 @@ function buildSlackWebApiStub(names, moduleName) {
export default {
packageName: "@chat-adapter/slack",
compiledPath: "@chat-adapter/slack",
+ entries: [
+ {
+ outputPath: "index",
+ },
+ {
+ input: "@chat-adapter/slack/blocks",
+ outputPath: "blocks",
+ },
+ ],
plugins: [createOptionalNativeStubPlugin(["bufferutil", "utf-8-validate"])],
copyDeclarations: createDeclarationCopier({
+ files: [
+ { source: "index.d.ts", output: "index.d.ts" },
+ { source: "blocks.d.ts", output: "blocks.d.ts" },
+ ],
rewrites: {
chat: { kind: "vendored", compiledPath: "chat" },
"@chat-adapter/shared": {
diff --git a/packages/eve/src/public/channels/slack/blocks.test.ts b/packages/eve/src/public/channels/slack/blocks.test.ts
index acd619def..cba501e13 100644
--- a/packages/eve/src/public/channels/slack/blocks.test.ts
+++ b/packages/eve/src/public/channels/slack/blocks.test.ts
@@ -8,6 +8,7 @@ import {
Divider,
Fields,
LinkButton,
+ Select,
Section,
Table,
Field,
@@ -62,13 +63,13 @@ describe("cardToBlocks", () => {
{
type: "button",
action_id: "approve",
- text: { type: "plain_text", text: "Approve" },
+ text: { type: "plain_text", text: "Approve", emoji: true },
style: "primary",
},
{
type: "button",
action_id: "deny",
- text: { type: "plain_text", text: "Deny" },
+ text: { type: "plain_text", text: "Deny", emoji: true },
value: "force",
style: "danger",
},
@@ -80,18 +81,74 @@ describe("cardToBlocks", () => {
it("converts link buttons with a synthetic action_id and url", () => {
const blocks = cardToBlocks(
Card({
- children: [Actions([LinkButton({ url: "https://example.com/docs", label: "View docs" })])],
+ children: [
+ Actions([
+ LinkButton({ url: "https://example.com/docs", label: "View docs" }),
+ LinkButton({
+ id: "account",
+ url: "https://example.com/account",
+ label: "Account",
+ }),
+ ]),
+ ],
}),
);
- const actions = blocks[0] as { elements: Array<Record<string, unknown>> };
- expect(actions.elements[0]).toEqual({
- type: "button",
- action_id: "link:https://example.com/docs",
- text: { type: "plain_text", text: "View docs" },
- url: "https://example.com/docs",
+ expect(blocks[0]).toEqual({
+ elements: [
+ {
+ action_id: "link:https://example.com/docs",
+ text: { emoji: true, text: "View docs", type: "plain_text" },
+ type: "button",
+ url: "https://example.com/docs",
+ },
+ {
+ action_id: "account",
+ text: { emoji: true, text: "Account", type: "plain_text" },
+ type: "button",
+ url: "https://example.com/account",
+ },
+ ],
+ type: "actions",
});
});
+ it("preserves a selected option", () => {
+ const blocks = cardToBlocks(
+ Card({
+ children: [
+ Actions([
+ Select({
+ id: "priority",
+ initialOption: "high",
+ label: "Priority",
+ options: [
+ { label: "Low", value: "low" },
+ { label: "High", value: "high" },
+ ],
+ }),
+ ]),
+ ],
+ }),
+ );
+ expect(blocks[0]).toMatchObject({
+ elements: [
+ {
+ initial_option: {
+ text: { text: "High", type: "plain_text" },
+ value: "high",
+ },
+ },
+ ],
+ });
+ });
+
+ it("limits the number of blocks", () => {
+ const blocks = cardToBlocks(
+ Card({ children: Array.from({ length: 60 }, (_, index) => CardText(`item ${index}`)) }),
+ );
+ expect(blocks).toHaveLength(50);
+ });
+
it("converts divider, image, and fields children", () => {
const blocks = cardToBlocks(
Card({
@@ -191,8 +248,6 @@ describe("cardToFallbackText", () => {
children: [CardText("Body content"), Divider()],
}),
);
- expect(text).toContain("Heading");
- expect(text).toContain("Caption");
- expect(text).toContain("Body content");
+ expect(text).toBe("Heading\nCaption\nBody content");
});
});
diff --git a/packages/eve/src/public/channels/slack/blocks.ts b/packages/eve/src/public/channels/slack/blocks.ts
index 534d3d773..cc8b4222a 100644
--- a/packages/eve/src/public/channels/slack/blocks.ts
+++ b/packages/eve/src/public/channels/slack/blocks.ts
@@ -1,314 +1,45 @@
-/**
- * Card → Slack Block Kit converter.
- *
- * The chat SDK's Slack adapter used to walk the cross-platform
- * `CardElement` AST (the data shape produced by `Card({...})`,
- * `Actions([...])`, `Button({...})`, etc.) and emit Slack Block Kit
- * JSON for `chat.postMessage`. We replicate just that conversion here
- * so authors can keep using the ergonomic card builders without the
- * `@chat-adapter/slack` runtime.
- *
- * Supported shapes:
- * Card → header + context + image header + children blocks
- * TextElement → `section`/`context` (style: plain | bold | muted)
- * ImageElement → `image` block
- * DividerElement → `divider`
- * ActionsElement → `actions` with buttons / link buttons /
- * static_select / radio_buttons
- * SectionElement → recurses into a sequence of blocks
- * FieldsElement → `section` with fields
- * LinkElement → `section` with a `<url|label>` mrkdwn
- * TableElement → `section` with a mrkdwn approximation
- * ButtonElement → `button` action element
- * LinkButtonElement → `button` action element with `url`
- *
- * Anything else falls back to the chat SDK's
- * `cardChildToFallbackText` (a string description) wrapped in a
- * section block so the message is never silently dropped.
- */
+import { cardToSlackBlocks } from "#compiled/@chat-adapter/slack/blocks.js";
+import { cardChildToFallbackText, type CardChild, type CardElement } from "#compiled/chat/index.js";
-import {
- cardChildToFallbackText,
- type ActionsElement,
- type ButtonElement,
- type CardChild,
- type CardElement,
- type DividerElement,
- type FieldsElement,
- type ImageElement,
- type LinkButtonElement,
- type LinkElement,
- type RadioSelectElement,
- type SectionElement,
- type SelectElement,
- type TableElement,
- type TextElement,
-} from "#compiled/chat/index.js";
-
-import { truncatePlainText } from "#public/channels/slack/limits.js";
-
-/**
- * One Slack Block Kit block. Slack accepts a wide enum and adds new
- * block types over time, so this type stays open-ended.
- */
+/** A Slack Block Kit block emitted by {@link cardToBlocks}. */
export type BlockKitBlock = Record<string, unknown>;
-interface CardToBlocksState {
- usedNativeTable: boolean;
-}
-
-/**
- * Converts a {@link CardElement} into a list of Slack Block Kit blocks
- * ready to pass to `chat.postMessage`'s `blocks` parameter.
- */
+/** Converts a Chat SDK card into Slack Block Kit blocks. */
export function cardToBlocks(card: CardElement): BlockKitBlock[] {
- const blocks: BlockKitBlock[] = [];
- const state: CardToBlocksState = { usedNativeTable: false };
-
- if (card.title) {
- blocks.push({
- type: "header",
- text: { type: "plain_text", text: truncatePlainText(card.title) ?? card.title, emoji: true },
- });
- }
- if (card.subtitle) {
- blocks.push({
- type: "context",
- elements: [{ type: "mrkdwn", text: card.subtitle }],
- });
- }
- if (card.imageUrl) {
- blocks.push({ type: "image", image_url: card.imageUrl, alt_text: card.title ?? "" });
- }
- for (const child of card.children) {
- appendChildBlocks(child, blocks, state);
- }
- return blocks;
+ return cardToSlackBlocks({
+ ...card,
+ children: card.children.map(preserveLinkActionId),
+ });
}
-/**
- * Best-effort fallback text for a card. `chat.postMessage` sends this
- * as the `text` field so notifications and accessibility readers still
- * see something meaningful.
- */
+/** Creates the plain-text fallback used for notifications and accessibility. */
export function cardToFallbackText(card: CardElement): string {
const lines: string[] = [];
if (card.title) lines.push(card.title);
if (card.subtitle) lines.push(card.subtitle);
for (const child of card.children) {
const text = cardChildToFallbackText(child);
- if (text && text.length > 0) lines.push(text);
+ if (text) lines.push(text);
}
return lines.join("\n").trim();
}
-function appendChildBlocks(
- child: CardChild,
- blocks: BlockKitBlock[],
- state: CardToBlocksState,
-): void {
- switch (child.type) {
- case "text":
- blocks.push(textToBlock(child));
- return;
- case "image":
- blocks.push(imageToBlock(child));
- return;
- case "divider":
- blocks.push(dividerToBlock(child));
- return;
- case "actions":
- blocks.push(actionsToBlock(child));
- return;
- case "section":
- for (const inner of (child as SectionElement).children) {
- appendChildBlocks(inner, blocks, state);
- }
- return;
- case "fields":
- blocks.push(fieldsToBlock(child));
- return;
- case "link":
- blocks.push(linkToBlock(child));
- return;
- case "table":
- blocks.push(...tableToBlocks(child, state));
- return;
- default: {
- const fallback = cardChildToFallbackText(child);
- if (fallback) {
- blocks.push({ type: "section", text: { type: "mrkdwn", text: fallback } });
- }
- }
- }
-}
-
-function textToBlock(text: TextElement): BlockKitBlock {
- if (text.style === "muted") {
+function preserveLinkActionId(child: CardChild): CardChild {
+ if (child.type === "section") {
return {
- type: "context",
- elements: [{ type: "mrkdwn", text: text.content }],
+ ...child,
+ children: child.children.map(preserveLinkActionId),
};
}
- const body = text.style === "bold" ? `*${text.content}*` : text.content;
- return { type: "section", text: { type: "mrkdwn", text: body } };
-}
-
-function imageToBlock(image: ImageElement): BlockKitBlock {
- return { type: "image", image_url: image.url, alt_text: image.alt ?? "" };
-}
-
-function dividerToBlock(_divider: DividerElement): BlockKitBlock {
- return { type: "divider" };
-}
-
-function actionsToBlock(actions: ActionsElement): BlockKitBlock {
- const elements: BlockKitBlock[] = [];
- for (const child of actions.children) {
- const element = actionChildToElement(child);
- if (element) elements.push(element);
- }
- return { type: "actions", elements };
-}
-
-function actionChildToElement(
- child: ButtonElement | LinkButtonElement | SelectElement | RadioSelectElement,
-): BlockKitBlock | null {
- switch (child.type) {
- case "button":
- return buttonToElement(child);
- case "link-button":
- return linkButtonToElement(child);
- case "select":
- return selectToElement(child);
- case "radio_select":
- return radioSelectToElement(child);
- default:
- return null;
- }
-}
-
-function buttonToElement(button: ButtonElement): BlockKitBlock {
- const element: BlockKitBlock = {
- type: "button",
- action_id: button.id,
- text: { type: "plain_text", text: truncatePlainText(button.label) ?? button.label },
- };
- if (button.value !== undefined) element.value = button.value;
- if (button.style && button.style !== "default") element.style = button.style;
- if (button.disabled === true) element.disabled = true;
- if (button.callbackUrl) element.url = button.callbackUrl;
- return element;
-}
-
-function linkButtonToElement(button: LinkButtonElement): BlockKitBlock {
- const element: BlockKitBlock = {
- type: "button",
- action_id: `link:${button.url}`,
- text: { type: "plain_text", text: truncatePlainText(button.label) ?? button.label },
- url: button.url,
- };
- if (button.style && button.style !== "default") element.style = button.style;
- return element;
-}
-
-function selectToElement(select: SelectElement): BlockKitBlock {
- return {
- type: "static_select",
- action_id: select.id,
- placeholder: {
- type: "plain_text",
- text: select.placeholder ?? select.label,
- },
- options: select.options.map((option) => ({
- text: { type: "plain_text", text: option.label },
- value: option.value,
- ...(option.description
- ? { description: { type: "plain_text", text: option.description } }
- : {}),
- })),
- };
-}
-
-function radioSelectToElement(select: RadioSelectElement): BlockKitBlock {
- return {
- type: "radio_buttons",
- action_id: select.id,
- options: select.options.map((option) => ({
- text: { type: "plain_text", text: option.label },
- value: option.value,
- ...(option.description
- ? { description: { type: "plain_text", text: option.description } }
- : {}),
- })),
- };
-}
-
-function fieldsToBlock(fields: FieldsElement): BlockKitBlock {
- return {
- type: "section",
- fields: fields.children.map((field) => ({
- type: "mrkdwn",
- text: `*${field.label}*\n${field.value}`,
- })),
- };
-}
-
-function linkToBlock(link: LinkElement): BlockKitBlock {
- return {
- type: "section",
- text: { type: "mrkdwn", text: `<${link.url}|${link.label}>` },
- };
-}
-
-/**
- * Renders a {@link TableElement} as Slack's native table block when it
- * fits Slack's limits. Slack allows one table block per message, so
- * additional or oversized tables fall back to a fixed-width mrkdwn
- * approximation.
- */
-function tableToBlocks(table: TableElement, state: CardToBlocksState): BlockKitBlock[] {
- const MAX_NATIVE_TABLE_ROWS = 100;
- const MAX_NATIVE_TABLE_COLUMNS = 20;
- if (
- !state.usedNativeTable &&
- table.rows.length <= MAX_NATIVE_TABLE_ROWS &&
- table.headers.length <= MAX_NATIVE_TABLE_COLUMNS
- ) {
- state.usedNativeTable = true;
- return [
- {
- type: "table",
- rows: [
- table.headers.map(tableCellToRawText),
- ...table.rows.map((row) => row.map(tableCellToRawText)),
- ],
- },
- ];
+ if (child.type === "actions") {
+ return {
+ ...child,
+ children: child.children.map((action) =>
+ action.type === "link-button" && action.id === undefined
+ ? { ...action, id: `link:${action.url}` }
+ : action,
+ ),
+ };
}
-
- return [tableToFallbackBlock(table)];
-}
-
-function tableCellToRawText(value: string): BlockKitBlock {
- return { type: "raw_text", text: value || " " };
-}
-
-function tableToFallbackBlock(table: TableElement): BlockKitBlock {
- const widths = table.headers.map((header, columnIndex) => {
- let width = header.length;
- for (const row of table.rows) {
- const cell = row[columnIndex] ?? "";
- if (cell.length > width) width = cell.length;
- }
- return width;
- });
-
- const headerLine = table.headers.map((header, i) => header.padEnd(widths[i] ?? 0)).join(" | ");
- const separator = widths.map((width) => "-".repeat(width)).join("-|-");
- const rowLines = table.rows.map((row) =>
- table.headers.map((_, i) => (row[i] ?? "").padEnd(widths[i] ?? 0)).join(" | "),
- );
- const body = ["```", headerLine, separator, ...rowLines, "```"].join("\n");
- return { type: "section", text: { type: "mrkdwn", text: body } };
+ return child;
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 105bdd767..1acdd81f5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -767,11 +767,11 @@ importers:
specifier: 'catalog:'
version: 4.0.0-beta.19
'@chat-adapter/slack':
- specifier: 4.29.0
+ specifier: 4.31.0
'@chat-adapter/state-memory':
- specifier: 4.29.0
+ specifier: 4.31.0
'@clack/core':
specifier: 1.3.1
version: 1.3.1
@@ -827,8 +827,8 @@ importers:
specifier: 0.0.132
version: 0.0.132([email protected])
chat:
- specifier: 4.29.0
+ specifier: 4.31.0
chokidar:
specifier: 5.0.0
version: 5.0.0
@@ -1291,16 +1291,16 @@ packages:
'@changesets/[email protected]':
resolution: {integrity: sha512-CdTLvIOPiCNuH71pyDu3rA+Q0n65cmAbXnwWH84rKGiFumFzkmHNT8KHTMEchcxN+Kl8I54xGUhJ7l3E7X396Q==}
- '@chat-adapter/[email protected]':
- resolution: {integrity: sha512-ARqTDoHJHKN9rpytbFPJbNmqqx3fOg5xwsTZdlingQPAssOSeHDBdqrFJkgDhyCRGbmDtG09cuS0FkVzeoh2qg==}
+ '@chat-adapter/[email protected]':
+ resolution: {integrity: sha512-vT/0S/LKSU5QTz5xJNWdiGp1jl55x0o8Z9I2VqlHfwjOKxVR87z++bQjXlE99w6BAxZjSYhWErlveyKo4LiDGg==}
engines: {node: '>=20'}
- '@chat-adapter/[email protected]':
- resolution: {integrity: sha512-s2DXAwkTpmiIKSATXgrO879s1pqFwS70Y0JPd+TRGRzDeh6nfqt5dnKt5Bug0P1zwkB6DoPurhnYS9nqhSmD/w==}
+ '@chat-adapter/[email protected]':
+ resolution: {integrity: sha512-b+nUizoTQac0gNEaZ+F4XAYcFtynXufpGUYMkeSwfiD9najoQEKXpvZya8PgqX1Ddn3SPddeJ/ip+RS2oQuBLA==}
engines: {node: '>=20'}
- '@chat-adapter/[email protected]':
- resolution: {integrity: sha512-+L5LPj9VkyXFXAcfFlTvf2JihuFfQV5U9TfXDlQeG7k6NMEA8irt4a0c6MTxFP7OI5YENknVwRGzmcUubvEWSw==}
+ '@chat-adapter/[email protected]':
+ resolution: {integrity: sha512-QsxWce5OaY+j980dRCfFZSIoVHtg+gOg6p4IOWVsB4vxwXFin8CNg/hd34kvnmzqizbD/tmLze0Pkq/sKC4NLg==}
engines: {node: '>=20'}
'@chevrotain/[email protected]':
@@ -7447,8 +7447,8 @@ packages:
resolution: {integrity: sha512-PsezH1rqdV9VvyNhxxOW32/d75r01NY7TQCmOqomRo15ZSOKbpTFVsfjghxo6JloQUCGnH4k1LGu0R4yCLlWQQ==}
- resolution: {integrity: sha512-KdPfzaie5ivYytyRICTERg5xT+LeCbYefokvNAqTHe92eqkFaoTMXXkSitikxJVWhZIb2YoXF1b9UZHyzSzKzw==}
+ resolution: {integrity: sha512-F6oJq9JUraLFkITS96/NKgwZwBfZX8aOwOj5qMs5NNwnOGHrSXZ5+osK+EA4HjzfyUEDfFTNiOSmyzgtFLpuWg==}
engines: {node: '>=20'}
peerDependencies:
ai: ^6.0.182
@@ -13519,20 +13519,20 @@ snapshots:
human-id: 4.1.3
prettier: 2.8.8
dependencies:
transitivePeerDependencies:
- ai
- supports-color
- zod
dependencies:
- '@chat-adapter/shared': 4.29.0([email protected]([email protected]))([email protected])
+ '@chat-adapter/shared': 4.31.0([email protected]([email protected]))([email protected])
'@slack/socket-mode': 2.0.7
'@slack/web-api': 7.16.0
transitivePeerDependencies:
- ai
- bufferutil
@@ -13541,9 +13541,9 @@ snapshots:
- utf-8-validate
- zod
dependencies:
transitivePeerDependencies:
- ai
- supports-color
@@ -19722,7 +19722,7 @@ snapshots:
dependencies:
'@workflow/serde': 4.1.0-beta.2
mdast-util-to-string: 4.0.0