chore: migrate to oxlint and oxfmt
Co-authored-by: Christoph Nakazawa <christoph.pojer@gmail.com>
This commit is contained in:
@@ -1,9 +1,6 @@
|
||||
import type { ClawdbotConfig } from "../config/config.js";
|
||||
import type { SlackAccountConfig } from "../config/types.js";
|
||||
import {
|
||||
DEFAULT_ACCOUNT_ID,
|
||||
normalizeAccountId,
|
||||
} from "../routing/session-key.js";
|
||||
import { DEFAULT_ACCOUNT_ID, normalizeAccountId } from "../routing/session-key.js";
|
||||
import { resolveSlackAppToken, resolveSlackBotToken } from "./token.js";
|
||||
|
||||
export type SlackTokenSource = "env" | "config" | "none";
|
||||
@@ -56,12 +53,10 @@ function resolveAccountConfig(
|
||||
return accounts[accountId] as SlackAccountConfig | undefined;
|
||||
}
|
||||
|
||||
function mergeSlackAccountConfig(
|
||||
cfg: ClawdbotConfig,
|
||||
accountId: string,
|
||||
): SlackAccountConfig {
|
||||
const { accounts: _ignored, ...base } = (cfg.channels?.slack ??
|
||||
{}) as SlackAccountConfig & { accounts?: unknown };
|
||||
function mergeSlackAccountConfig(cfg: ClawdbotConfig, accountId: string): SlackAccountConfig {
|
||||
const { accounts: _ignored, ...base } = (cfg.channels?.slack ?? {}) as SlackAccountConfig & {
|
||||
accounts?: unknown;
|
||||
};
|
||||
const account = resolveAccountConfig(cfg, accountId) ?? {};
|
||||
return { ...base, ...account };
|
||||
}
|
||||
@@ -76,26 +71,14 @@ export function resolveSlackAccount(params: {
|
||||
const accountEnabled = merged.enabled !== false;
|
||||
const enabled = baseEnabled && accountEnabled;
|
||||
const allowEnv = accountId === DEFAULT_ACCOUNT_ID;
|
||||
const envBot = allowEnv
|
||||
? resolveSlackBotToken(process.env.SLACK_BOT_TOKEN)
|
||||
: undefined;
|
||||
const envApp = allowEnv
|
||||
? resolveSlackAppToken(process.env.SLACK_APP_TOKEN)
|
||||
: undefined;
|
||||
const envBot = allowEnv ? resolveSlackBotToken(process.env.SLACK_BOT_TOKEN) : undefined;
|
||||
const envApp = allowEnv ? resolveSlackAppToken(process.env.SLACK_APP_TOKEN) : undefined;
|
||||
const configBot = resolveSlackBotToken(merged.botToken);
|
||||
const configApp = resolveSlackAppToken(merged.appToken);
|
||||
const botToken = configBot ?? envBot;
|
||||
const appToken = configApp ?? envApp;
|
||||
const botTokenSource: SlackTokenSource = configBot
|
||||
? "config"
|
||||
: envBot
|
||||
? "env"
|
||||
: "none";
|
||||
const appTokenSource: SlackTokenSource = configApp
|
||||
? "config"
|
||||
: envApp
|
||||
? "env"
|
||||
: "none";
|
||||
const botTokenSource: SlackTokenSource = configBot ? "config" : envBot ? "env" : "none";
|
||||
const appTokenSource: SlackTokenSource = configApp ? "config" : envApp ? "env" : "none";
|
||||
|
||||
return {
|
||||
accountId,
|
||||
@@ -119,9 +102,7 @@ export function resolveSlackAccount(params: {
|
||||
};
|
||||
}
|
||||
|
||||
export function listEnabledSlackAccounts(
|
||||
cfg: ClawdbotConfig,
|
||||
): ResolvedSlackAccount[] {
|
||||
export function listEnabledSlackAccounts(cfg: ClawdbotConfig): ResolvedSlackAccount[] {
|
||||
return listSlackAccountIds(cfg)
|
||||
.map((accountId) => resolveSlackAccount({ cfg, accountId }))
|
||||
.filter((account) => account.enabled);
|
||||
|
||||
@@ -41,9 +41,7 @@ function resolveToken(explicit?: string, accountId?: string) {
|
||||
explicit,
|
||||
)} source=${account.botTokenSource ?? "unknown"}`,
|
||||
);
|
||||
throw new Error(
|
||||
"SLACK_BOT_TOKEN or channels.slack.botToken is required for Slack actions",
|
||||
);
|
||||
throw new Error("SLACK_BOT_TOKEN or channels.slack.botToken is required for Slack actions");
|
||||
}
|
||||
return token;
|
||||
}
|
||||
@@ -203,10 +201,7 @@ export async function readSlackMessages(
|
||||
};
|
||||
}
|
||||
|
||||
export async function getSlackMemberInfo(
|
||||
userId: string,
|
||||
opts: SlackActionClientOpts = {},
|
||||
) {
|
||||
export async function getSlackMemberInfo(userId: string, opts: SlackActionClientOpts = {}) {
|
||||
const client = await getClient(opts);
|
||||
return await client.users.info({ user: userId });
|
||||
}
|
||||
|
||||
@@ -49,9 +49,7 @@ describe("markdownToSlackMrkdwn", () => {
|
||||
});
|
||||
|
||||
it("preserves Slack angle-bracket markup (mentions/links)", () => {
|
||||
const res = markdownToSlackMrkdwn(
|
||||
"hi <@U123> see <https://example.com|docs> and <!here>",
|
||||
);
|
||||
const res = markdownToSlackMrkdwn("hi <@U123> see <https://example.com|docs> and <!here>");
|
||||
expect(res).toBe("hi <@U123> see <https://example.com|docs> and <!here>");
|
||||
});
|
||||
|
||||
|
||||
@@ -29,10 +29,7 @@ md.enable("strikethrough");
|
||||
* can intentionally include them, while escaping other uses of "<" and ">".
|
||||
*/
|
||||
function escapeSlackMrkdwnSegment(text: string): string {
|
||||
return text
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">");
|
||||
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
}
|
||||
|
||||
const SLACK_ANGLE_TOKEN_RE = /<[^>\n]+>/g;
|
||||
@@ -69,9 +66,7 @@ function escapeSlackMrkdwnText(text: string): string {
|
||||
const matchIndex = match.index ?? 0;
|
||||
out.push(escapeSlackMrkdwnSegment(text.slice(lastIndex, matchIndex)));
|
||||
const token = match[0] ?? "";
|
||||
out.push(
|
||||
isAllowedSlackAngleToken(token) ? token : escapeSlackMrkdwnSegment(token),
|
||||
);
|
||||
out.push(isAllowedSlackAngleToken(token) ? token : escapeSlackMrkdwnSegment(token));
|
||||
lastIndex = matchIndex + token.length;
|
||||
}
|
||||
|
||||
@@ -89,8 +84,7 @@ function getLinkStack(env: RenderEnv): { href: string }[] {
|
||||
return env.slackLinkStack;
|
||||
}
|
||||
|
||||
md.renderer.rules.text = (tokens, idx) =>
|
||||
escapeSlackMrkdwnText(tokens[idx]?.content ?? "");
|
||||
md.renderer.rules.text = (tokens, idx) => escapeSlackMrkdwnText(tokens[idx]?.content ?? "");
|
||||
|
||||
md.renderer.rules.softbreak = () => "\n";
|
||||
md.renderer.rules.hardbreak = () => "\n";
|
||||
|
||||
@@ -36,10 +36,8 @@ vi.mock("./send.js", () => ({
|
||||
}));
|
||||
|
||||
vi.mock("../pairing/pairing-store.js", () => ({
|
||||
readChannelAllowFromStore: (...args: unknown[]) =>
|
||||
readAllowFromStoreMock(...args),
|
||||
upsertChannelPairingRequest: (...args: unknown[]) =>
|
||||
upsertPairingRequestMock(...args),
|
||||
readChannelAllowFromStore: (...args: unknown[]) => readAllowFromStoreMock(...args),
|
||||
upsertChannelPairingRequest: (...args: unknown[]) => upsertPairingRequestMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../config/sessions.js", () => ({
|
||||
@@ -50,8 +48,7 @@ vi.mock("../config/sessions.js", () => ({
|
||||
|
||||
vi.mock("@slack/bolt", () => {
|
||||
const handlers = new Map<string, (args: unknown) => Promise<void>>();
|
||||
(globalThis as { __slackHandlers?: typeof handlers }).__slackHandlers =
|
||||
handlers;
|
||||
(globalThis as { __slackHandlers?: typeof handlers }).__slackHandlers = handlers;
|
||||
const client = {
|
||||
auth: { test: vi.fn().mockResolvedValue({ user_id: "bot-user" }) },
|
||||
conversations: {
|
||||
@@ -118,9 +115,7 @@ beforeEach(() => {
|
||||
updateLastRouteMock.mockReset();
|
||||
reactMock.mockReset();
|
||||
readAllowFromStoreMock.mockReset().mockResolvedValue([]);
|
||||
upsertPairingRequestMock
|
||||
.mockReset()
|
||||
.mockResolvedValue({ code: "PAIRCODE", created: true });
|
||||
upsertPairingRequestMock.mockReset().mockResolvedValue({ code: "PAIRCODE", created: true });
|
||||
});
|
||||
|
||||
describe("monitorSlackProvider tool results", () => {
|
||||
@@ -255,12 +250,8 @@ describe("monitorSlackProvider tool results", () => {
|
||||
expect(replyMock).not.toHaveBeenCalled();
|
||||
expect(upsertPairingRequestMock).toHaveBeenCalled();
|
||||
expect(sendMock).toHaveBeenCalledTimes(1);
|
||||
expect(String(sendMock.mock.calls[0]?.[1] ?? "")).toContain(
|
||||
"Your Slack user id: U1",
|
||||
);
|
||||
expect(String(sendMock.mock.calls[0]?.[1] ?? "")).toContain(
|
||||
"Pairing code: PAIRCODE",
|
||||
);
|
||||
expect(String(sendMock.mock.calls[0]?.[1] ?? "")).toContain("Your Slack user id: U1");
|
||||
expect(String(sendMock.mock.calls[0]?.[1] ?? "")).toContain("Pairing code: PAIRCODE");
|
||||
});
|
||||
|
||||
it("does not resend pairing code when a request is already pending", async () => {
|
||||
|
||||
@@ -38,10 +38,8 @@ vi.mock("./send.js", () => ({
|
||||
}));
|
||||
|
||||
vi.mock("../pairing/pairing-store.js", () => ({
|
||||
readChannelAllowFromStore: (...args: unknown[]) =>
|
||||
readAllowFromStoreMock(...args),
|
||||
upsertChannelPairingRequest: (...args: unknown[]) =>
|
||||
upsertPairingRequestMock(...args),
|
||||
readChannelAllowFromStore: (...args: unknown[]) => readAllowFromStoreMock(...args),
|
||||
upsertChannelPairingRequest: (...args: unknown[]) => upsertPairingRequestMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../config/sessions.js", () => ({
|
||||
@@ -52,8 +50,7 @@ vi.mock("../config/sessions.js", () => ({
|
||||
|
||||
vi.mock("@slack/bolt", () => {
|
||||
const handlers = new Map<string, (args: unknown) => Promise<void>>();
|
||||
(globalThis as { __slackHandlers?: typeof handlers }).__slackHandlers =
|
||||
handlers;
|
||||
(globalThis as { __slackHandlers?: typeof handlers }).__slackHandlers = handlers;
|
||||
const client = {
|
||||
auth: { test: vi.fn().mockResolvedValue({ user_id: "bot-user" }) },
|
||||
conversations: {
|
||||
@@ -120,9 +117,7 @@ beforeEach(() => {
|
||||
updateLastRouteMock.mockReset();
|
||||
reactMock.mockReset();
|
||||
readAllowFromStoreMock.mockReset().mockResolvedValue([]);
|
||||
upsertPairingRequestMock
|
||||
.mockReset()
|
||||
.mockResolvedValue({ code: "PAIRCODE", created: true });
|
||||
upsertPairingRequestMock.mockReset().mockResolvedValue({ code: "PAIRCODE", created: true });
|
||||
});
|
||||
|
||||
describe("monitorSlackProvider tool results", () => {
|
||||
@@ -241,8 +236,7 @@ describe("monitorSlackProvider tool results", () => {
|
||||
},
|
||||
};
|
||||
|
||||
let capturedCtx: { Body?: string; RawBody?: string; CommandBody?: string } =
|
||||
{};
|
||||
let capturedCtx: { Body?: string; RawBody?: string; CommandBody?: string } = {};
|
||||
replyMock.mockImplementation(async (ctx) => {
|
||||
capturedCtx = ctx ?? {};
|
||||
return undefined;
|
||||
|
||||
@@ -36,10 +36,8 @@ vi.mock("./send.js", () => ({
|
||||
}));
|
||||
|
||||
vi.mock("../pairing/pairing-store.js", () => ({
|
||||
readChannelAllowFromStore: (...args: unknown[]) =>
|
||||
readAllowFromStoreMock(...args),
|
||||
upsertChannelPairingRequest: (...args: unknown[]) =>
|
||||
upsertPairingRequestMock(...args),
|
||||
readChannelAllowFromStore: (...args: unknown[]) => readAllowFromStoreMock(...args),
|
||||
upsertChannelPairingRequest: (...args: unknown[]) => upsertPairingRequestMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../config/sessions.js", () => ({
|
||||
@@ -50,8 +48,7 @@ vi.mock("../config/sessions.js", () => ({
|
||||
|
||||
vi.mock("@slack/bolt", () => {
|
||||
const handlers = new Map<string, (args: unknown) => Promise<void>>();
|
||||
(globalThis as { __slackHandlers?: typeof handlers }).__slackHandlers =
|
||||
handlers;
|
||||
(globalThis as { __slackHandlers?: typeof handlers }).__slackHandlers = handlers;
|
||||
const client = {
|
||||
auth: { test: vi.fn().mockResolvedValue({ user_id: "bot-user" }) },
|
||||
conversations: {
|
||||
@@ -118,9 +115,7 @@ beforeEach(() => {
|
||||
updateLastRouteMock.mockReset();
|
||||
reactMock.mockReset();
|
||||
readAllowFromStoreMock.mockReset().mockResolvedValue([]);
|
||||
upsertPairingRequestMock
|
||||
.mockReset()
|
||||
.mockResolvedValue({ code: "PAIRCODE", created: true });
|
||||
upsertPairingRequestMock.mockReset().mockResolvedValue({ code: "PAIRCODE", created: true });
|
||||
});
|
||||
|
||||
describe("monitorSlackProvider tool results", () => {
|
||||
@@ -285,9 +280,7 @@ describe("monitorSlackProvider tool results", () => {
|
||||
channels: { C1: { allow: true, requireMention: false } },
|
||||
},
|
||||
},
|
||||
bindings: [
|
||||
{ agentId: "support", match: { channel: "slack", teamId: "T1" } },
|
||||
],
|
||||
bindings: [{ agentId: "support", match: { channel: "slack", teamId: "T1" } }],
|
||||
};
|
||||
|
||||
const client = getSlackClient();
|
||||
@@ -335,9 +328,7 @@ describe("monitorSlackProvider tool results", () => {
|
||||
SessionKey?: string;
|
||||
ParentSessionKey?: string;
|
||||
};
|
||||
expect(ctx.SessionKey).toBe(
|
||||
"agent:support:slack:channel:C1:thread:111.222",
|
||||
);
|
||||
expect(ctx.SessionKey).toBe("agent:support:slack:channel:C1:thread:111.222");
|
||||
expect(ctx.ParentSessionKey).toBe("agent:support:slack:channel:C1");
|
||||
});
|
||||
|
||||
|
||||
@@ -14,11 +14,7 @@ export function normalizeAllowListLower(list?: Array<string | number>) {
|
||||
return normalizeAllowList(list).map((entry) => entry.toLowerCase());
|
||||
}
|
||||
|
||||
export function allowListMatches(params: {
|
||||
allowList: string[];
|
||||
id?: string;
|
||||
name?: string;
|
||||
}) {
|
||||
export function allowListMatches(params: { allowList: string[]; id?: string; name?: string }) {
|
||||
const allowList = params.allowList;
|
||||
if (allowList.length === 0) return false;
|
||||
if (allowList.includes("*")) return true;
|
||||
|
||||
@@ -1,16 +1,10 @@
|
||||
import { readChannelAllowFromStore } from "../../pairing/pairing-store.js";
|
||||
|
||||
import {
|
||||
allowListMatches,
|
||||
normalizeAllowList,
|
||||
normalizeAllowListLower,
|
||||
} from "./allow-list.js";
|
||||
import { allowListMatches, normalizeAllowList, normalizeAllowListLower } from "./allow-list.js";
|
||||
import type { SlackMonitorContext } from "./context.js";
|
||||
|
||||
export async function resolveSlackEffectiveAllowFrom(ctx: SlackMonitorContext) {
|
||||
const storeAllowFrom = await readChannelAllowFromStore("slack").catch(
|
||||
() => [],
|
||||
);
|
||||
const storeAllowFrom = await readChannelAllowFromStore("slack").catch(() => []);
|
||||
const allowFrom = normalizeAllowList([...ctx.allowFrom, ...storeAllowFrom]);
|
||||
const allowFromLower = normalizeAllowListLower(allowFrom);
|
||||
return { allowFrom, allowFromLower };
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import type { SlackReactionNotificationMode } from "../../config/config.js";
|
||||
import type { SlackMessageEvent } from "../types.js";
|
||||
import {
|
||||
allowListMatches,
|
||||
normalizeAllowListLower,
|
||||
normalizeSlackSlug,
|
||||
} from "./allow-list.js";
|
||||
import { allowListMatches, normalizeAllowListLower, normalizeSlackSlug } from "./allow-list.js";
|
||||
|
||||
export type SlackChannelConfigResolved = {
|
||||
allowed: boolean;
|
||||
@@ -49,10 +45,7 @@ export function shouldEmitSlackReactionNotification(params: {
|
||||
return true;
|
||||
}
|
||||
|
||||
export function resolveSlackChannelLabel(params: {
|
||||
channelId?: string;
|
||||
channelName?: string;
|
||||
}) {
|
||||
export function resolveSlackChannelLabel(params: { channelId?: string; channelName?: string }) {
|
||||
const channelName = params.channelName?.trim();
|
||||
if (channelName) {
|
||||
const slug = normalizeSlackSlug(channelName);
|
||||
@@ -118,23 +111,14 @@ export function resolveSlackChannelConfig(params: {
|
||||
|
||||
const resolved = matched ?? fallback ?? {};
|
||||
const allowed =
|
||||
firstDefined(
|
||||
resolved.enabled,
|
||||
resolved.allow,
|
||||
fallback?.enabled,
|
||||
fallback?.allow,
|
||||
true,
|
||||
) ?? true;
|
||||
const requireMention =
|
||||
firstDefined(resolved.requireMention, fallback?.requireMention, true) ??
|
||||
firstDefined(resolved.enabled, resolved.allow, fallback?.enabled, fallback?.allow, true) ??
|
||||
true;
|
||||
const requireMention =
|
||||
firstDefined(resolved.requireMention, fallback?.requireMention, true) ?? true;
|
||||
const allowBots = firstDefined(resolved.allowBots, fallback?.allowBots);
|
||||
const users = firstDefined(resolved.users, fallback?.users);
|
||||
const skills = firstDefined(resolved.skills, fallback?.skills);
|
||||
const systemPrompt = firstDefined(
|
||||
resolved.systemPrompt,
|
||||
fallback?.systemPrompt,
|
||||
);
|
||||
const systemPrompt = firstDefined(resolved.systemPrompt, fallback?.systemPrompt);
|
||||
return { allowed, requireMention, allowBots, users, skills, systemPrompt };
|
||||
}
|
||||
|
||||
|
||||
@@ -7,9 +7,7 @@ export function normalizeSlackSlashCommandName(raw: string) {
|
||||
export function resolveSlackSlashCommandConfig(
|
||||
raw?: SlackSlashCommandConfig,
|
||||
): Required<SlackSlashCommandConfig> {
|
||||
const normalizedName = normalizeSlackSlashCommandName(
|
||||
raw?.name?.trim() || "clawd",
|
||||
);
|
||||
const normalizedName = normalizeSlackSlashCommandName(raw?.name?.trim() || "clawd");
|
||||
const name = normalizedName || "clawd";
|
||||
return {
|
||||
enabled: raw?.enabled === true,
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import type { App } from "@slack/bolt";
|
||||
import type { HistoryEntry } from "../../auto-reply/reply/history.js";
|
||||
import type {
|
||||
ClawdbotConfig,
|
||||
SlackReactionNotificationMode,
|
||||
} from "../../config/config.js";
|
||||
import type { ClawdbotConfig, SlackReactionNotificationMode } from "../../config/config.js";
|
||||
import { resolveSessionKey, type SessionScope } from "../../config/sessions.js";
|
||||
import type { DmPolicy, GroupPolicy } from "../../config/types.js";
|
||||
import { logVerbose } from "../../globals.js";
|
||||
@@ -12,11 +9,7 @@ import { getChildLogger } from "../../logging.js";
|
||||
import type { RuntimeEnv } from "../../runtime.js";
|
||||
import type { SlackMessageEvent } from "../types.js";
|
||||
|
||||
import {
|
||||
normalizeAllowList,
|
||||
normalizeAllowListLower,
|
||||
normalizeSlackSlug,
|
||||
} from "./allow-list.js";
|
||||
import { normalizeAllowList, normalizeAllowListLower, normalizeSlackSlug } from "./allow-list.js";
|
||||
import { resolveSlackChannelConfig } from "./channel-config.js";
|
||||
import { isSlackRoomAllowedByPolicy } from "./policy.js";
|
||||
|
||||
@@ -57,9 +50,7 @@ export type SlackMonitorContext = {
|
||||
reactionMode: SlackReactionNotificationMode;
|
||||
reactionAllowlist: Array<string | number>;
|
||||
replyToMode: "off" | "first" | "all";
|
||||
slashCommand: Required<
|
||||
import("../../config/config.js").SlackSlashCommandConfig
|
||||
>;
|
||||
slashCommand: Required<import("../../config/config.js").SlackSlashCommandConfig>;
|
||||
textLimit: number;
|
||||
ackReactionScope: string;
|
||||
mediaMaxBytes: number;
|
||||
@@ -174,8 +165,7 @@ export function createSlackMonitorContext(params: {
|
||||
token: params.botToken,
|
||||
channel: channelId,
|
||||
});
|
||||
const name =
|
||||
info.channel && "name" in info.channel ? info.channel.name : undefined;
|
||||
const name = info.channel && "name" in info.channel ? info.channel.name : undefined;
|
||||
const channel = info.channel ?? undefined;
|
||||
const type: SlackMessageEvent["channel_type"] | undefined = channel?.is_im
|
||||
? "im"
|
||||
@@ -186,14 +176,9 @@ export function createSlackMonitorContext(params: {
|
||||
: channel?.is_group
|
||||
? "group"
|
||||
: undefined;
|
||||
const topic =
|
||||
channel && "topic" in channel
|
||||
? (channel.topic?.value ?? undefined)
|
||||
: undefined;
|
||||
const topic = channel && "topic" in channel ? (channel.topic?.value ?? undefined) : undefined;
|
||||
const purpose =
|
||||
channel && "purpose" in channel
|
||||
? (channel.purpose?.value ?? undefined)
|
||||
: undefined;
|
||||
channel && "purpose" in channel ? (channel.purpose?.value ?? undefined) : undefined;
|
||||
const entry = { name, type, topic, purpose };
|
||||
channelCache.set(channelId, entry);
|
||||
return entry;
|
||||
@@ -211,11 +196,7 @@ export function createSlackMonitorContext(params: {
|
||||
user: userId,
|
||||
});
|
||||
const profile = info.user?.profile;
|
||||
const name =
|
||||
profile?.display_name ||
|
||||
profile?.real_name ||
|
||||
info.user?.name ||
|
||||
undefined;
|
||||
const name = profile?.display_name || profile?.real_name || info.user?.name || undefined;
|
||||
const entry = { name };
|
||||
userCache.set(userId, entry);
|
||||
return entry;
|
||||
@@ -253,9 +234,7 @@ export function createSlackMonitorContext(params: {
|
||||
await client.apiCall("assistant.threads.setStatus", payload);
|
||||
}
|
||||
} catch (err) {
|
||||
logVerbose(
|
||||
`slack status update failed for channel ${p.channelId}: ${String(err)}`,
|
||||
);
|
||||
logVerbose(`slack status update failed for channel ${p.channelId}: ${String(err)}`);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -283,8 +262,7 @@ export function createSlackMonitorContext(params: {
|
||||
.filter((value): value is string => Boolean(value))
|
||||
.map((value) => value.toLowerCase());
|
||||
const permitted =
|
||||
allowList.includes("*") ||
|
||||
candidates.some((candidate) => allowList.includes(candidate));
|
||||
allowList.includes("*") || candidates.some((candidate) => allowList.includes(candidate));
|
||||
if (!permitted) return false;
|
||||
}
|
||||
|
||||
@@ -296,8 +274,7 @@ export function createSlackMonitorContext(params: {
|
||||
});
|
||||
const channelAllowed = channelConfig?.allowed !== false;
|
||||
const channelAllowlistConfigured =
|
||||
Boolean(params.channelsConfig) &&
|
||||
Object.keys(params.channelsConfig ?? {}).length > 0;
|
||||
Boolean(params.channelsConfig) && Object.keys(params.channelsConfig ?? {}).length > 0;
|
||||
if (
|
||||
!isSlackRoomAllowedByPolicy({
|
||||
groupPolicy: params.groupPolicy,
|
||||
|
||||
@@ -5,14 +5,9 @@ import { enqueueSystemEvent } from "../../../infra/system-events.js";
|
||||
|
||||
import { resolveSlackChannelLabel } from "../channel-config.js";
|
||||
import type { SlackMonitorContext } from "../context.js";
|
||||
import type {
|
||||
SlackChannelCreatedEvent,
|
||||
SlackChannelRenamedEvent,
|
||||
} from "../types.js";
|
||||
import type { SlackChannelCreatedEvent, SlackChannelRenamedEvent } from "../types.js";
|
||||
|
||||
export function registerSlackChannelEvents(params: {
|
||||
ctx: SlackMonitorContext;
|
||||
}) {
|
||||
export function registerSlackChannelEvents(params: { ctx: SlackMonitorContext }) {
|
||||
const { ctx } = params;
|
||||
|
||||
ctx.app.event(
|
||||
@@ -41,44 +36,36 @@ export function registerSlackChannelEvents(params: {
|
||||
contextKey: `slack:channel:created:${channelId ?? channelName ?? "unknown"}`,
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.runtime.error?.(
|
||||
danger(`slack channel created handler failed: ${String(err)}`),
|
||||
);
|
||||
ctx.runtime.error?.(danger(`slack channel created handler failed: ${String(err)}`));
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
ctx.app.event(
|
||||
"channel_rename",
|
||||
async ({ event }: SlackEventMiddlewareArgs<"channel_rename">) => {
|
||||
try {
|
||||
const payload = event as SlackChannelRenamedEvent;
|
||||
const channelId = payload.channel?.id;
|
||||
const channelName =
|
||||
payload.channel?.name_normalized ?? payload.channel?.name;
|
||||
if (
|
||||
!ctx.isChannelAllowed({
|
||||
channelId,
|
||||
channelName,
|
||||
channelType: "channel",
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const label = resolveSlackChannelLabel({ channelId, channelName });
|
||||
const sessionKey = ctx.resolveSlackSystemEventSessionKey({
|
||||
ctx.app.event("channel_rename", async ({ event }: SlackEventMiddlewareArgs<"channel_rename">) => {
|
||||
try {
|
||||
const payload = event as SlackChannelRenamedEvent;
|
||||
const channelId = payload.channel?.id;
|
||||
const channelName = payload.channel?.name_normalized ?? payload.channel?.name;
|
||||
if (
|
||||
!ctx.isChannelAllowed({
|
||||
channelId,
|
||||
channelName,
|
||||
channelType: "channel",
|
||||
});
|
||||
enqueueSystemEvent(`Slack channel renamed: ${label}.`, {
|
||||
sessionKey,
|
||||
contextKey: `slack:channel:renamed:${channelId ?? channelName ?? "unknown"}`,
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.runtime.error?.(
|
||||
danger(`slack channel rename handler failed: ${String(err)}`),
|
||||
);
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
},
|
||||
);
|
||||
const label = resolveSlackChannelLabel({ channelId, channelName });
|
||||
const sessionKey = ctx.resolveSlackSystemEventSessionKey({
|
||||
channelId,
|
||||
channelType: "channel",
|
||||
});
|
||||
enqueueSystemEvent(`Slack channel renamed: ${label}.`, {
|
||||
sessionKey,
|
||||
contextKey: `slack:channel:renamed:${channelId ?? channelName ?? "unknown"}`,
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.runtime.error?.(danger(`slack channel rename handler failed: ${String(err)}`));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,9 +7,7 @@ import { resolveSlackChannelLabel } from "../channel-config.js";
|
||||
import type { SlackMonitorContext } from "../context.js";
|
||||
import type { SlackMemberChannelEvent } from "../types.js";
|
||||
|
||||
export function registerSlackMemberEvents(params: {
|
||||
ctx: SlackMonitorContext;
|
||||
}) {
|
||||
export function registerSlackMemberEvents(params: { ctx: SlackMonitorContext }) {
|
||||
const { ctx } = params;
|
||||
|
||||
ctx.app.event(
|
||||
@@ -18,9 +16,7 @@ export function registerSlackMemberEvents(params: {
|
||||
try {
|
||||
const payload = event as SlackMemberChannelEvent;
|
||||
const channelId = payload.channel;
|
||||
const channelInfo = channelId
|
||||
? await ctx.resolveChannelName(channelId)
|
||||
: {};
|
||||
const channelInfo = channelId ? await ctx.resolveChannelName(channelId) : {};
|
||||
const channelType = payload.channel_type ?? channelInfo?.type;
|
||||
if (
|
||||
!ctx.isChannelAllowed({
|
||||
@@ -31,9 +27,7 @@ export function registerSlackMemberEvents(params: {
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const userInfo = payload.user
|
||||
? await ctx.resolveUserName(payload.user)
|
||||
: {};
|
||||
const userInfo = payload.user ? await ctx.resolveUserName(payload.user) : {};
|
||||
const userLabel = userInfo?.name ?? payload.user ?? "someone";
|
||||
const label = resolveSlackChannelLabel({
|
||||
channelId,
|
||||
@@ -48,9 +42,7 @@ export function registerSlackMemberEvents(params: {
|
||||
contextKey: `slack:member:joined:${channelId ?? "unknown"}:${payload.user ?? "unknown"}`,
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.runtime.error?.(
|
||||
danger(`slack join handler failed: ${String(err)}`),
|
||||
);
|
||||
ctx.runtime.error?.(danger(`slack join handler failed: ${String(err)}`));
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -61,9 +53,7 @@ export function registerSlackMemberEvents(params: {
|
||||
try {
|
||||
const payload = event as SlackMemberChannelEvent;
|
||||
const channelId = payload.channel;
|
||||
const channelInfo = channelId
|
||||
? await ctx.resolveChannelName(channelId)
|
||||
: {};
|
||||
const channelInfo = channelId ? await ctx.resolveChannelName(channelId) : {};
|
||||
const channelType = payload.channel_type ?? channelInfo?.type;
|
||||
if (
|
||||
!ctx.isChannelAllowed({
|
||||
@@ -74,9 +64,7 @@ export function registerSlackMemberEvents(params: {
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const userInfo = payload.user
|
||||
? await ctx.resolveUserName(payload.user)
|
||||
: {};
|
||||
const userInfo = payload.user ? await ctx.resolveUserName(payload.user) : {};
|
||||
const userLabel = userInfo?.name ?? payload.user ?? "someone";
|
||||
const label = resolveSlackChannelLabel({
|
||||
channelId,
|
||||
@@ -91,9 +79,7 @@ export function registerSlackMemberEvents(params: {
|
||||
contextKey: `slack:member:left:${channelId ?? "unknown"}:${payload.user ?? "unknown"}`,
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.runtime.error?.(
|
||||
danger(`slack leave handler failed: ${String(err)}`),
|
||||
);
|
||||
ctx.runtime.error?.(danger(`slack leave handler failed: ${String(err)}`));
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -19,124 +19,110 @@ export function registerSlackMessageEvents(params: {
|
||||
}) {
|
||||
const { ctx, handleSlackMessage } = params;
|
||||
|
||||
ctx.app.event(
|
||||
"message",
|
||||
async ({ event }: SlackEventMiddlewareArgs<"message">) => {
|
||||
try {
|
||||
const message = event as SlackMessageEvent;
|
||||
if (message.subtype === "message_changed") {
|
||||
const changed = event as SlackMessageChangedEvent;
|
||||
const channelId = changed.channel;
|
||||
const channelInfo = channelId
|
||||
? await ctx.resolveChannelName(channelId)
|
||||
: {};
|
||||
const channelType = channelInfo?.type;
|
||||
if (
|
||||
!ctx.isChannelAllowed({
|
||||
channelId,
|
||||
channelName: channelInfo?.name,
|
||||
channelType,
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const messageId = changed.message?.ts ?? changed.previous_message?.ts;
|
||||
const label = resolveSlackChannelLabel({
|
||||
ctx.app.event("message", async ({ event }: SlackEventMiddlewareArgs<"message">) => {
|
||||
try {
|
||||
const message = event as SlackMessageEvent;
|
||||
if (message.subtype === "message_changed") {
|
||||
const changed = event as SlackMessageChangedEvent;
|
||||
const channelId = changed.channel;
|
||||
const channelInfo = channelId ? await ctx.resolveChannelName(channelId) : {};
|
||||
const channelType = channelInfo?.type;
|
||||
if (
|
||||
!ctx.isChannelAllowed({
|
||||
channelId,
|
||||
channelName: channelInfo?.name,
|
||||
});
|
||||
const sessionKey = ctx.resolveSlackSystemEventSessionKey({
|
||||
channelId,
|
||||
channelType,
|
||||
});
|
||||
enqueueSystemEvent(`Slack message edited in ${label}.`, {
|
||||
sessionKey,
|
||||
contextKey: `slack:message:changed:${channelId ?? "unknown"}:${messageId ?? changed.event_ts ?? "unknown"}`,
|
||||
});
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (message.subtype === "message_deleted") {
|
||||
const deleted = event as SlackMessageDeletedEvent;
|
||||
const channelId = deleted.channel;
|
||||
const channelInfo = channelId
|
||||
? await ctx.resolveChannelName(channelId)
|
||||
: {};
|
||||
const channelType = channelInfo?.type;
|
||||
if (
|
||||
!ctx.isChannelAllowed({
|
||||
channelId,
|
||||
channelName: channelInfo?.name,
|
||||
channelType,
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const label = resolveSlackChannelLabel({
|
||||
channelId,
|
||||
channelName: channelInfo?.name,
|
||||
});
|
||||
const sessionKey = ctx.resolveSlackSystemEventSessionKey({
|
||||
channelId,
|
||||
channelType,
|
||||
});
|
||||
enqueueSystemEvent(`Slack message deleted in ${label}.`, {
|
||||
sessionKey,
|
||||
contextKey: `slack:message:deleted:${channelId ?? "unknown"}:${deleted.deleted_ts ?? deleted.event_ts ?? "unknown"}`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (message.subtype === "thread_broadcast") {
|
||||
const thread = event as SlackThreadBroadcastEvent;
|
||||
const channelId = thread.channel;
|
||||
const channelInfo = channelId
|
||||
? await ctx.resolveChannelName(channelId)
|
||||
: {};
|
||||
const channelType = channelInfo?.type;
|
||||
if (
|
||||
!ctx.isChannelAllowed({
|
||||
channelId,
|
||||
channelName: channelInfo?.name,
|
||||
channelType,
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const label = resolveSlackChannelLabel({
|
||||
channelId,
|
||||
channelName: channelInfo?.name,
|
||||
});
|
||||
const messageId = thread.message?.ts ?? thread.event_ts;
|
||||
const sessionKey = ctx.resolveSlackSystemEventSessionKey({
|
||||
channelId,
|
||||
channelType,
|
||||
});
|
||||
enqueueSystemEvent(`Slack thread reply broadcast in ${label}.`, {
|
||||
sessionKey,
|
||||
contextKey: `slack:thread:broadcast:${channelId ?? "unknown"}:${messageId ?? "unknown"}`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
await handleSlackMessage(message, { source: "message" });
|
||||
} catch (err) {
|
||||
ctx.runtime.error?.(danger(`slack handler failed: ${String(err)}`));
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
ctx.app.event(
|
||||
"app_mention",
|
||||
async ({ event }: SlackEventMiddlewareArgs<"app_mention">) => {
|
||||
try {
|
||||
const mention = event as SlackAppMentionEvent;
|
||||
await handleSlackMessage(mention as unknown as SlackMessageEvent, {
|
||||
source: "app_mention",
|
||||
wasMentioned: true,
|
||||
const messageId = changed.message?.ts ?? changed.previous_message?.ts;
|
||||
const label = resolveSlackChannelLabel({
|
||||
channelId,
|
||||
channelName: channelInfo?.name,
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.runtime.error?.(
|
||||
danger(`slack mention handler failed: ${String(err)}`),
|
||||
);
|
||||
const sessionKey = ctx.resolveSlackSystemEventSessionKey({
|
||||
channelId,
|
||||
channelType,
|
||||
});
|
||||
enqueueSystemEvent(`Slack message edited in ${label}.`, {
|
||||
sessionKey,
|
||||
contextKey: `slack:message:changed:${channelId ?? "unknown"}:${messageId ?? changed.event_ts ?? "unknown"}`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
},
|
||||
);
|
||||
if (message.subtype === "message_deleted") {
|
||||
const deleted = event as SlackMessageDeletedEvent;
|
||||
const channelId = deleted.channel;
|
||||
const channelInfo = channelId ? await ctx.resolveChannelName(channelId) : {};
|
||||
const channelType = channelInfo?.type;
|
||||
if (
|
||||
!ctx.isChannelAllowed({
|
||||
channelId,
|
||||
channelName: channelInfo?.name,
|
||||
channelType,
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const label = resolveSlackChannelLabel({
|
||||
channelId,
|
||||
channelName: channelInfo?.name,
|
||||
});
|
||||
const sessionKey = ctx.resolveSlackSystemEventSessionKey({
|
||||
channelId,
|
||||
channelType,
|
||||
});
|
||||
enqueueSystemEvent(`Slack message deleted in ${label}.`, {
|
||||
sessionKey,
|
||||
contextKey: `slack:message:deleted:${channelId ?? "unknown"}:${deleted.deleted_ts ?? deleted.event_ts ?? "unknown"}`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (message.subtype === "thread_broadcast") {
|
||||
const thread = event as SlackThreadBroadcastEvent;
|
||||
const channelId = thread.channel;
|
||||
const channelInfo = channelId ? await ctx.resolveChannelName(channelId) : {};
|
||||
const channelType = channelInfo?.type;
|
||||
if (
|
||||
!ctx.isChannelAllowed({
|
||||
channelId,
|
||||
channelName: channelInfo?.name,
|
||||
channelType,
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const label = resolveSlackChannelLabel({
|
||||
channelId,
|
||||
channelName: channelInfo?.name,
|
||||
});
|
||||
const messageId = thread.message?.ts ?? thread.event_ts;
|
||||
const sessionKey = ctx.resolveSlackSystemEventSessionKey({
|
||||
channelId,
|
||||
channelType,
|
||||
});
|
||||
enqueueSystemEvent(`Slack thread reply broadcast in ${label}.`, {
|
||||
sessionKey,
|
||||
contextKey: `slack:thread:broadcast:${channelId ?? "unknown"}:${messageId ?? "unknown"}`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
await handleSlackMessage(message, { source: "message" });
|
||||
} catch (err) {
|
||||
ctx.runtime.error?.(danger(`slack handler failed: ${String(err)}`));
|
||||
}
|
||||
});
|
||||
|
||||
ctx.app.event("app_mention", async ({ event }: SlackEventMiddlewareArgs<"app_mention">) => {
|
||||
try {
|
||||
const mention = event as SlackAppMentionEvent;
|
||||
await handleSlackMessage(mention as unknown as SlackMessageEvent, {
|
||||
source: "app_mention",
|
||||
wasMentioned: true,
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.runtime.error?.(danger(`slack mention handler failed: ${String(err)}`));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -10,97 +10,73 @@ import type { SlackPinEvent } from "../types.js";
|
||||
export function registerSlackPinEvents(params: { ctx: SlackMonitorContext }) {
|
||||
const { ctx } = params;
|
||||
|
||||
ctx.app.event(
|
||||
"pin_added",
|
||||
async ({ event }: SlackEventMiddlewareArgs<"pin_added">) => {
|
||||
try {
|
||||
const payload = event as SlackPinEvent;
|
||||
const channelId = payload.channel_id;
|
||||
const channelInfo = channelId
|
||||
? await ctx.resolveChannelName(channelId)
|
||||
: {};
|
||||
if (
|
||||
!ctx.isChannelAllowed({
|
||||
channelId,
|
||||
channelName: channelInfo?.name,
|
||||
channelType: channelInfo?.type,
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const label = resolveSlackChannelLabel({
|
||||
ctx.app.event("pin_added", async ({ event }: SlackEventMiddlewareArgs<"pin_added">) => {
|
||||
try {
|
||||
const payload = event as SlackPinEvent;
|
||||
const channelId = payload.channel_id;
|
||||
const channelInfo = channelId ? await ctx.resolveChannelName(channelId) : {};
|
||||
if (
|
||||
!ctx.isChannelAllowed({
|
||||
channelId,
|
||||
channelName: channelInfo?.name,
|
||||
});
|
||||
const userInfo = payload.user
|
||||
? await ctx.resolveUserName(payload.user)
|
||||
: {};
|
||||
const userLabel = userInfo?.name ?? payload.user ?? "someone";
|
||||
const itemType = payload.item?.type ?? "item";
|
||||
const messageId = payload.item?.message?.ts ?? payload.event_ts;
|
||||
const sessionKey = ctx.resolveSlackSystemEventSessionKey({
|
||||
channelId,
|
||||
channelType: channelInfo?.type ?? undefined,
|
||||
});
|
||||
enqueueSystemEvent(
|
||||
`Slack: ${userLabel} pinned a ${itemType} in ${label}.`,
|
||||
{
|
||||
sessionKey,
|
||||
contextKey: `slack:pin:added:${channelId ?? "unknown"}:${messageId ?? "unknown"}`,
|
||||
},
|
||||
);
|
||||
} catch (err) {
|
||||
ctx.runtime.error?.(
|
||||
danger(`slack pin added handler failed: ${String(err)}`),
|
||||
);
|
||||
channelType: channelInfo?.type,
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
},
|
||||
);
|
||||
const label = resolveSlackChannelLabel({
|
||||
channelId,
|
||||
channelName: channelInfo?.name,
|
||||
});
|
||||
const userInfo = payload.user ? await ctx.resolveUserName(payload.user) : {};
|
||||
const userLabel = userInfo?.name ?? payload.user ?? "someone";
|
||||
const itemType = payload.item?.type ?? "item";
|
||||
const messageId = payload.item?.message?.ts ?? payload.event_ts;
|
||||
const sessionKey = ctx.resolveSlackSystemEventSessionKey({
|
||||
channelId,
|
||||
channelType: channelInfo?.type ?? undefined,
|
||||
});
|
||||
enqueueSystemEvent(`Slack: ${userLabel} pinned a ${itemType} in ${label}.`, {
|
||||
sessionKey,
|
||||
contextKey: `slack:pin:added:${channelId ?? "unknown"}:${messageId ?? "unknown"}`,
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.runtime.error?.(danger(`slack pin added handler failed: ${String(err)}`));
|
||||
}
|
||||
});
|
||||
|
||||
ctx.app.event(
|
||||
"pin_removed",
|
||||
async ({ event }: SlackEventMiddlewareArgs<"pin_removed">) => {
|
||||
try {
|
||||
const payload = event as SlackPinEvent;
|
||||
const channelId = payload.channel_id;
|
||||
const channelInfo = channelId
|
||||
? await ctx.resolveChannelName(channelId)
|
||||
: {};
|
||||
if (
|
||||
!ctx.isChannelAllowed({
|
||||
channelId,
|
||||
channelName: channelInfo?.name,
|
||||
channelType: channelInfo?.type,
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const label = resolveSlackChannelLabel({
|
||||
ctx.app.event("pin_removed", async ({ event }: SlackEventMiddlewareArgs<"pin_removed">) => {
|
||||
try {
|
||||
const payload = event as SlackPinEvent;
|
||||
const channelId = payload.channel_id;
|
||||
const channelInfo = channelId ? await ctx.resolveChannelName(channelId) : {};
|
||||
if (
|
||||
!ctx.isChannelAllowed({
|
||||
channelId,
|
||||
channelName: channelInfo?.name,
|
||||
});
|
||||
const userInfo = payload.user
|
||||
? await ctx.resolveUserName(payload.user)
|
||||
: {};
|
||||
const userLabel = userInfo?.name ?? payload.user ?? "someone";
|
||||
const itemType = payload.item?.type ?? "item";
|
||||
const messageId = payload.item?.message?.ts ?? payload.event_ts;
|
||||
const sessionKey = ctx.resolveSlackSystemEventSessionKey({
|
||||
channelId,
|
||||
channelType: channelInfo?.type ?? undefined,
|
||||
});
|
||||
enqueueSystemEvent(
|
||||
`Slack: ${userLabel} unpinned a ${itemType} in ${label}.`,
|
||||
{
|
||||
sessionKey,
|
||||
contextKey: `slack:pin:removed:${channelId ?? "unknown"}:${messageId ?? "unknown"}`,
|
||||
},
|
||||
);
|
||||
} catch (err) {
|
||||
ctx.runtime.error?.(
|
||||
danger(`slack pin removed handler failed: ${String(err)}`),
|
||||
);
|
||||
channelType: channelInfo?.type,
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
},
|
||||
);
|
||||
const label = resolveSlackChannelLabel({
|
||||
channelId,
|
||||
channelName: channelInfo?.name,
|
||||
});
|
||||
const userInfo = payload.user ? await ctx.resolveUserName(payload.user) : {};
|
||||
const userLabel = userInfo?.name ?? payload.user ?? "someone";
|
||||
const itemType = payload.item?.type ?? "item";
|
||||
const messageId = payload.item?.message?.ts ?? payload.event_ts;
|
||||
const sessionKey = ctx.resolveSlackSystemEventSessionKey({
|
||||
channelId,
|
||||
channelType: channelInfo?.type ?? undefined,
|
||||
});
|
||||
enqueueSystemEvent(`Slack: ${userLabel} unpinned a ${itemType} in ${label}.`, {
|
||||
sessionKey,
|
||||
contextKey: `slack:pin:removed:${channelId ?? "unknown"}:${messageId ?? "unknown"}`,
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.runtime.error?.(danger(`slack pin removed handler failed: ${String(err)}`));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -11,15 +11,10 @@ import {
|
||||
import type { SlackMonitorContext } from "../context.js";
|
||||
import type { SlackReactionEvent } from "../types.js";
|
||||
|
||||
export function registerSlackReactionEvents(params: {
|
||||
ctx: SlackMonitorContext;
|
||||
}) {
|
||||
export function registerSlackReactionEvents(params: { ctx: SlackMonitorContext }) {
|
||||
const { ctx } = params;
|
||||
|
||||
const handleReactionEvent = async (
|
||||
event: SlackReactionEvent,
|
||||
action: "added" | "removed",
|
||||
) => {
|
||||
const handleReactionEvent = async (event: SlackReactionEvent, action: "added" | "removed") => {
|
||||
try {
|
||||
const item = event.item;
|
||||
if (!event.user) return;
|
||||
@@ -67,9 +62,7 @@ export function registerSlackReactionEvents(params: {
|
||||
const channelLabel = channelName
|
||||
? `#${normalizeSlackSlug(channelName) || channelName}`
|
||||
: `#${item.channel}`;
|
||||
const authorInfo = event.item_user
|
||||
? await ctx.resolveUserName(event.item_user)
|
||||
: undefined;
|
||||
const authorInfo = event.item_user ? await ctx.resolveUserName(event.item_user) : undefined;
|
||||
const authorLabel = authorInfo?.name ?? event.item_user;
|
||||
const baseText = `Slack reaction ${action}: :${emojiLabel}: by ${actorLabel} in ${channelLabel} msg ${item.ts}`;
|
||||
const text = authorLabel ? `${baseText} from ${authorLabel}` : baseText;
|
||||
@@ -82,18 +75,13 @@ export function registerSlackReactionEvents(params: {
|
||||
contextKey: `slack:reaction:${action}:${item.channel}:${item.ts}:${event.user}:${emojiLabel}`,
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.runtime.error?.(
|
||||
danger(`slack reaction handler failed: ${String(err)}`),
|
||||
);
|
||||
ctx.runtime.error?.(danger(`slack reaction handler failed: ${String(err)}`));
|
||||
}
|
||||
};
|
||||
|
||||
ctx.app.event(
|
||||
"reaction_added",
|
||||
async ({ event }: SlackEventMiddlewareArgs<"reaction_added">) => {
|
||||
await handleReactionEvent(event as SlackReactionEvent, "added");
|
||||
},
|
||||
);
|
||||
ctx.app.event("reaction_added", async ({ event }: SlackEventMiddlewareArgs<"reaction_added">) => {
|
||||
await handleReactionEvent(event as SlackReactionEvent, "added");
|
||||
});
|
||||
|
||||
ctx.app.event(
|
||||
"reaction_removed",
|
||||
|
||||
@@ -14,9 +14,7 @@ import { createSlackReplyDeliveryPlan, deliverReplies } from "../replies.js";
|
||||
|
||||
import type { PreparedSlackMessage } from "./types.js";
|
||||
|
||||
export async function dispatchPreparedSlackMessage(
|
||||
prepared: PreparedSlackMessage,
|
||||
) {
|
||||
export async function dispatchPreparedSlackMessage(prepared: PreparedSlackMessage) {
|
||||
const { ctx, account, message, route } = prepared;
|
||||
const cfg = ctx.cfg;
|
||||
const runtime = ctx.runtime;
|
||||
@@ -64,39 +62,35 @@ export async function dispatchPreparedSlackMessage(
|
||||
};
|
||||
|
||||
let didSendReply = false;
|
||||
const { dispatcher, replyOptions, markDispatchIdle } =
|
||||
createReplyDispatcherWithTyping({
|
||||
responsePrefix: resolveEffectiveMessagesConfig(cfg, route.agentId)
|
||||
.responsePrefix,
|
||||
humanDelay: resolveHumanDelayConfig(cfg, route.agentId),
|
||||
deliver: async (payload) => {
|
||||
const replyThreadTs = replyPlan.nextThreadTs();
|
||||
await deliverReplies({
|
||||
replies: [payload],
|
||||
target: prepared.replyTarget,
|
||||
token: ctx.botToken,
|
||||
accountId: account.accountId,
|
||||
runtime,
|
||||
textLimit: ctx.textLimit,
|
||||
replyThreadTs,
|
||||
const { dispatcher, replyOptions, markDispatchIdle } = createReplyDispatcherWithTyping({
|
||||
responsePrefix: resolveEffectiveMessagesConfig(cfg, route.agentId).responsePrefix,
|
||||
humanDelay: resolveHumanDelayConfig(cfg, route.agentId),
|
||||
deliver: async (payload) => {
|
||||
const replyThreadTs = replyPlan.nextThreadTs();
|
||||
await deliverReplies({
|
||||
replies: [payload],
|
||||
target: prepared.replyTarget,
|
||||
token: ctx.botToken,
|
||||
accountId: account.accountId,
|
||||
runtime,
|
||||
textLimit: ctx.textLimit,
|
||||
replyThreadTs,
|
||||
});
|
||||
didSendReply = true;
|
||||
replyPlan.markSent();
|
||||
},
|
||||
onError: (err, info) => {
|
||||
runtime.error?.(danger(`slack ${info.kind} reply failed: ${String(err)}`));
|
||||
if (didSetStatus) {
|
||||
void ctx.setSlackThreadStatus({
|
||||
channelId: message.channel,
|
||||
threadTs: statusThreadTs,
|
||||
status: "",
|
||||
});
|
||||
didSendReply = true;
|
||||
replyPlan.markSent();
|
||||
},
|
||||
onError: (err, info) => {
|
||||
runtime.error?.(
|
||||
danger(`slack ${info.kind} reply failed: ${String(err)}`),
|
||||
);
|
||||
if (didSetStatus) {
|
||||
void ctx.setSlackThreadStatus({
|
||||
channelId: message.channel,
|
||||
threadTs: statusThreadTs,
|
||||
status: "",
|
||||
});
|
||||
}
|
||||
},
|
||||
onReplyStart,
|
||||
});
|
||||
}
|
||||
},
|
||||
onReplyStart,
|
||||
});
|
||||
|
||||
const { queuedFinal, counts } = await dispatchReplyFromConfig({
|
||||
ctx: prepared.ctxPayload,
|
||||
@@ -139,11 +133,7 @@ export async function dispatchPreparedSlackMessage(
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
ctx.removeAckAfterReply &&
|
||||
prepared.ackReactionPromise &&
|
||||
prepared.ackReactionMessageTs
|
||||
) {
|
||||
if (ctx.removeAckAfterReply && prepared.ackReactionPromise && prepared.ackReactionMessageTs) {
|
||||
const messageTs = prepared.ackReactionMessageTs;
|
||||
const ackValue = prepared.ackReactionValue;
|
||||
void prepared.ackReactionPromise.then((didAck) => {
|
||||
|
||||
@@ -1,15 +1,9 @@
|
||||
import { resolveAckReaction } from "../../../agents/identity.js";
|
||||
import { hasControlCommand } from "../../../auto-reply/command-detection.js";
|
||||
import { shouldHandleTextCommands } from "../../../auto-reply/commands-registry.js";
|
||||
import {
|
||||
formatAgentEnvelope,
|
||||
formatThreadStarterEnvelope,
|
||||
} from "../../../auto-reply/envelope.js";
|
||||
import { formatAgentEnvelope, formatThreadStarterEnvelope } from "../../../auto-reply/envelope.js";
|
||||
import { buildHistoryContextFromMap } from "../../../auto-reply/reply/history.js";
|
||||
import {
|
||||
buildMentionRegexes,
|
||||
matchesMentionPatterns,
|
||||
} from "../../../auto-reply/reply/mentions.js";
|
||||
import { buildMentionRegexes, matchesMentionPatterns } from "../../../auto-reply/reply/mentions.js";
|
||||
import { logVerbose, shouldLogVerbose } from "../../../globals.js";
|
||||
import { enqueueSystemEvent } from "../../../infra/system-events.js";
|
||||
import { buildPairingReply } from "../../../pairing/pairing-messages.js";
|
||||
@@ -23,10 +17,7 @@ import { sendMessageSlack } from "../../send.js";
|
||||
import type { SlackMessageEvent } from "../../types.js";
|
||||
|
||||
import { allowListMatches, resolveSlackUserAllowed } from "../allow-list.js";
|
||||
import {
|
||||
isSlackSenderAllowListed,
|
||||
resolveSlackEffectiveAllowFrom,
|
||||
} from "../auth.js";
|
||||
import { isSlackSenderAllowListed, resolveSlackEffectiveAllowFrom } from "../auth.js";
|
||||
import { resolveSlackChannelConfig } from "../channel-config.js";
|
||||
import type { SlackMonitorContext } from "../context.js";
|
||||
import { resolveSlackMedia, resolveSlackThreadStarter } from "../media.js";
|
||||
@@ -57,8 +48,7 @@ export async function prepareSlackMessage(params: {
|
||||
const resolvedChannelType = channelType;
|
||||
const isDirectMessage = resolvedChannelType === "im";
|
||||
const isGroupDm = resolvedChannelType === "mpim";
|
||||
const isRoom =
|
||||
resolvedChannelType === "channel" || resolvedChannelType === "group";
|
||||
const isRoom = resolvedChannelType === "channel" || resolvedChannelType === "group";
|
||||
const isRoomish = isRoom || isGroupDm;
|
||||
|
||||
const channelConfig = isRoom
|
||||
@@ -77,12 +67,9 @@ export async function prepareSlackMessage(params: {
|
||||
|
||||
const isBotMessage = Boolean(message.bot_id);
|
||||
if (isBotMessage) {
|
||||
if (message.user && ctx.botUserId && message.user === ctx.botUserId)
|
||||
return null;
|
||||
if (message.user && ctx.botUserId && message.user === ctx.botUserId) return null;
|
||||
if (!allowBots) {
|
||||
logVerbose(
|
||||
`slack: drop bot message ${message.bot_id ?? "unknown"} (allowBots=false)`,
|
||||
);
|
||||
logVerbose(`slack: drop bot message ${message.bot_id ?? "unknown"} (allowBots=false)`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -154,9 +141,7 @@ export async function prepareSlackMessage(params: {
|
||||
},
|
||||
);
|
||||
} catch (err) {
|
||||
logVerbose(
|
||||
`slack pairing reply failed for ${message.user}: ${String(err)}`,
|
||||
);
|
||||
logVerbose(`slack pairing reply failed for ${message.user}: ${String(err)}`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -184,18 +169,12 @@ export async function prepareSlackMessage(params: {
|
||||
const wasMentioned =
|
||||
opts.wasMentioned ??
|
||||
(!isDirectMessage &&
|
||||
(Boolean(
|
||||
ctx.botUserId && message.text?.includes(`<@${ctx.botUserId}>`),
|
||||
) ||
|
||||
(Boolean(ctx.botUserId && message.text?.includes(`<@${ctx.botUserId}>`)) ||
|
||||
matchesMentionPatterns(message.text ?? "", mentionRegexes)));
|
||||
|
||||
const sender = message.user ? await ctx.resolveUserName(message.user) : null;
|
||||
const senderName =
|
||||
sender?.name ??
|
||||
message.username?.trim() ??
|
||||
message.user ??
|
||||
message.bot_id ??
|
||||
"unknown";
|
||||
sender?.name ?? message.username?.trim() ?? message.user ?? message.bot_id ?? "unknown";
|
||||
|
||||
const channelUserAuthorized = isRoom
|
||||
? resolveSlackUserAllowed({
|
||||
@@ -205,9 +184,7 @@ export async function prepareSlackMessage(params: {
|
||||
})
|
||||
: true;
|
||||
if (isRoom && !channelUserAuthorized) {
|
||||
logVerbose(
|
||||
`Blocked unauthorized slack sender ${senderId} (not in channel users)`,
|
||||
);
|
||||
logVerbose(`Blocked unauthorized slack sender ${senderId} (not in channel users)`);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -223,9 +200,7 @@ export async function prepareSlackMessage(params: {
|
||||
cfg,
|
||||
surface: "slack",
|
||||
});
|
||||
const shouldRequireMention = isRoom
|
||||
? (channelConfig?.requireMention ?? true)
|
||||
: false;
|
||||
const shouldRequireMention = isRoom ? (channelConfig?.requireMention ?? true) : false;
|
||||
|
||||
// Allow "control commands" to bypass mention gating if sender is authorized.
|
||||
const shouldBypassMention =
|
||||
@@ -239,17 +214,8 @@ export async function prepareSlackMessage(params: {
|
||||
|
||||
const effectiveWasMentioned = wasMentioned || shouldBypassMention;
|
||||
const canDetectMention = Boolean(ctx.botUserId) || mentionRegexes.length > 0;
|
||||
if (
|
||||
isRoom &&
|
||||
shouldRequireMention &&
|
||||
canDetectMention &&
|
||||
!wasMentioned &&
|
||||
!shouldBypassMention
|
||||
) {
|
||||
ctx.logger.info(
|
||||
{ channel: message.channel, reason: "no-mention" },
|
||||
"skipping room message",
|
||||
);
|
||||
if (isRoom && shouldRequireMention && canDetectMention && !wasMentioned && !shouldBypassMention) {
|
||||
ctx.logger.info({ channel: message.channel, reason: "no-mention" }, "skipping room message");
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -281,20 +247,13 @@ export async function prepareSlackMessage(params: {
|
||||
const ackReactionMessageTs = message.ts;
|
||||
const ackReactionPromise =
|
||||
shouldAckReaction() && ackReactionMessageTs && ackReactionValue
|
||||
? reactSlackMessage(
|
||||
message.channel,
|
||||
ackReactionMessageTs,
|
||||
ackReactionValue,
|
||||
{
|
||||
token: ctx.botToken,
|
||||
client: ctx.app.client,
|
||||
},
|
||||
).then(
|
||||
? reactSlackMessage(message.channel, ackReactionMessageTs, ackReactionValue, {
|
||||
token: ctx.botToken,
|
||||
client: ctx.app.client,
|
||||
}).then(
|
||||
() => true,
|
||||
(err) => {
|
||||
logVerbose(
|
||||
`slack react failed for channel ${message.channel}: ${String(err)}`,
|
||||
);
|
||||
logVerbose(`slack react failed for channel ${message.channel}: ${String(err)}`);
|
||||
return false;
|
||||
},
|
||||
)
|
||||
@@ -307,9 +266,7 @@ export async function prepareSlackMessage(params: {
|
||||
? {
|
||||
sender: senderName,
|
||||
body: rawBody,
|
||||
timestamp: message.ts
|
||||
? Math.round(Number(message.ts) * 1000)
|
||||
: undefined,
|
||||
timestamp: message.ts ? Math.round(Number(message.ts) * 1000) : undefined,
|
||||
messageId: message.ts,
|
||||
}
|
||||
: undefined;
|
||||
@@ -327,8 +284,7 @@ export async function prepareSlackMessage(params: {
|
||||
const baseSessionKey = route.sessionKey;
|
||||
const threadTs = message.thread_ts;
|
||||
const hasThreadTs = typeof threadTs === "string" && threadTs.length > 0;
|
||||
const isThreadReply =
|
||||
hasThreadTs && (threadTs !== message.ts || Boolean(message.parent_user_id));
|
||||
const isThreadReply = hasThreadTs && (threadTs !== message.ts || Boolean(message.parent_user_id));
|
||||
const threadKeys = resolveThreadSessionKeys({
|
||||
baseSessionKey,
|
||||
threadId: isThreadReply ? threadTs : undefined,
|
||||
@@ -362,17 +318,13 @@ export async function prepareSlackMessage(params: {
|
||||
from: roomLabel,
|
||||
timestamp: entry.timestamp,
|
||||
body: `${entry.sender}: ${entry.body}${
|
||||
entry.messageId
|
||||
? ` [id:${entry.messageId} channel:${message.channel}]`
|
||||
: ""
|
||||
entry.messageId ? ` [id:${entry.messageId} channel:${message.channel}]` : ""
|
||||
}`,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
const slackTo = isDirectMessage
|
||||
? `user:${message.user}`
|
||||
: `channel:${message.channel}`;
|
||||
const slackTo = isDirectMessage ? `user:${message.user}` : `channel:${message.channel}`;
|
||||
|
||||
const channelDescription = [channelInfo?.topic, channelInfo?.purpose]
|
||||
.map((entry) => entry?.trim())
|
||||
@@ -395,17 +347,13 @@ export async function prepareSlackMessage(params: {
|
||||
client: ctx.app.client,
|
||||
});
|
||||
if (starter?.text) {
|
||||
const starterUser = starter.userId
|
||||
? await ctx.resolveUserName(starter.userId)
|
||||
: null;
|
||||
const starterUser = starter.userId ? await ctx.resolveUserName(starter.userId) : null;
|
||||
const starterName = starterUser?.name ?? starter.userId ?? "Unknown";
|
||||
const starterWithId = `${starter.text}\n[slack message id: ${starter.ts ?? threadTs} channel: ${message.channel}]`;
|
||||
threadStarterBody = formatThreadStarterEnvelope({
|
||||
channel: "Slack",
|
||||
author: starterName,
|
||||
timestamp: starter.ts
|
||||
? Math.round(Number(starter.ts) * 1000)
|
||||
: undefined,
|
||||
timestamp: starter.ts ? Math.round(Number(starter.ts) * 1000) : undefined,
|
||||
body: starterWithId,
|
||||
});
|
||||
const snippet = starter.text.replace(/\s+/g, " ").slice(0, 80);
|
||||
@@ -449,9 +397,7 @@ export async function prepareSlackMessage(params: {
|
||||
if (!replyTarget) return null;
|
||||
|
||||
if (shouldLogVerbose()) {
|
||||
logVerbose(
|
||||
`slack inbound: channel=${message.channel} from=${slackFrom} preview="${preview}"`,
|
||||
);
|
||||
logVerbose(`slack inbound: channel=${message.channel} from=${slackFrom} preview="${preview}"`);
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -67,13 +67,10 @@ export async function monitorSlackProvider(opts: MonitorSlackOpts = {}) {
|
||||
const reactionMode = slackCfg.reactionNotifications ?? "own";
|
||||
const reactionAllowlist = slackCfg.reactionAllowlist ?? [];
|
||||
const replyToMode = slackCfg.replyToMode ?? "off";
|
||||
const slashCommand = resolveSlackSlashCommandConfig(
|
||||
opts.slashCommand ?? slackCfg.slashCommand,
|
||||
);
|
||||
const slashCommand = resolveSlackSlashCommandConfig(opts.slashCommand ?? slackCfg.slashCommand);
|
||||
const textLimit = resolveTextChunkLimit(cfg, "slack", account.accountId);
|
||||
const ackReactionScope = cfg.messages?.ackReactionScope ?? "group-mentions";
|
||||
const mediaMaxBytes =
|
||||
(opts.mediaMaxMb ?? slackCfg.mediaMaxMb ?? 20) * 1024 * 1024;
|
||||
const mediaMaxBytes = (opts.mediaMaxMb ?? slackCfg.mediaMaxMb ?? 20) * 1024 * 1024;
|
||||
const removeAckAfterReply = cfg.messages?.removeAckAfterReply ?? false;
|
||||
|
||||
const app = new App({
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { chunkMarkdownText } from "../../auto-reply/chunk.js";
|
||||
import { createReplyReferencePlanner } from "../../auto-reply/reply/reply-reference.js";
|
||||
import {
|
||||
isSilentReplyText,
|
||||
SILENT_REPLY_TOKEN,
|
||||
} from "../../auto-reply/tokens.js";
|
||||
import { isSilentReplyText, SILENT_REPLY_TOKEN } from "../../auto-reply/tokens.js";
|
||||
import type { ReplyPayload } from "../../auto-reply/types.js";
|
||||
import type { RuntimeEnv } from "../../runtime.js";
|
||||
import { sendMessageSlack } from "../send.js";
|
||||
@@ -20,16 +17,14 @@ export async function deliverReplies(params: {
|
||||
const chunkLimit = Math.min(params.textLimit, 4000);
|
||||
for (const payload of params.replies) {
|
||||
const threadTs = payload.replyToId ?? params.replyThreadTs;
|
||||
const mediaList =
|
||||
payload.mediaUrls ?? (payload.mediaUrl ? [payload.mediaUrl] : []);
|
||||
const mediaList = payload.mediaUrls ?? (payload.mediaUrl ? [payload.mediaUrl] : []);
|
||||
const text = payload.text ?? "";
|
||||
if (!text && mediaList.length === 0) continue;
|
||||
|
||||
if (mediaList.length === 0) {
|
||||
for (const chunk of chunkMarkdownText(text, chunkLimit)) {
|
||||
const trimmed = chunk.trim();
|
||||
if (!trimmed || isSilentReplyText(trimmed, SILENT_REPLY_TOKEN))
|
||||
continue;
|
||||
if (!trimmed || isSilentReplyText(trimmed, SILENT_REPLY_TOKEN)) continue;
|
||||
await sendMessageSlack(params.target, trimmed, {
|
||||
token: params.token,
|
||||
threadTs,
|
||||
@@ -129,16 +124,9 @@ export async function deliverSlackSlashReplies(params: {
|
||||
const chunkLimit = Math.min(params.textLimit, 4000);
|
||||
for (const payload of params.replies) {
|
||||
const textRaw = payload.text?.trim() ?? "";
|
||||
const text =
|
||||
textRaw && !isSilentReplyText(textRaw, SILENT_REPLY_TOKEN)
|
||||
? textRaw
|
||||
: undefined;
|
||||
const mediaList =
|
||||
payload.mediaUrls ?? (payload.mediaUrl ? [payload.mediaUrl] : []);
|
||||
const combined = [
|
||||
text ?? "",
|
||||
...mediaList.map((url) => url.trim()).filter(Boolean),
|
||||
]
|
||||
const text = textRaw && !isSilentReplyText(textRaw, SILENT_REPLY_TOKEN) ? textRaw : undefined;
|
||||
const mediaList = payload.mediaUrls ?? (payload.mediaUrl ? [payload.mediaUrl] : []);
|
||||
const combined = [text ?? "", ...mediaList.map((url) => url.trim()).filter(Boolean)]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
if (!combined) continue;
|
||||
|
||||
@@ -22,14 +22,8 @@ import {
|
||||
normalizeAllowListLower,
|
||||
resolveSlackUserAllowed,
|
||||
} from "./allow-list.js";
|
||||
import {
|
||||
resolveSlackChannelConfig,
|
||||
type SlackChannelConfigResolved,
|
||||
} from "./channel-config.js";
|
||||
import {
|
||||
buildSlackSlashCommandMatcher,
|
||||
resolveSlackSlashCommandConfig,
|
||||
} from "./commands.js";
|
||||
import { resolveSlackChannelConfig, type SlackChannelConfigResolved } from "./channel-config.js";
|
||||
import { buildSlackSlashCommandMatcher, resolveSlackSlashCommandConfig } from "./commands.js";
|
||||
import type { SlackMonitorContext } from "./context.js";
|
||||
import { isSlackRoomAllowedByPolicy } from "./policy.js";
|
||||
import { deliverSlackSlashReplies } from "./replies.js";
|
||||
@@ -67,8 +61,7 @@ export function registerSlackMonitorSlashCommands(params: {
|
||||
|
||||
const channelInfo = await ctx.resolveChannelName(command.channel_id);
|
||||
const channelType =
|
||||
channelInfo?.type ??
|
||||
(command.channel_name === "directmessage" ? "im" : undefined);
|
||||
channelInfo?.type ?? (command.channel_name === "directmessage" ? "im" : undefined);
|
||||
const isDirectMessage = channelType === "im";
|
||||
const isGroupDm = channelType === "mpim";
|
||||
const isRoom = channelType === "channel" || channelType === "group";
|
||||
@@ -87,15 +80,9 @@ export function registerSlackMonitorSlashCommands(params: {
|
||||
return;
|
||||
}
|
||||
|
||||
const storeAllowFrom = await readChannelAllowFromStore("slack").catch(
|
||||
() => [],
|
||||
);
|
||||
const effectiveAllowFrom = normalizeAllowList([
|
||||
...ctx.allowFrom,
|
||||
...storeAllowFrom,
|
||||
]);
|
||||
const effectiveAllowFromLower =
|
||||
normalizeAllowListLower(effectiveAllowFrom);
|
||||
const storeAllowFrom = await readChannelAllowFromStore("slack").catch(() => []);
|
||||
const effectiveAllowFrom = normalizeAllowList([...ctx.allowFrom, ...storeAllowFrom]);
|
||||
const effectiveAllowFromLower = normalizeAllowListLower(effectiveAllowFrom);
|
||||
|
||||
let commandAuthorized = true;
|
||||
let channelConfig: SlackChannelConfigResolved | null = null;
|
||||
@@ -152,8 +139,7 @@ export function registerSlackMonitorSlashCommands(params: {
|
||||
});
|
||||
if (ctx.useAccessGroups) {
|
||||
const channelAllowlistConfigured =
|
||||
Boolean(ctx.channelsConfig) &&
|
||||
Object.keys(ctx.channelsConfig ?? {}).length > 0;
|
||||
Boolean(ctx.channelsConfig) && Object.keys(ctx.channelsConfig ?? {}).length > 0;
|
||||
const channelAllowed = channelConfig?.allowed !== false;
|
||||
if (
|
||||
!isSlackRoomAllowedByPolicy({
|
||||
@@ -197,9 +183,7 @@ export function registerSlackMonitorSlashCommands(params: {
|
||||
}
|
||||
|
||||
const channelName = channelInfo?.name;
|
||||
const roomLabel = channelName
|
||||
? `#${channelName}`
|
||||
: `#${command.channel_id}`;
|
||||
const roomLabel = channelName ? `#${channelName}` : `#${command.channel_id}`;
|
||||
const isRoomish = isRoom || isGroupDm;
|
||||
const route = resolveAgentRoute({
|
||||
cfg,
|
||||
@@ -218,15 +202,11 @@ export function registerSlackMonitorSlashCommands(params: {
|
||||
.filter((entry, index, list) => list.indexOf(entry) === index)
|
||||
.join("\n");
|
||||
const systemPromptParts = [
|
||||
channelDescription
|
||||
? `Channel description: ${channelDescription}`
|
||||
: null,
|
||||
channelDescription ? `Channel description: ${channelDescription}` : null,
|
||||
channelConfig?.systemPrompt?.trim() || null,
|
||||
].filter((entry): entry is string => Boolean(entry));
|
||||
const groupSystemPrompt =
|
||||
systemPromptParts.length > 0
|
||||
? systemPromptParts.join("\n\n")
|
||||
: undefined;
|
||||
systemPromptParts.length > 0 ? systemPromptParts.join("\n\n") : undefined;
|
||||
|
||||
const ctxPayload = {
|
||||
Body: prompt,
|
||||
@@ -259,8 +239,7 @@ export function registerSlackMonitorSlashCommands(params: {
|
||||
ctx: ctxPayload,
|
||||
cfg,
|
||||
dispatcherOptions: {
|
||||
responsePrefix: resolveEffectiveMessagesConfig(cfg, route.agentId)
|
||||
.responsePrefix,
|
||||
responsePrefix: resolveEffectiveMessagesConfig(cfg, route.agentId).responsePrefix,
|
||||
deliver: async (payload) => {
|
||||
await deliverSlackSlashReplies({
|
||||
replies: [payload],
|
||||
@@ -270,9 +249,7 @@ export function registerSlackMonitorSlashCommands(params: {
|
||||
});
|
||||
},
|
||||
onError: (err, info) => {
|
||||
runtime.error?.(
|
||||
danger(`slack slash ${info.kind} reply failed: ${String(err)}`),
|
||||
);
|
||||
runtime.error?.(danger(`slack slash ${info.kind} reply failed: ${String(err)}`));
|
||||
},
|
||||
},
|
||||
replyOptions: { skillFilter: channelConfig?.skills },
|
||||
@@ -299,9 +276,7 @@ export function registerSlackMonitorSlashCommands(params: {
|
||||
providerSetting: account.config.commands?.native,
|
||||
globalSetting: cfg.commands?.native,
|
||||
});
|
||||
const nativeCommands = nativeEnabled
|
||||
? listNativeCommandSpecsForConfig(cfg)
|
||||
: [];
|
||||
const nativeCommands = nativeEnabled ? listNativeCommandSpecsForConfig(cfg) : [];
|
||||
if (nativeCommands.length > 0) {
|
||||
for (const command of nativeCommands) {
|
||||
ctx.app.command(
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
import type {
|
||||
ClawdbotConfig,
|
||||
SlackSlashCommandConfig,
|
||||
} from "../../config/config.js";
|
||||
import type { ClawdbotConfig, SlackSlashCommandConfig } from "../../config/config.js";
|
||||
import type { RuntimeEnv } from "../../runtime.js";
|
||||
import type { SlackFile, SlackMessageEvent } from "../types.js";
|
||||
|
||||
|
||||
@@ -20,10 +20,7 @@ function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
|
||||
});
|
||||
}
|
||||
|
||||
export async function probeSlack(
|
||||
token: string,
|
||||
timeoutMs = 2500,
|
||||
): Promise<SlackProbe> {
|
||||
export async function probeSlack(token: string, timeoutMs = 2500): Promise<SlackProbe> {
|
||||
const client = new WebClient(token);
|
||||
const start = Date.now();
|
||||
try {
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { type FilesUploadV2Arguments, WebClient } from "@slack/web-api";
|
||||
|
||||
import {
|
||||
chunkMarkdownText,
|
||||
resolveTextChunkLimit,
|
||||
} from "../auto-reply/chunk.js";
|
||||
import { chunkMarkdownText, resolveTextChunkLimit } from "../auto-reply/chunk.js";
|
||||
import { loadConfig } from "../config/config.js";
|
||||
import { logVerbose } from "../globals.js";
|
||||
import { loadWebMedia } from "../web/media.js";
|
||||
@@ -117,10 +114,7 @@ async function uploadSlackFile(params: {
|
||||
threadTs?: string;
|
||||
maxBytes?: number;
|
||||
}): Promise<string> {
|
||||
const { buffer, contentType, fileName } = await loadWebMedia(
|
||||
params.mediaUrl,
|
||||
params.maxBytes,
|
||||
);
|
||||
const { buffer, contentType, fileName } = await loadWebMedia(params.mediaUrl, params.maxBytes);
|
||||
const basePayload = {
|
||||
channel_id: params.channelId,
|
||||
file: buffer,
|
||||
|
||||
@@ -8,8 +8,7 @@ export function resolveSlackThreadTargets(params: {
|
||||
const incomingThreadTs = params.message.thread_ts;
|
||||
const eventTs = params.message.event_ts;
|
||||
const messageTs = params.message.ts ?? eventTs;
|
||||
const replyThreadTs =
|
||||
incomingThreadTs ?? (params.replyToMode === "all" ? messageTs : undefined);
|
||||
const replyThreadTs = incomingThreadTs ?? (params.replyToMode === "all" ? messageTs : undefined);
|
||||
const statusThreadTs = replyThreadTs ?? messageTs;
|
||||
return { replyThreadTs, statusThreadTs };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user