The Open Framework for Building Agents
refactor(slack): use chat sdk api primitives (#419)
josh087d6fd51042
diff --git a/.changeset/fresh-streets-bathe.md b/.changeset/fresh-streets-bathe.mdnew file mode 100644index 000000000..2fd2a95a7--- /dev/null+++ b/.changeset/fresh-streets-bathe.md@@ -0,0 +1,5 @@+---+"eve": patch+---++use chat sdk slack api primitives for slack channel api helpersdiff --git a/packages/eve/scripts/vendor-compiled/@chat-adapter/slack.mjs b/packages/eve/scripts/vendor-compiled/@chat-adapter/slack.mjsindex b1931f5ee..1e180e317 100644--- a/packages/eve/scripts/vendor-compiled/@chat-adapter/slack.mjs+++ b/packages/eve/scripts/vendor-compiled/@chat-adapter/slack.mjs@@ -82,6 +82,10 @@ export default {input: "@chat-adapter/slack/format",outputPath: "format",},+ {+ input: "@chat-adapter/slack/api",+ outputPath: "api",+ },],plugins: [createOptionalNativeStubPlugin(["bufferutil", "utf-8-validate"])],copyDeclarations: createDeclarationCopier({@@ -92,6 +96,7 @@ export default {{ source: "blocks.d.ts", output: "blocks.d.ts" },{ source: "webhook.d.ts", output: "webhook.d.ts" },{ source: "format.d.ts", output: "format.d.ts" },+ { source: "api.d.ts", output: "api.d.ts" },],rewrites: {chat: { kind: "vendored", compiledPath: "chat" },diff --git a/packages/eve/src/public/channels/slack/api.ts b/packages/eve/src/public/channels/slack/api.tsindex c18260f0f..f9b38b7f1 100644--- a/packages/eve/src/public/channels/slack/api.ts+++ b/packages/eve/src/public/channels/slack/api.ts@@ -15,10 +15,22 @@* without depending on each other.*/+import {+ callSlackApi as callSlackApiPrimitive,+ fetchSlackThreadReplies,+ postSlackEphemeral,+ postSlackMessage,+ resolveSlackBotToken as resolveSlackBotTokenPrimitive,+ uploadSlackFiles,+ type SlackApiOptions,+ type SlackApiResponse as SlackPrimitiveApiResponse,+ type SlackBotToken as SlackPrimitiveBotToken,+ type SlackFileUpload,+ type SlackMessageOptions,+} from "#compiled/@chat-adapter/slack/api.js";import { isCardElement, type CardElement, type FileUpload } from "#compiled/chat/index.js";import { createLogger, logError } from "#internal/logging.js";-import { encodeSlackApiBody } from "#public/channels/slack/api-encoding.js";import { cardToBlocks, cardToFallbackText } from "#public/channels/slack/blocks.js";import { truncateTypingStatus } from "#public/channels/slack/limits.js";import {@@ -34,7 +46,7 @@ const log = createLogger("slack.api");* as a (possibly async) function that returns one. The function form* supports secret-manager lookups and credential rotation.*/-export type SlackBotToken = string | (() => string | Promise<string>);+export type SlackBotToken = SlackPrimitiveBotToken;/*** Builds the channel-local continuation token (`<channelId>:<threadTs>`).@@ -54,7 +66,7 @@ export function slackContinuationToken(channelId: string, threadTs: string): strexport async function resolveSlackBotToken(token?: SlackBotToken): Promise<string> {const source = token ?? process.env.SLACK_BOT_TOKEN;if (!source) throw new Error("SLACK_BOT_TOKEN is required.");- return typeof source === "function" ? await source() : source;+ return resolveSlackBotTokenPrimitive(source);}/**@@ -62,11 +74,7 @@ export async function resolveSlackBotToken(token?: SlackBotToken): Promise<strin* carries Slack's error code on failure, and method-specific fields pass* through verbatim. Callers inspect `ok` themselves.*/-export interface SlackApiResponse {- readonly ok: boolean;- readonly error?: string;- readonly [key: string]: unknown;-}+export type SlackApiResponse = SlackPrimitiveApiResponse;/*** Low-level POST to a Slack Web API method, signed with the bot token@@ -79,17 +87,11 @@ export async function callSlackApi(input: {readonly operation: string;readonly body: unknown;}): Promise<SlackApiResponse> {- const token = await resolveSlackBotToken(input.botToken);- const encoded = encodeSlackApiBody(input.body);- const response = await fetch(`https://slack.com/api/${input.operation}`, {- method: "POST",- headers: {- authorization: `Bearer ${token}`,- "content-type": encoded.contentType,- },- body: encoded.body,- });- return response.json() as Promise<SlackApiResponse>;+ return callSlackApiPrimitive(+ input.operation,+ normalizeSlackApiBody(input.body),+ createSlackApiOptions(input.botToken),+ );}/**@@ -347,67 +349,14 @@ export function buildSlackBinding(input: {files: readonly FileUpload[],options?: SlackUploadFilesOptions,): Promise<SlackUploadFilesResult> {- if (files.length === 0) {- return { fileIds: [], raw: { ok: true } as SlackApiResponse };- }const channelId = options?.channelId ?? input.channelId;const threadTs = options?.threadTs ?? currentThreadTs;- const token = await resolveSlackBotToken(input.botToken);-- const fileIds: string[] = [];- for (const file of files) {- const bytes = await readFileBytes(file.data);- const getUrl = await callSlackApi({- botToken: input.botToken,- operation: "files.getUploadURLExternal",- body: {- filename: file.filename,- length: bytes.byteLength,- },- });- if (- getUrl.ok !== true ||- typeof getUrl.upload_url !== "string" ||- typeof getUrl.file_id !== "string"- ) {- throw new Error(- `Slack files.getUploadURLExternal failed: ${getUrl.error ?? "unknown_error"}`,- );- }- const uploadResponse = await fetch(getUrl.upload_url, {- method: "POST",- headers: {- authorization: `Bearer ${token}`,- "content-type": "application/octet-stream",- },- body: bytes,- });- if (!uploadResponse.ok) {- throw new Error(- `Slack upload POST returned HTTP ${uploadResponse.status} for ${file.filename}.`,- );- }- fileIds.push(getUrl.file_id);- }-- const completeBody: Record<string, unknown> = {- files: files.map((file, i) => ({ id: fileIds[i], title: file.filename })),- };- if (channelId) completeBody.channel_id = channelId;- if (threadTs) completeBody.thread_ts = threadTs;- if (options?.initialComment) completeBody.initial_comment = options.initialComment;-- const complete = await callSlackApi({- botToken: input.botToken,- operation: "files.completeUploadExternal",- body: completeBody,+ return uploadSlackFiles(files.map(toSlackFileUpload), {+ ...createSlackApiOptions(input.botToken),+ channelId: channelId || undefined,+ initialComment: options?.initialComment,+ threadTs: threadTs || undefined,});- if (complete.ok !== true) {- throw new Error(- `Slack files.completeUploadExternal failed: ${complete.error ?? "unknown_error"}`,- );- }- return { fileIds, raw: complete };}const thread: SlackThread = {@@ -434,12 +383,10 @@ export function buildSlackBinding(input: {return { id, raw: result.raw };}- const body = buildPostMessageBody(message, input.channelId, currentThreadTs);- const response = await request("chat.postMessage", body);- if (response.ok !== true) {- throw new Error(`Slack chat.postMessage failed: ${response.error ?? "unknown_error"}`);- }- const id = typeof response.ts === "string" ? response.ts : "";+ const response = await postSlackMessage(+ buildPostMessageOptions(message, input.channelId, currentThreadTs, input.botToken),+ );+ const id = response.id;handleMessageTs(id);// blocks / card + files: structured message lands first, then upload@@ -451,18 +398,15 @@ export function buildSlackBinding(input: {log.warn("file upload after structured post failed", { error });}}- return { id, raw: response };+ return { id, raw: response.raw };},async postEphemeral(userId, rawMessage) {const message = normalizePostInput(rawMessage);- const body = buildPostMessageBody(message, input.channelId, currentThreadTs);- body.user = userId;- const response = await request("chat.postEphemeral", body);- if (response.ok !== true) {- throw new Error(`Slack chat.postEphemeral failed: ${response.error ?? "unknown_error"}`);- }- const id = typeof response.message_ts === "string" ? response.message_ts : "";- return { id, raw: response };+ const response = await postSlackEphemeral({+ ...buildPostMessageOptions(message, input.channelId, currentThreadTs, input.botToken),+ user: userId,+ });+ return { id: response.id, raw: response.raw };},async postDirectMessage(userId, rawMessage) {const open = await request("conversations.open", { users: userId });@@ -472,12 +416,10 @@ export function buildSlackBinding(input: {throw new Error(`Slack conversations.open failed: ${open.error ?? "unknown_error"}`);}const message = normalizePostInput(rawMessage);- const body = buildPostMessageBody(message, imChannelId, "");- const response = await request("chat.postMessage", body);- if (response.ok !== true) {- throw new Error(`Slack chat.postMessage failed: ${response.error ?? "unknown_error"}`);- }- return { id: typeof response.ts === "string" ? response.ts : "", raw: response };+ const response = await postSlackMessage(+ buildPostMessageOptions(message, imChannelId, "", input.botToken),+ );+ return { id: response.id, raw: response.raw };},async startTyping(status) {if (!input.channelId || !currentThreadTs) return;@@ -505,15 +447,12 @@ export function buildSlackBinding(input: {messages.length = 0;if (!input.channelId || !currentThreadTs) return;try {- const response = await request("conversations.replies", {+ const response = await fetchSlackThreadReplies({+ ...createSlackApiOptions(input.botToken),channel: input.channelId,- ts: currentThreadTs,limit: 50,+ ts: currentThreadTs,});- if (response.ok !== true || !Array.isArray(response.messages)) {- log.warn("conversations.replies returned not-ok", { error: response.error });- return;- }for (const raw of response.messages as Record<string, unknown>[]) {messages.push(parseThreadMessage(raw, currentThreadTs));}@@ -556,17 +495,19 @@ function normalizePostInput(message: string | CardElement | SlackPostInput): Slareturn message;}-function buildPostMessageBody(+function buildPostMessageOptions(message: SlackPostInput,channelId: string,threadTs: string,-): Record<string, unknown> {- const base: Record<string, unknown> = {+ botToken: SlackBotToken | undefined,+): SlackMessageOptions {+ const base: SlackMessageOptions = {+ ...createSlackApiOptions(botToken),channel: channelId,- unfurl_links: false,- unfurl_media: false,+ threadTs: threadTs || undefined,+ unfurlLinks: false,+ unfurlMedia: false,};- if (threadTs) base.thread_ts = threadTs;if ("card" in message) {base.blocks = cardToBlocks(message.card);@@ -574,18 +515,46 @@ function buildPostMessageBody(return base;}if ("blocks" in message) {- base.blocks = message.blocks;+ base.blocks = [...message.blocks];if (message.text !== undefined) base.text = message.text;return base;}if ("markdown" in message) {- base.markdown_text = rewriteBareMentions(message.markdown);+ base.markdownText = rewriteBareMentions(message.markdown);return base;}base.text = rewriteBareMentions(message.text);return base;}+function createSlackApiOptions(botToken: SlackBotToken | undefined): SlackApiOptions {+ return { token: () => resolveSlackBotToken(botToken) };+}++function normalizeSlackApiBody(body: unknown): Record<string, unknown> {+ if (body && typeof body === "object" && !Array.isArray(body)) {+ return body as Record<string, unknown>;+ }+ return {};+}++function toSlackFileUpload(file: FileUpload): SlackFileUpload {+ return {+ data: normalizeFileData(file.data),+ filename: file.filename,+ };+}++function normalizeFileData(data: FileUpload["data"]): SlackFileUpload["data"] {+ if (data instanceof ArrayBuffer) return data;+ if (typeof Blob !== "undefined" && data instanceof Blob) return data;+ if (ArrayBuffer.isView(data)) {+ const view = data as ArrayBufferView;+ return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);+ }+ return data;+}+function parseThreadMessage(raw: Record<string, unknown>,threadRootTs: string,@@ -606,20 +575,3 @@ function parseThreadMessage(raw,};}--/**- * Normalize a {@link FileUpload.data} value (`Buffer | Blob | ArrayBuffer`) to- * a contiguous `Buffer` we can both POST and length-prefix without- * holding two copies of the payload in memory.- */-async function readFileBytes(data: FileUpload["data"]): Promise<Buffer> {- if (data instanceof ArrayBuffer) return Buffer.from(data);- if (typeof Blob !== "undefined" && data instanceof Blob) {- return Buffer.from(await data.arrayBuffer());- }- if (ArrayBuffer.isView(data)) {- const view = data as ArrayBufferView;- return Buffer.from(view.buffer, view.byteOffset, view.byteLength);- }- throw new Error("FileUpload.data must be a Buffer, ArrayBuffer, or Blob.");-}