@meetopenbot/slack 1.3.1 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -15,7 +15,7 @@ Slack specialist agent for OpenBot: Events API ingress, simple LLM replies, and
15
15
  A workspace owner clicks **Connect** on the Slack agent and approves "Add to Slack". That installs OpenBot's Slack app in their Slack workspace. OpenBot keeps the bot token, and the agent gets it on every run. Nothing to paste. The plugin asks for these bot scopes:
16
16
 
17
17
  - `app_mentions:read`, `im:history`: mentions and DMs
18
- - `channels:read`, `channels:history`, `users:read`, `users.profile:read`: reading channels, threads and people
18
+ - `channels:read`, `channels:history`, `groups:history`, `users:read`, `users.profile:read`: reading channels, threads (public and private) and people
19
19
  - `chat:write`, `reactions:write`: replying and reacting
20
20
 
21
21
  On **OpenBot Cloud** this works as is. A **self-hosted** runtime brings its own Slack app:
@@ -30,29 +30,56 @@ plugins:
30
30
  - id: "@meetopenbot/slack"
31
31
  config:
32
32
  model: anthropic/claude-haiku-5-5
33
- channelMappings: "C01234567:engineering,C89ABCDEF:support"
34
33
  ```
35
34
 
36
35
  On cloud, the model runs on your workspace credits by default. For BYOK, add `ANTHROPIC_API_KEY` (or `OPENAI_API_KEY` for OpenAI models) under workspace settings.
37
36
 
38
37
  ### Channel routing (webhook ingress)
39
38
 
40
- When a Slack message arrives via the Events API webhook, the runtime answers Slack at once and opens an OpenBot thread for the Slack thread. The Slack agent hands the message to the OpenBot **system** agent there and posts each reply back into the Slack thread. Set `channelMappings` as comma-separated `slackChannelId:openbotChannelId` pairs to pick the OpenBot channel:
39
+ When a Slack message arrives via the Events API webhook, the runtime answers Slack at once and opens an OpenBot thread for the Slack thread. The Slack agent hands the message to the OpenBot **system** agent in a Space and posts each reply back into the Slack thread. Each Space has its own working directory, repo and variables, so the Space decides which project the work runs in.
40
+
41
+ **Pick the Space from Slack.** Mention the bot in the channel:
42
+
43
+ ```
44
+ @Behalf use #backend here
45
+ ```
46
+
47
+ The bot saves the binding and confirms in the thread. From then on, mentions in that channel go to `backend`. A few things to know:
48
+
49
+ - The Space must already exist. If it doesn't, the bot says so and lists the Spaces you can use. It never creates a Space from Slack.
50
+ - The name matches a Space's id or display name, ignoring case. `use #backend`, `use space backend here` and `use backend here` all work. A bare word (no `#`, no "space") only counts when a Space by that name exists, so "use pnpm here" still goes to the agent as a normal request.
51
+ - Only full members of the connected Slack workspace can change a channel's Space. Guests and people from other organizations in a shared channel can't.
52
+ - To move a channel back, say `use #general here`.
53
+ - It works the same in a DM with the bot.
54
+
55
+ Bindings are saved in the Slack agent's plugin config in its `AGENT.md`, as `channelBindings` (Slack channel id → Space id). You can edit or remove them there.
56
+
57
+ **Which Space a message goes to:**
58
+
59
+ 1. The channel's saved binding, if its Space still exists.
60
+ 2. The channel's entry in `channelMappings`, if any.
61
+ 3. **`general`**.
62
+
63
+ The first time a channel with neither a binding nor a mapping reaches `general`, the bot adds a one-line hint after its reply saying how to pick a Space. It shows the hint once per Slack channel and remembers that in `routingHintsShown`.
64
+
65
+ **Fixed mappings (optional).** `channelMappings` still works for setups that pin channels in config. It's a comma-separated list of `slackChannelId:spaceId` pairs:
41
66
 
42
67
  ```
43
68
  C01234567:engineering,C89ABCDEF:support,D0789ABC:slack-dms
44
69
  ```
45
70
 
46
- - **Left side** — Slack channel id (`C…` for channels, `D…` for DMs). In Slack: right-click the channel → **View channel details** → copy the id at the bottom.
47
- - **Right side** — OpenBot channel id to run in (must already exist).
71
+ - **Left side**: Slack channel id (`C…` for channels, `D…` for DMs). In Slack: right-click the channel → **View channel details** → copy the id at the bottom.
72
+ - **Right side**: the Space to run in (must already exist).
48
73
 
49
- Slack channels without a mapping route to **`general`**.
74
+ A binding saved from Slack wins over `channelMappings`.
50
75
 
51
76
  This applies only to **webhook ingress delegation**, not Slack MCP tools.
52
77
 
53
78
  ### Events (inbound mentions)
54
79
 
55
- On **OpenBot Cloud**, mentions and DMs arrive on their own once the workspace connects Slack. OpenBot's Slack app sends every event to OpenBot Cloud. The cloud checks Slack's signature and forwards the event to the workspace that connected that Slack team, marked `verified`. Disconnecting stops the events. So does removing the app from Slack.
80
+ The bot answers when it is tagged and in DMs. Once tagged in a thread, it also answers later replies in that thread without a tag. It stays quiet on replies that tag someone else, and never joins threads it wasn't tagged in.
81
+
82
+ On **OpenBot Cloud**, mentions, DMs and thread replies arrive on their own once the workspace connects Slack. OpenBot's Slack app sends every event to OpenBot Cloud. The cloud checks Slack's signature and forwards the event to the workspace that connected that Slack team, marked `verified`. Disconnecting stops the events. So does removing the app from Slack.
56
83
 
57
84
  A **self-hosted** app sends its events straight to the runtime:
58
85
 
@@ -64,9 +91,7 @@ A **self-hosted** app sends its events straight to the runtime:
64
91
  https://<your-host>/api/webhooks/slack
65
92
  ```
66
93
 
67
- 3. Subscribe to **`app_mention`** for channel mentions. Add **`message.im`** only if you want DMs.
68
-
69
- Do **not** subscribe to `message.channels` or `message.groups` — that causes duplicate replies alongside `app_mention`.
94
+ 3. Subscribe the bot to **`app_mention`** for mentions, **`message.im`** for DMs, and **`message.channels`** / **`message.groups`** for untagged replies in threads the bot is in (public / private channels). The plugin handles a tagged reply once, even though Slack sends it as both `app_mention` and `message`.
70
95
 
71
96
  ## Build
72
97
 
@@ -0,0 +1,53 @@
1
+ import { findSlackPluginRefIndex, parseChannelMappings, readChannelBindings, resolveSpaceRoute, } from "./routing.js";
2
+ /**
3
+ * Bindings live in the Slack agent's own plugin config in AGENT.md (`channelBindings`,
4
+ * `routingHintsShown`): they belong to this agent, survive restarts, show in its config
5
+ * editor, and the next run reads them as `context.config`. Writes are queued and re-read
6
+ * AGENT.md, so two Slack messages at once don't drop each other's change. Resolves true
7
+ * when the config changed.
8
+ */
9
+ let pendingWrite = Promise.resolve();
10
+ export function updateSlackPluginConfig(args) {
11
+ const write = pendingWrite.then(async () => {
12
+ const details = await args.storage.getAgentDetails({ agentId: args.agentId });
13
+ const refs = details.pluginRefs ?? [];
14
+ const index = findSlackPluginRefIndex(refs);
15
+ if (index < 0) {
16
+ throw new Error(`The Slack plugin isn't on agent "${args.agentId}".`);
17
+ }
18
+ const current = { ...(refs[index].config ?? {}) };
19
+ const next = args.update(current);
20
+ if (next === current)
21
+ return false;
22
+ await args.storage.updateAgent({
23
+ agentId: args.agentId,
24
+ plugins: refs.map((ref, i) => (i === index ? { ...ref, config: next } : ref)),
25
+ });
26
+ return true;
27
+ });
28
+ pendingWrite = write.catch(() => undefined);
29
+ return write;
30
+ }
31
+ /**
32
+ * The Space for a Slack channel. A saved binding counts only while its Space exists;
33
+ * when the Spaces can't be listed, the binding is trusted.
34
+ */
35
+ export async function resolveSlackSpace(args) {
36
+ const bindings = readChannelBindings(args.config.channelBindings);
37
+ let spaceExists;
38
+ if (bindings[args.slackChannelId.trim()] && args.storage) {
39
+ try {
40
+ const ids = new Set((await args.storage.getChannels()).map((space) => space.id));
41
+ spaceExists = (spaceId) => ids.has(spaceId);
42
+ }
43
+ catch {
44
+ spaceExists = undefined;
45
+ }
46
+ }
47
+ return resolveSpaceRoute({
48
+ slackChannelId: args.slackChannelId,
49
+ bindings,
50
+ mappings: parseChannelMappings(args.config.channelMappings),
51
+ spaceExists,
52
+ });
53
+ }
package/dist/config.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { lookupSecret, modelConfigField, trimmedString, } from "@meetopenbot/plugin-sdk";
2
- export const DEFAULT_OPENBOT_CHANNEL_ID = "general";
2
+ import { readChannelBindings, readHintedChannels, } from "./routing.js";
3
+ export { DEFAULT_SPACE_ID as DEFAULT_OPENBOT_CHANNEL_ID } from "./routing.js";
3
4
  export const ROUTING_AGENT_ID = "system";
4
5
  export const SLACK_USER_DISPLAY_NAME = "Slack user";
5
6
  export const DEFAULT_SLACK_MODEL = "anthropic/claude-haiku-5-5";
@@ -17,49 +18,32 @@ export const pluginConfigSchema = {
17
18
  },
18
19
  channelMappings: {
19
20
  type: "string",
20
- description: "Inbound — webhook routing. Comma-separated slackChannelId:openbotChannelId pairs (e.g. C01234567:engineering,C89ABCDEF:support). Unmapped Slack channels use general.",
21
+ description: "Inbound — fixed routing, optional. Comma-separated slackChannelId:spaceId pairs (e.g. C01234567:engineering,C89ABCDEF:support). Easier: mention the bot in a Slack channel with \"use #space here\". A binding saved that way wins over this list; channels with neither use general.",
21
22
  },
22
23
  },
23
24
  };
24
- export function buildSlackChannelMappingIndex(config) {
25
- const index = new Map();
26
- const raw = trimmedString(config.channelMappings) ?? "";
27
- if (!raw)
28
- return index;
29
- for (const segment of raw.split(",")) {
30
- const trimmed = segment.trim();
31
- const colon = trimmed.indexOf(":");
32
- if (colon <= 0 || colon === trimmed.length - 1)
33
- continue;
34
- const slackChannelId = trimmed.slice(0, colon).trim();
35
- const channelId = trimmed.slice(colon + 1).trim();
36
- if (slackChannelId && channelId)
37
- index.set(slackChannelId, channelId);
38
- }
39
- return index;
40
- }
41
- export function resolveOpenBotChannelId(slackChannelId, config) {
42
- const normalized = slackChannelId.trim();
43
- if (!normalized)
44
- return DEFAULT_OPENBOT_CHANNEL_ID;
45
- return (buildSlackChannelMappingIndex(config).get(normalized) ??
46
- DEFAULT_OPENBOT_CHANNEL_ID);
47
- }
48
25
  export function readSlackConfig(config) {
49
26
  return {
50
27
  channelMappings: trimmedString(config.channelMappings),
28
+ channelBindings: readChannelBindings(config.channelBindings),
29
+ routingHintsShown: readHintedChannels(config.routingHintsShown),
51
30
  model: trimmedString(config.model),
52
31
  };
53
32
  }
54
33
  export function resolveSlackSigningSecret() {
55
34
  return lookupSecret({ envKeys: ["SLACK_SIGNING_SECRET"] });
56
35
  }
57
- /** Bot scopes asked for at sign-in: the MCP tools plus mention and DM ingress. */
36
+ /**
37
+ * Bot scopes asked for at sign-in: the MCP tools plus mention, DM and thread-reply ingress.
38
+ * `channels:history` and `groups:history` let the bot read replies in public and private
39
+ * channel threads it is in.
40
+ */
58
41
  export const SLACK_BOT_SCOPES = [
59
42
  "app_mentions:read",
60
43
  "channels:history",
61
44
  "channels:read",
62
45
  "chat:write",
46
+ "groups:history",
63
47
  "im:history",
64
48
  "reactions:write",
65
49
  "users:read",
package/dist/index.js CHANGED
@@ -24,6 +24,14 @@ export const plugin = definePlugin({
24
24
  ctx: { state },
25
25
  config: slackConfig,
26
26
  agentId: context.agentId,
27
+ hasThread: async (channelId, threadId) => {
28
+ const details = await context.storage
29
+ .getThreadDetails({ channelId, threadId })
30
+ .catch(() => null);
31
+ const state = details?.state;
32
+ return !!state && typeof state === "object" && Object.keys(state).length > 0;
33
+ },
34
+ storage: context.storage,
27
35
  });
28
36
  },
29
37
  async *run({ event, handlerCtx, context }) {
@@ -35,6 +43,7 @@ export const plugin = definePlugin({
35
43
  config: slackConfig,
36
44
  credentials: slackCredentials(context),
37
45
  host: context.host,
46
+ storage: context.storage,
38
47
  publicBaseUrl: context.publicBaseUrl,
39
48
  });
40
49
  },
package/dist/invoke.js CHANGED
@@ -1,9 +1,11 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { agentModelKeyEnv, agentModelProvider, agentOutput, creditsErrorMessage, hasLlmAuth, llmAuthNotConfiguredMessage, shouldHandleInvoke, toAgentTurnEvents, } from "@meetopenbot/plugin-sdk";
3
3
  import { runSlackAgent } from "./agent.js";
4
- import { resolveOpenBotChannelId, resolveSlackModel, ROUTING_AGENT_ID, SLACK_USER_DISPLAY_NAME, } from "./config.js";
4
+ import { resolveSlackSpace, updateSlackPluginConfig } from "./bindings.js";
5
+ import { resolveSlackModel, ROUTING_AGENT_ID, SLACK_USER_DISPLAY_NAME, } from "./config.js";
5
6
  import { buildPromptWithSlackContext } from "./context.js";
6
- import { postSlackMessage } from "./post.js";
7
+ import { fetchSlackUserFlags, postSlackMessage } from "./post.js";
8
+ import { ambiguousSpaceMessage, boundMessage, canRouteSlackChannel, findSpace, missingSpaceMessage, parseUseSpaceCommand, ROUTING_FORBIDDEN, ROUTING_HINT, ROUTING_UNNAMED_CHANNEL, withChannelBinding, withHintedChannel, } from "./routing.js";
7
9
  import { getSlackThreadMeta, isSlackWebhookIngress } from "./webhook.js";
8
10
  /**
9
11
  * The host connects Slack before `run`. A run without credentials means the host is too
@@ -90,6 +92,41 @@ async function* bridgeSystemAgentRun(args) {
90
92
  }
91
93
  await runPromise;
92
94
  }
95
+ /**
96
+ * The bot's answer to "use #space here", or undefined when the message isn't that command
97
+ * after all (a bare word that names no Space, like "use pnpm here"). Never creates a Space.
98
+ */
99
+ async function answerUseSpaceCommand(args) {
100
+ if (!args.command.ref)
101
+ return ROUTING_UNNAMED_CHANNEL;
102
+ const spaces = (await args.storage.getChannels()).map(({ id, name }) => ({ id, name }));
103
+ const found = findSpace(args.command.ref, spaces);
104
+ if (!args.command.explicit && found.kind !== "found")
105
+ return undefined;
106
+ if (!args.slackUserId)
107
+ return ROUTING_FORBIDDEN;
108
+ try {
109
+ const user = await fetchSlackUserFlags({
110
+ token: args.credentials.botToken,
111
+ userId: args.slackUserId,
112
+ });
113
+ if (!canRouteSlackChannel(user, args.credentials.teamId))
114
+ return ROUTING_FORBIDDEN;
115
+ }
116
+ catch {
117
+ return ROUTING_FORBIDDEN;
118
+ }
119
+ if (found.kind === "missing")
120
+ return missingSpaceMessage(args.command.ref, spaces);
121
+ if (found.kind === "ambiguous")
122
+ return ambiguousSpaceMessage(args.command.ref, found.spaces);
123
+ await updateSlackPluginConfig({
124
+ storage: args.storage,
125
+ agentId: args.agentId,
126
+ update: (config) => withChannelBinding(config, args.slackChannelId, found.space.id),
127
+ });
128
+ return boundMessage(found.space);
129
+ }
93
130
  export async function* handleSlackInvoke(args) {
94
131
  const fromWebhook = isSlackWebhookIngress(args.event.meta);
95
132
  if (!shouldHandleInvoke(args.event, args.agentId))
@@ -132,9 +169,69 @@ export async function* handleSlackInvoke(args) {
132
169
  return;
133
170
  }
134
171
  const slackMeta = getSlackThreadMeta(args.event.meta);
135
- const channelId = slackMeta?.channel
136
- ? resolveOpenBotChannelId(slackMeta.channel, args.config)
137
- : args.ctx.state.channelId;
172
+ const slackChannelId = slackMeta?.channel;
173
+ const postToSlack = async (text) => {
174
+ if (!slackChannelId || !text.trim())
175
+ return;
176
+ try {
177
+ await postSlackMessage({
178
+ token: credentials.botToken,
179
+ channel: slackChannelId,
180
+ text,
181
+ threadTs: slackMeta?.threadTs ?? slackMeta?.ts,
182
+ });
183
+ }
184
+ catch (error) {
185
+ console.warn("[slack] could not post reply", {
186
+ channel: slackChannelId,
187
+ error: error instanceof Error ? error.message : String(error),
188
+ });
189
+ }
190
+ };
191
+ // Each reply shows in the OpenBot thread and is posted to the Slack thread it answers.
192
+ const reply = (output) => postToSlack(output.data.content ?? "");
193
+ const botOutput = (content) => ({
194
+ type: "agent:output",
195
+ data: { content },
196
+ meta: {
197
+ agentId: ROUTING_AGENT_ID,
198
+ threadId,
199
+ source: "slack",
200
+ slack: slackMeta,
201
+ },
202
+ });
203
+ const command = slackChannelId ? parseUseSpaceCommand(userMessage) : undefined;
204
+ if (command && slackChannelId && args.storage) {
205
+ let answer;
206
+ try {
207
+ answer = await answerUseSpaceCommand({
208
+ command,
209
+ storage: args.storage,
210
+ agentId: args.agentId,
211
+ slackChannelId,
212
+ slackUserId: slackMeta?.user,
213
+ credentials,
214
+ });
215
+ }
216
+ catch (error) {
217
+ const message = error instanceof Error ? error.message : String(error);
218
+ answer = `I couldn't change this channel's Space: ${message}`;
219
+ }
220
+ if (answer !== undefined) {
221
+ const output = botOutput(answer);
222
+ yield output;
223
+ await reply(output);
224
+ return;
225
+ }
226
+ }
227
+ const route = slackChannelId
228
+ ? await resolveSlackSpace({
229
+ slackChannelId,
230
+ config: args.config,
231
+ storage: args.storage,
232
+ })
233
+ : undefined;
234
+ const channelId = route?.spaceId ?? args.ctx.state.channelId;
138
235
  if (!channelId)
139
236
  return;
140
237
  let prompt = userMessage;
@@ -152,25 +249,6 @@ export async function* handleSlackInvoke(args) {
152
249
  // Fall back to the raw mention if Slack history is unavailable.
153
250
  }
154
251
  }
155
- // Each reply shows in the OpenBot thread and is posted to the Slack thread it answers.
156
- const reply = async (output) => {
157
- if (!slackMeta?.channel || !output.data.content?.trim())
158
- return;
159
- try {
160
- await postSlackMessage({
161
- token: credentials.botToken,
162
- channel: slackMeta.channel,
163
- text: output.data.content,
164
- threadTs: slackMeta.threadTs ?? slackMeta.ts,
165
- });
166
- }
167
- catch (error) {
168
- console.warn("[slack] could not post reply", {
169
- channel: slackMeta.channel,
170
- error: error instanceof Error ? error.message : String(error),
171
- });
172
- }
173
- };
174
252
  try {
175
253
  for await (const output of bridgeSystemAgentRun({
176
254
  host: args.host,
@@ -186,19 +264,33 @@ export async function* handleSlackInvoke(args) {
186
264
  }
187
265
  catch (error) {
188
266
  const message = error instanceof Error ? error.message : String(error);
189
- const output = {
190
- type: "agent:output",
191
- data: { content: `Slack agent error: ${message}` },
192
- meta: {
193
- agentId: ROUTING_AGENT_ID,
194
- threadId,
195
- source: "slack",
196
- slack: slackMeta,
197
- },
198
- };
267
+ const output = botOutput(`Slack agent error: ${message}`);
199
268
  yield output;
200
269
  await reply(output);
201
270
  }
271
+ // The first message from a channel with no binding or mapping says how to pick a Space.
272
+ // It's marked first, so a failed save never turns into a hint on every message, and
273
+ // two messages at once post it once.
274
+ if (route?.source === "default" &&
275
+ slackChannelId &&
276
+ args.storage &&
277
+ !(args.config.routingHintsShown ?? []).includes(slackChannelId)) {
278
+ try {
279
+ const marked = await updateSlackPluginConfig({
280
+ storage: args.storage,
281
+ agentId: args.agentId,
282
+ update: (config) => withHintedChannel(config, slackChannelId),
283
+ });
284
+ if (marked)
285
+ await postToSlack(ROUTING_HINT);
286
+ }
287
+ catch (error) {
288
+ console.warn("[slack] could not save the routing hint", {
289
+ channel: slackChannelId,
290
+ error: error instanceof Error ? error.message : String(error),
291
+ });
292
+ }
293
+ }
202
294
  return;
203
295
  }
204
296
  if (!credentials) {
@@ -0,0 +1,19 @@
1
+ /** Someone tagged in the text: a person (`<@U…>`) or a user group (`<!subteam^…>`). */
2
+ const MENTION = /<@[^>]+>|<!subteam\^[^>]+>/;
3
+ export function slackMessageKind(slackEvent) {
4
+ if (slackEvent.bot_id)
5
+ return null;
6
+ // "Also send to channel" replies carry a subtype but are still replies.
7
+ if (slackEvent.subtype && slackEvent.subtype !== "thread_broadcast")
8
+ return null;
9
+ if (slackEvent.type === "app_mention")
10
+ return "mention";
11
+ if (slackEvent.type !== "message")
12
+ return null;
13
+ if (slackEvent.channel_type === "im")
14
+ return "direct";
15
+ const inThread = !!slackEvent.thread_ts && slackEvent.thread_ts !== slackEvent.ts;
16
+ if (inThread && !MENTION.test(slackEvent.text ?? ""))
17
+ return "threadReply";
18
+ return null;
19
+ }
package/dist/post.js CHANGED
@@ -16,3 +16,12 @@ export async function postSlackMessage(args) {
16
16
  throw new Error(body.error ?? `Slack API error (${res.status})`);
17
17
  }
18
18
  }
19
+ /** The Slack user's membership flags from `users.info`. Throws when Slack refuses. */
20
+ export async function fetchSlackUserFlags(args) {
21
+ const res = await fetch(`https://slack.com/api/users.info?${new URLSearchParams({ user: args.userId })}`, { headers: { Authorization: `Bearer ${args.token}` } });
22
+ const body = (await res.json());
23
+ if (!body.ok || !body.user) {
24
+ throw new Error(body.error ?? `Slack API error (${res.status})`);
25
+ }
26
+ return body.user;
27
+ }
@@ -0,0 +1,160 @@
1
+ // Which Space a Slack channel's messages go to. No imports, so tests run it directly.
2
+ export const DEFAULT_SPACE_ID = "general";
3
+ /** The npm name the host loads this plugin under, as it appears in AGENT.md `plugins`. */
4
+ export const SLACK_PLUGIN_ID = "@meetopenbot/slack";
5
+ /** Parses `channelMappings`: comma-separated `slackChannelId:spaceId` pairs. */
6
+ export function parseChannelMappings(raw) {
7
+ const index = new Map();
8
+ if (typeof raw !== "string")
9
+ return index;
10
+ for (const segment of raw.split(",")) {
11
+ const trimmed = segment.trim();
12
+ const colon = trimmed.indexOf(":");
13
+ if (colon <= 0 || colon === trimmed.length - 1)
14
+ continue;
15
+ const slackChannelId = trimmed.slice(0, colon).trim();
16
+ const spaceId = trimmed.slice(colon + 1).trim();
17
+ if (slackChannelId && spaceId)
18
+ index.set(slackChannelId, spaceId);
19
+ }
20
+ return index;
21
+ }
22
+ /** The saved bindings from plugin config, ignoring anything that isn't id → id. */
23
+ export function readChannelBindings(value) {
24
+ if (!value || typeof value !== "object" || Array.isArray(value))
25
+ return {};
26
+ const bindings = {};
27
+ for (const [slackChannelId, spaceId] of Object.entries(value)) {
28
+ const key = slackChannelId.trim();
29
+ if (!key || typeof spaceId !== "string" || !spaceId.trim())
30
+ continue;
31
+ bindings[key] = spaceId.trim();
32
+ }
33
+ return bindings;
34
+ }
35
+ /** Slack channel ids that were already told how to pick a Space. */
36
+ export function readHintedChannels(value) {
37
+ if (!Array.isArray(value))
38
+ return [];
39
+ return value.filter((id) => typeof id === "string" && id.trim() !== "");
40
+ }
41
+ /**
42
+ * The saved binding first, then `channelMappings`, then `general`. A binding to a Space
43
+ * that no longer exists is skipped when `spaceExists` is given.
44
+ */
45
+ export function resolveSpaceRoute(args) {
46
+ const slackChannelId = args.slackChannelId.trim();
47
+ if (!slackChannelId)
48
+ return { spaceId: DEFAULT_SPACE_ID, source: "default" };
49
+ const bound = args.bindings[slackChannelId];
50
+ if (bound && (!args.spaceExists || args.spaceExists(bound))) {
51
+ return { spaceId: bound, source: "binding" };
52
+ }
53
+ const mapped = args.mappings.get(slackChannelId);
54
+ if (mapped)
55
+ return { spaceId: mapped, source: "mapping" };
56
+ return { spaceId: DEFAULT_SPACE_ID, source: "default" };
57
+ }
58
+ const USE_SPACE_COMMAND = /^(?:please\s+)?use\s+(?:the\s+)?(space\s+)?(\S+?)(\s+space)?(\s+(?:here|in here|in this channel|for this channel))?\s*[.!]?$/i;
59
+ const SLACK_CHANNEL_LINK = /^<#[A-Z0-9]+(?:\|([^>]*))?>$/i;
60
+ const BARE_SPACE_REF = /^[\w.-]+$/;
61
+ export function parseUseSpaceCommand(text) {
62
+ const match = USE_SPACE_COMMAND.exec(text.replace(/\s+/g, " ").trim());
63
+ if (!match)
64
+ return undefined;
65
+ const [, spaceWordBefore, token, spaceWordAfter, here] = match;
66
+ const namedSpace = Boolean(spaceWordBefore || spaceWordAfter);
67
+ const link = SLACK_CHANNEL_LINK.exec(token);
68
+ if (link)
69
+ return { ref: (link[1] ?? "").trim(), explicit: true };
70
+ if (token.startsWith("#")) {
71
+ const ref = token.slice(1);
72
+ return ref ? { ref, explicit: true } : undefined;
73
+ }
74
+ if (!BARE_SPACE_REF.test(token))
75
+ return undefined;
76
+ if (!here && !namedSpace)
77
+ return undefined;
78
+ return { ref: token, explicit: namedSpace };
79
+ }
80
+ function normalizeSpaceRef(value) {
81
+ return value.trim().replace(/^#/, "").toLowerCase().replace(/[\s_]+/g, "-");
82
+ }
83
+ /** Matches a Space by exact id, then by id or name ignoring case, spaces and underscores. */
84
+ export function findSpace(ref, spaces) {
85
+ const exact = spaces.find((space) => space.id === ref);
86
+ if (exact)
87
+ return { kind: "found", space: exact };
88
+ const wanted = normalizeSpaceRef(ref);
89
+ if (!wanted)
90
+ return { kind: "missing" };
91
+ const matches = spaces.filter((space) => normalizeSpaceRef(space.id) === wanted || normalizeSpaceRef(space.name) === wanted);
92
+ if (matches.length === 1)
93
+ return { kind: "found", space: matches[0] };
94
+ if (matches.length > 1)
95
+ return { kind: "ambiguous", spaces: matches };
96
+ return { kind: "missing" };
97
+ }
98
+ /** The `slack` plugin entry among an agent's plugins, or -1. */
99
+ export function findSlackPluginRefIndex(refs) {
100
+ const exact = refs.findIndex((ref) => ref.id === SLACK_PLUGIN_ID);
101
+ if (exact >= 0)
102
+ return exact;
103
+ const named = refs.findIndex((ref) => ref.id === "slack" || ref.id.endsWith("/slack"));
104
+ if (named >= 0)
105
+ return named;
106
+ return refs.length === 1 ? 0 : -1;
107
+ }
108
+ /** Plugin config with this Slack channel bound to the Space. */
109
+ export function withChannelBinding(config, slackChannelId, spaceId) {
110
+ return {
111
+ ...config,
112
+ channelBindings: { ...readChannelBindings(config.channelBindings), [slackChannelId]: spaceId },
113
+ };
114
+ }
115
+ /** Plugin config noting that this Slack channel was shown the routing hint. */
116
+ export function withHintedChannel(config, slackChannelId) {
117
+ const hinted = readHintedChannels(config.routingHintsShown);
118
+ if (hinted.includes(slackChannelId))
119
+ return config;
120
+ return { ...config, routingHintsShown: [...hinted, slackChannelId] };
121
+ }
122
+ /**
123
+ * Only full members of the connected Slack workspace may change where a channel's work
124
+ * runs: not guests, not people from another organization in a shared channel, not bots.
125
+ */
126
+ export function canRouteSlackChannel(user, teamId) {
127
+ if (user.deleted || user.is_bot)
128
+ return false;
129
+ if (user.is_restricted || user.is_ultra_restricted || user.is_stranger)
130
+ return false;
131
+ if (user.team_id && teamId && user.team_id !== teamId && !user.enterprise_user)
132
+ return false;
133
+ return true;
134
+ }
135
+ export function formatSpace(space) {
136
+ const name = space.name.trim();
137
+ return name && normalizeSpaceRef(name) !== normalizeSpaceRef(space.id)
138
+ ? `#${space.id} (${name})`
139
+ : `#${space.id}`;
140
+ }
141
+ const MAX_LISTED_SPACES = 20;
142
+ export function formatSpaceList(spaces) {
143
+ if (spaces.length === 0)
144
+ return "There are no Spaces yet.";
145
+ const listed = spaces.slice(0, MAX_LISTED_SPACES).map(formatSpace).join(", ");
146
+ const more = spaces.length - MAX_LISTED_SPACES;
147
+ return more > 0 ? `${listed} and ${more} more` : listed;
148
+ }
149
+ export const ROUTING_HINT = `This channel isn't linked to a Space yet, so I worked in #${DEFAULT_SPACE_ID}. To pick one, mention me with \`use #space-name here\`.`;
150
+ export const ROUTING_FORBIDDEN = "Only full members of this Slack workspace can change which Space this channel uses.";
151
+ export const ROUTING_UNNAMED_CHANNEL = "Slack turned that into a channel link, so I can't read the Space name. Write it as `use space backend here`.";
152
+ export function boundMessage(space) {
153
+ return `Done. From now on, mentions in this channel go to the ${formatSpace(space)} Space.`;
154
+ }
155
+ export function missingSpaceMessage(ref, spaces) {
156
+ return `There's no Space called #${ref.replace(/^#/, "")}, and I don't create Spaces from Slack. Spaces you can use: ${formatSpaceList(spaces)}. To add one, create it in Behalf first.`;
157
+ }
158
+ export function ambiguousSpaceMessage(ref, spaces) {
159
+ return `More than one Space matches "${ref}": ${formatSpaceList(spaces)}. Use the exact id, like \`use #${spaces[0]?.id ?? DEFAULT_SPACE_ID} here\`.`;
160
+ }
package/dist/webhook.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { decodeWebhookRawBody, getWebhookHeader, webhookHttpResponse, } from "@meetopenbot/plugin-sdk";
2
- import { DEFAULT_OPENBOT_CHANNEL_ID, SLACK_USER_DISPLAY_NAME, resolveOpenBotChannelId, resolveSlackSigningSecret, } from "./config.js";
2
+ import { resolveSlackSpace } from "./bindings.js";
3
+ import { DEFAULT_OPENBOT_CHANNEL_ID, SLACK_USER_DISPLAY_NAME, resolveSlackSigningSecret, } from "./config.js";
4
+ import { slackMessageKind } from "./message-kind.js";
3
5
  import { verifySlackSignature } from "./verify.js";
4
6
  const seenSlackEvents = new Map();
5
7
  const SLACK_EVENT_DEDUP_MS = 5 * 60 * 1000;
@@ -17,17 +19,14 @@ function markSlackEventSeen(dedupKey) {
17
19
  seenSlackEvents.set(dedupKey, now);
18
20
  return false;
19
21
  }
22
+ /**
23
+ * One key per Slack message. A mention inside a thread arrives twice, as `app_mention`
24
+ * and as `message`, with different event ids.
25
+ */
20
26
  function slackEventDedupKey(payload, slackEvent) {
21
- if (payload.event_id)
22
- return payload.event_id;
23
- return `${slackEvent.channel}:${slackEvent.ts}`;
24
- }
25
- function shouldProcessSlackEvent(slackEvent) {
26
- if (slackEvent.bot_id || slackEvent.subtype)
27
- return false;
28
- if (slackEvent.type === "app_mention")
29
- return true;
30
- return slackEvent.type === "message" && slackEvent.channel_type === "im";
27
+ if (slackEvent.channel && slackEvent.ts)
28
+ return `${slackEvent.channel}:${slackEvent.ts}`;
29
+ return payload.event_id ?? "";
31
30
  }
32
31
  function normalizeSlackText(text) {
33
32
  return text.replace(/<@[^>]+>/g, "").replace(/\s+/g, " ").trim();
@@ -68,7 +67,20 @@ export async function* handleSlackWebhook(args) {
68
67
  return;
69
68
  }
70
69
  const slackEvent = payload.type === "event_callback" ? payload.event : undefined;
71
- if (!slackEvent || !shouldProcessSlackEvent(slackEvent)) {
70
+ const kind = slackEvent ? slackMessageKind(slackEvent) : null;
71
+ if (!slackEvent || !kind) {
72
+ yield webhookHttpResponse({ status: 200, body: {} });
73
+ return;
74
+ }
75
+ const openBotChannelId = slackEvent.channel
76
+ ? (await resolveSlackSpace({
77
+ slackChannelId: slackEvent.channel,
78
+ config: args.config,
79
+ storage: args.storage,
80
+ })).spaceId
81
+ : DEFAULT_OPENBOT_CHANNEL_ID;
82
+ if (kind === "threadReply" &&
83
+ !(await args.hasThread(openBotChannelId, slackEvent.thread_ts))) {
72
84
  yield webhookHttpResponse({ status: 200, body: {} });
73
85
  return;
74
86
  }
@@ -91,9 +103,6 @@ export async function* handleSlackWebhook(args) {
91
103
  ts: slackEvent.ts,
92
104
  threadTs: slackEvent.thread_ts,
93
105
  };
94
- const openBotChannelId = slackEvent.channel
95
- ? resolveOpenBotChannelId(slackEvent.channel, args.config)
96
- : DEFAULT_OPENBOT_CHANNEL_ID;
97
106
  args.ctx.state.channelId = openBotChannelId;
98
107
  yield webhookHttpResponse({ status: 200, body: {} });
99
108
  yield {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@meetopenbot/slack",
3
- "version": "1.3.1",
3
+ "version": "1.5.0",
4
4
  "description": "Slack Events API ingress, simple agent replies, and thread delivery for OpenBot",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -28,6 +28,7 @@
28
28
  "scripts": {
29
29
  "build": "tsc && node ../../scripts/write-plugin-declaration.mjs",
30
30
  "dev": "tsc --watch --preserveWatchOutput",
31
- "typecheck": "tsc --noEmit"
31
+ "typecheck": "tsc --noEmit",
32
+ "test": "node --experimental-strip-types --test src/*.test.ts"
32
33
  }
33
34
  }