@meetopenbot/slack 1.6.1 → 1.7.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/dist/index.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { definePlugin } from "@meetopenbot/plugin-sdk";
2
2
  import { pluginConfigSchema, readSlackConfig, SLACK_BOT_SCOPES, slackCredentials, } from "./config.js";
3
3
  import { handleSlackInvoke } from "./invoke.js";
4
- import { addSlackReaction } from "./reactions.js";
4
+ import { slackRelayMessage } from "./needs-input.js";
5
+ import { postSlackMessage } from "./post.js";
5
6
  import { handleSlackWebhook } from "./webhook.js";
6
7
  export const plugin = definePlugin({
7
8
  name: "Slack",
@@ -33,18 +34,17 @@ export const plugin = definePlugin({
33
34
  return !!state && typeof state === "object" && Object.keys(state).length > 0;
34
35
  },
35
36
  storage: context.storage,
36
- acknowledge: (message) => {
37
- const credentials = slackCredentials(context);
38
- if (!credentials)
39
- return;
40
- void addSlackReaction({
41
- token: credentials.botToken,
42
- channel: message.channel,
43
- timestamp: message.ts,
44
- });
45
- },
37
+ credentials: slackCredentials(context),
46
38
  });
47
39
  },
40
+ // Behalf's run started from a Slack message answers in that Slack thread.
41
+ async onOriginEvent({ event, trigger, context }) {
42
+ const credentials = slackCredentials(context);
43
+ const message = slackRelayMessage(event, trigger);
44
+ if (!credentials || !message)
45
+ return;
46
+ await postSlackMessage({ token: credentials.botToken, ...message });
47
+ },
48
48
  async *run({ event, handlerCtx, context }) {
49
49
  const slackConfig = readSlackConfig(context.config);
50
50
  yield* handleSlackInvoke({
@@ -53,9 +53,6 @@ export const plugin = definePlugin({
53
53
  agentId: context.agentId,
54
54
  config: slackConfig,
55
55
  credentials: slackCredentials(context),
56
- host: context.host,
57
- storage: context.storage,
58
- publicBaseUrl: context.publicBaseUrl,
59
56
  });
60
57
  },
61
58
  });
package/dist/invoke.js CHANGED
@@ -1,148 +1,16 @@
1
- import { randomUUID } from "node:crypto";
2
1
  import { agentModelKeyEnv, agentModelProvider, agentOutput, creditsErrorMessage, hasLlmAuth, llmAuthNotConfiguredMessage, shouldHandleInvoke, toAgentTurnEvents, } from "@meetopenbot/plugin-sdk";
3
2
  import { runSlackAgent } from "./agent.js";
4
- import { resolveSlackSpace, updateSlackPluginConfig } from "./bindings.js";
5
- import { resolveSlackModel, ROUTING_AGENT_ID, SLACK_USER_DISPLAY_NAME, } from "./config.js";
6
- import { buildPromptWithSlackContext } from "./context.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";
9
- import { slackNeedsInputNotice, SLACK_THREAD_STATE_KEY, } from "./needs-input.js";
10
- import { getSlackThreadMeta, isSlackWebhookIngress } from "./webhook.js";
3
+ import { resolveSlackModel } from "./config.js";
11
4
  /**
12
5
  * The host connects Slack before `run`. A run without credentials means the host is too
13
6
  * old to know `oauthApp` connections.
14
7
  */
15
8
  export const SLACK_NEEDS_NEWER_RUNTIME = "Slack needs a newer OpenBot runtime to connect. Update the runtime and try again.";
16
- /** Behalf's own answer, as opposed to what a specialist said inside it. */
17
- function isCoordinatorReply(event) {
18
- return event.type === "agent:output" && !event.meta?.parentToolCallId;
19
- }
20
- async function* bridgeSystemAgentRun(args) {
21
- const runId = `slack_${randomUUID()}`;
22
- const slackMeta = getSlackThreadMeta(args.meta);
23
- // Only a run that answers a Slack message is marked as Slack's; a reply typed in OpenBot is not.
24
- const slackOrigin = isSlackWebhookIngress(args.meta)
25
- ? { source: "slack", slack: slackMeta }
26
- : {};
27
- const eventQueue = [];
28
- let resolveNext = null;
29
- let isFinished = false;
30
- const runPromise = args.host
31
- .runAgent({
32
- runId,
33
- agentId: ROUTING_AGENT_ID,
34
- publicBaseUrl: args.publicBaseUrl,
35
- persistEvents: false,
36
- event: {
37
- type: "agent:invoke",
38
- data: {
39
- agentId: ROUTING_AGENT_ID,
40
- role: "user",
41
- content: args.userMessage,
42
- },
43
- meta: {
44
- channelId: args.channelId,
45
- threadId: args.threadId,
46
- // The person's message is already in the thread; don't store it a second time.
47
- alreadyStored: true,
48
- ...slackOrigin,
49
- userName: SLACK_USER_DISPLAY_NAME,
50
- ...(typeof args.meta?.userId === "string" ? { userId: args.meta.userId } : {}),
51
- },
52
- },
53
- onEvent: async (outEvent) => {
54
- // The run isn't stored here; the Slack run that wraps it stores what it yields. So pass
55
- // on everything a normal Behalf run would show: replies, tool calls, and the cards a
56
- // specialist (Linear, GitHub…) raises inside it. Without those cards a run waiting on
57
- // one would sit on "Working…" with nothing to answer. Only this run's own start/end
58
- // are left out; the Slack run has its own.
59
- const isOwnLifecycle = (outEvent.type === "agent:run:start" || outEvent.type === "agent:run:end") &&
60
- !outEvent.meta?.parentToolCallId;
61
- if (!isOwnLifecycle) {
62
- const isReply = isCoordinatorReply(outEvent);
63
- eventQueue.push({
64
- ...outEvent,
65
- meta: {
66
- ...outEvent.meta,
67
- threadId: args.threadId,
68
- ...(isReply ? { agentId: ROUTING_AGENT_ID, ...slackOrigin } : {}),
69
- },
70
- });
71
- }
72
- if (resolveNext) {
73
- resolveNext();
74
- resolveNext = null;
75
- }
76
- },
77
- })
78
- .catch((error) => {
79
- const message = error instanceof Error ? error.message : String(error);
80
- eventQueue.push({
81
- type: "agent:output",
82
- data: { content: `Slack agent error: ${message}` },
83
- meta: {
84
- agentId: ROUTING_AGENT_ID,
85
- threadId: args.threadId,
86
- ...slackOrigin,
87
- },
88
- });
89
- })
90
- .finally(() => {
91
- isFinished = true;
92
- if (resolveNext) {
93
- resolveNext();
94
- resolveNext = null;
95
- }
96
- });
97
- while (!isFinished || eventQueue.length > 0) {
98
- if (eventQueue.length === 0) {
99
- await new Promise((resolve) => {
100
- resolveNext = resolve;
101
- });
102
- }
103
- while (eventQueue.length > 0) {
104
- yield eventQueue.shift();
105
- }
106
- }
107
- await runPromise;
108
- }
109
9
  /**
110
- * The bot's answer to "use #space here", or undefined when the message isn't that command
111
- * after all (a bare word that names no Space, like "use pnpm here"). Never creates a Space.
10
+ * The Slack specialist, for when someone addresses it directly in OpenBot. Messages that
11
+ * arrive from Slack never get here: the webhook hands them to Behalf (see `webhook.ts`).
112
12
  */
113
- async function answerUseSpaceCommand(args) {
114
- if (!args.command.ref)
115
- return ROUTING_UNNAMED_CHANNEL;
116
- const spaces = (await args.storage.getChannels()).map(({ id, name }) => ({ id, name }));
117
- const found = findSpace(args.command.ref, spaces);
118
- if (!args.command.explicit && found.kind !== "found")
119
- return undefined;
120
- if (!args.slackUserId)
121
- return ROUTING_FORBIDDEN;
122
- try {
123
- const user = await fetchSlackUserFlags({
124
- token: args.credentials.botToken,
125
- userId: args.slackUserId,
126
- });
127
- if (!canRouteSlackChannel(user, args.credentials.teamId))
128
- return ROUTING_FORBIDDEN;
129
- }
130
- catch {
131
- return ROUTING_FORBIDDEN;
132
- }
133
- if (found.kind === "missing")
134
- return missingSpaceMessage(args.command.ref, spaces);
135
- if (found.kind === "ambiguous")
136
- return ambiguousSpaceMessage(args.command.ref, found.spaces);
137
- await updateSlackPluginConfig({
138
- storage: args.storage,
139
- agentId: args.agentId,
140
- update: (config) => withChannelBinding(config, args.slackChannelId, found.space.id),
141
- });
142
- return boundMessage(found.space);
143
- }
144
13
  export async function* handleSlackInvoke(args) {
145
- const fromWebhook = isSlackWebhookIngress(args.event.meta);
146
14
  if (!shouldHandleInvoke(args.event, args.agentId))
147
15
  return;
148
16
  if (args.event.meta?.threadId) {
@@ -152,176 +20,7 @@ export async function* handleSlackInvoke(args) {
152
20
  const userMessage = (args.event.data.content ?? "").trim();
153
21
  if (!userMessage || !threadId)
154
22
  return;
155
- const credentials = args.credentials;
156
- if (fromWebhook) {
157
- if (!credentials) {
158
- yield {
159
- type: "agent:output",
160
- data: { content: SLACK_NEEDS_NEWER_RUNTIME },
161
- meta: {
162
- agentId: ROUTING_AGENT_ID,
163
- threadId,
164
- source: "slack",
165
- slack: getSlackThreadMeta(args.event.meta),
166
- },
167
- };
168
- return;
169
- }
170
- if (!args.host?.runAgent) {
171
- yield {
172
- type: "agent:output",
173
- data: {
174
- content: "Slack plugin requires host.runAgent to delegate to the system agent.",
175
- },
176
- meta: {
177
- agentId: ROUTING_AGENT_ID,
178
- threadId,
179
- source: "slack",
180
- slack: getSlackThreadMeta(args.event.meta),
181
- },
182
- };
183
- return;
184
- }
185
- const slackMeta = getSlackThreadMeta(args.event.meta);
186
- const slackChannelId = slackMeta?.channel;
187
- const postToSlack = async (text) => {
188
- if (!slackChannelId || !text.trim())
189
- return;
190
- try {
191
- await postSlackMessage({
192
- token: credentials.botToken,
193
- channel: slackChannelId,
194
- text,
195
- threadTs: slackMeta?.threadTs ?? slackMeta?.ts,
196
- });
197
- }
198
- catch (error) {
199
- console.warn("[slack] could not post reply", {
200
- channel: slackChannelId,
201
- error: error instanceof Error ? error.message : String(error),
202
- });
203
- }
204
- };
205
- // Each reply shows in the OpenBot thread and is posted to the Slack thread it answers.
206
- const reply = (output) => postToSlack(output.data.content ?? "");
207
- const botOutput = (content) => ({
208
- type: "agent:output",
209
- data: { content },
210
- meta: {
211
- agentId: ROUTING_AGENT_ID,
212
- threadId,
213
- source: "slack",
214
- slack: slackMeta,
215
- },
216
- });
217
- const command = slackChannelId ? parseUseSpaceCommand(userMessage) : undefined;
218
- if (command && slackChannelId && args.storage) {
219
- let answer;
220
- try {
221
- answer = await answerUseSpaceCommand({
222
- command,
223
- storage: args.storage,
224
- agentId: args.agentId,
225
- slackChannelId,
226
- slackUserId: slackMeta?.user,
227
- credentials,
228
- });
229
- }
230
- catch (error) {
231
- const message = error instanceof Error ? error.message : String(error);
232
- answer = `I couldn't change this channel's Space: ${message}`;
233
- }
234
- if (answer !== undefined) {
235
- const output = botOutput(answer);
236
- yield output;
237
- await reply(output);
238
- return;
239
- }
240
- }
241
- const route = slackChannelId
242
- ? await resolveSlackSpace({
243
- slackChannelId,
244
- config: args.config,
245
- storage: args.storage,
246
- })
247
- : undefined;
248
- const channelId = route?.spaceId ?? args.ctx.state.channelId;
249
- if (!channelId)
250
- return;
251
- let prompt = userMessage;
252
- if (slackMeta?.channel && slackMeta.ts) {
253
- try {
254
- prompt = await buildPromptWithSlackContext({
255
- token: credentials.botToken,
256
- channel: slackMeta.channel,
257
- messageTs: slackMeta.ts,
258
- threadTs: slackMeta.threadTs,
259
- userMessage,
260
- });
261
- }
262
- catch {
263
- // Fall back to the raw mention if Slack history is unavailable.
264
- }
265
- }
266
- // Remember the thread came from Slack, so replies typed in OpenBot still go to Behalf.
267
- await args.storage
268
- ?.patchThreadState({
269
- channelId,
270
- threadId,
271
- state: { [SLACK_THREAD_STATE_KEY]: { channel: slackChannelId, threadTs: threadId } },
272
- })
273
- .catch(() => undefined);
274
- try {
275
- for await (const output of bridgeSystemAgentRun({
276
- host: args.host,
277
- channelId,
278
- threadId,
279
- userMessage: prompt,
280
- meta: args.event.meta,
281
- publicBaseUrl: args.publicBaseUrl,
282
- })) {
283
- yield output;
284
- if (isCoordinatorReply(output))
285
- await reply(output);
286
- else {
287
- const notice = slackNeedsInputNotice(output);
288
- if (notice)
289
- await postToSlack(notice);
290
- }
291
- }
292
- }
293
- catch (error) {
294
- const message = error instanceof Error ? error.message : String(error);
295
- const output = botOutput(`Slack agent error: ${message}`);
296
- yield output;
297
- await reply(output);
298
- }
299
- // The first message from a channel with no binding or mapping says how to pick a Space.
300
- // It's marked first, so a failed save never turns into a hint on every message, and
301
- // two messages at once post it once.
302
- if (route?.source === "default" &&
303
- slackChannelId &&
304
- args.storage &&
305
- !(args.config.routingHintsShown ?? []).includes(slackChannelId)) {
306
- try {
307
- const marked = await updateSlackPluginConfig({
308
- storage: args.storage,
309
- agentId: args.agentId,
310
- update: (config) => withHintedChannel(config, slackChannelId),
311
- });
312
- if (marked)
313
- await postToSlack(ROUTING_HINT);
314
- }
315
- catch (error) {
316
- console.warn("[slack] could not save the routing hint", {
317
- channel: slackChannelId,
318
- error: error instanceof Error ? error.message : String(error),
319
- });
320
- }
321
- }
322
- return;
323
- }
324
- if (!credentials) {
23
+ if (!args.credentials) {
325
24
  yield agentOutput({
326
25
  agentId: args.agentId,
327
26
  content: SLACK_NEEDS_NEWER_RUNTIME,
@@ -330,38 +29,6 @@ export async function* handleSlackInvoke(args) {
330
29
  });
331
30
  return;
332
31
  }
333
- // A reply typed in OpenBot into a thread that started in Slack is for Behalf, not for the
334
- // Slack specialist, which only has Slack tools.
335
- const metaChannelId = args.event.meta?.channelId;
336
- const channelId = typeof metaChannelId === "string" ? metaChannelId : undefined;
337
- if (args.host?.runAgent && channelId && args.storage) {
338
- const details = await args.storage.getThreadDetails({ channelId, threadId }).catch(() => null);
339
- const state = details?.state;
340
- if (state?.[SLACK_THREAD_STATE_KEY]) {
341
- try {
342
- for await (const output of bridgeSystemAgentRun({
343
- host: args.host,
344
- channelId,
345
- threadId,
346
- userMessage,
347
- meta: args.event.meta,
348
- publicBaseUrl: args.publicBaseUrl,
349
- })) {
350
- yield output;
351
- }
352
- }
353
- catch (error) {
354
- const message = error instanceof Error ? error.message : String(error);
355
- yield agentOutput({
356
- agentId: ROUTING_AGENT_ID,
357
- content: `Agent error: ${message}`,
358
- threadId,
359
- meta: args.event.meta,
360
- });
361
- }
362
- return;
363
- }
364
- }
365
32
  const model = resolveSlackModel(args.config);
366
33
  let provider;
367
34
  try {
@@ -378,8 +45,8 @@ export async function* handleSlackInvoke(args) {
378
45
  }
379
46
  for await (const item of runSlackAgent({
380
47
  prompt: userMessage,
381
- botToken: credentials.botToken,
382
- teamId: credentials.teamId,
48
+ botToken: args.credentials.botToken,
49
+ teamId: args.credentials.teamId,
383
50
  model,
384
51
  })) {
385
52
  yield* toAgentTurnEvents(item, args.agentId, threadId, args.event.meta);
@@ -1,9 +1,3 @@
1
- /** Thread-state key marking an OpenBot thread that started from a Slack message. */
2
- export const SLACK_THREAD_STATE_KEY = "slackThread";
3
- /** Events from the system agent's run that the Slack thread's own run must pass on. */
4
- export function isInteractionEvent(event) {
5
- return event.type === "client:ui:widget" || event.type === "action:set_thread_status:result";
6
- }
7
1
  /**
8
2
  * What to tell the Slack thread when Behalf stops to ask for something (approval, a question,
9
3
  * a connection to set up). The card itself only exists in OpenBot, so without this the Slack
@@ -17,8 +11,30 @@ export function slackNeedsInputNotice(event) {
17
11
  return undefined;
18
12
  const hasInput = (Array.isArray(widget.actions) && widget.actions.length > 0) ||
19
13
  ("fields" in widget && Array.isArray(widget.fields) && widget.fields.length > 0);
20
- if (!hasInput)
14
+ // A connect card has a button in the app but carries no actions of its own.
15
+ const isConnect = widget.metadata?.type === "connection_request";
16
+ if (!hasInput && !isConnect)
21
17
  return undefined;
22
18
  const title = widget.title?.trim();
23
19
  return `I need your input to continue${title ? `: ${title}` : ""}. Open this conversation in OpenBot to answer, and I'll carry on from there.`;
24
20
  }
21
+ /** Behalf's own answer, as opposed to what a specialist said inside its run. */
22
+ function isCoordinatorReply(event) {
23
+ return event.type === "agent:output" && !event.meta?.parentToolCallId;
24
+ }
25
+ /**
26
+ * What a Behalf run that started from a Slack message should say back in that thread for
27
+ * one of its events: its own replies, and a note when it stops for input that only exists in
28
+ * OpenBot. Undefined when the event isn't for Slack or the trigger names no Slack thread.
29
+ */
30
+ export function slackRelayMessage(event, trigger) {
31
+ const slack = trigger.meta?.slack;
32
+ if (!slack?.channel)
33
+ return undefined;
34
+ const text = isCoordinatorReply(event)
35
+ ? (event.data.content ?? "")
36
+ : slackNeedsInputNotice(event);
37
+ if (!text?.trim())
38
+ return undefined;
39
+ return { channel: slack.channel, threadTs: slack.threadTs ?? slack.ts, text };
40
+ }
@@ -0,0 +1,38 @@
1
+ import { updateSlackPluginConfig } from "./bindings.js";
2
+ import { fetchSlackUserFlags } from "./post.js";
3
+ import { ambiguousSpaceMessage, boundMessage, canRouteSlackChannel, findSpace, missingSpaceMessage, ROUTING_FORBIDDEN, ROUTING_UNNAMED_CHANNEL, withChannelBinding, } from "./routing.js";
4
+ /**
5
+ * The bot's answer to "use #space here", or undefined when the message isn't that command
6
+ * after all (a bare word that names no Space, like "use pnpm here"). Never creates a Space.
7
+ */
8
+ export async function answerUseSpaceCommand(args) {
9
+ if (!args.command.ref)
10
+ return ROUTING_UNNAMED_CHANNEL;
11
+ const spaces = (await args.storage.getChannels()).map(({ id, name }) => ({ id, name }));
12
+ const found = findSpace(args.command.ref, spaces);
13
+ if (!args.command.explicit && found.kind !== "found")
14
+ return undefined;
15
+ if (!args.slackUserId)
16
+ return ROUTING_FORBIDDEN;
17
+ try {
18
+ const user = await fetchSlackUserFlags({
19
+ token: args.credentials.botToken,
20
+ userId: args.slackUserId,
21
+ });
22
+ if (!canRouteSlackChannel(user, args.credentials.teamId))
23
+ return ROUTING_FORBIDDEN;
24
+ }
25
+ catch {
26
+ return ROUTING_FORBIDDEN;
27
+ }
28
+ if (found.kind === "missing")
29
+ return missingSpaceMessage(args.command.ref, spaces);
30
+ if (found.kind === "ambiguous")
31
+ return ambiguousSpaceMessage(args.command.ref, found.spaces);
32
+ await updateSlackPluginConfig({
33
+ storage: args.storage,
34
+ agentId: args.agentId,
35
+ update: (config) => withChannelBinding(config, args.slackChannelId, found.space.id),
36
+ });
37
+ return boundMessage(found.space);
38
+ }
package/dist/webhook.js CHANGED
@@ -1,6 +1,11 @@
1
1
  import { decodeWebhookRawBody, getWebhookHeader, webhookHttpResponse, } from "@meetopenbot/plugin-sdk";
2
- import { resolveSlackSpace } from "./bindings.js";
3
- import { DEFAULT_OPENBOT_CHANNEL_ID, SLACK_USER_DISPLAY_NAME, resolveSlackSigningSecret, } from "./config.js";
2
+ import { resolveSlackSpace, updateSlackPluginConfig } from "./bindings.js";
3
+ import { DEFAULT_OPENBOT_CHANNEL_ID, ROUTING_AGENT_ID, SLACK_USER_DISPLAY_NAME, resolveSlackSigningSecret, } from "./config.js";
4
+ import { buildPromptWithSlackContext } from "./context.js";
5
+ import { postSlackMessage } from "./post.js";
6
+ import { addSlackReaction } from "./reactions.js";
7
+ import { ROUTING_HINT, parseUseSpaceCommand, withHintedChannel } from "./routing.js";
8
+ import { answerUseSpaceCommand } from "./space-command.js";
4
9
  import { slackMessageKind } from "./message-kind.js";
5
10
  import { verifySlackSignature } from "./verify.js";
6
11
  const seenSlackEvents = new Map();
@@ -72,13 +77,14 @@ export async function* handleSlackWebhook(args) {
72
77
  yield webhookHttpResponse({ status: 200, body: {} });
73
78
  return;
74
79
  }
75
- const openBotChannelId = slackEvent.channel
76
- ? (await resolveSlackSpace({
80
+ const route = slackEvent.channel
81
+ ? await resolveSlackSpace({
77
82
  slackChannelId: slackEvent.channel,
78
83
  config: args.config,
79
84
  storage: args.storage,
80
- })).spaceId
81
- : DEFAULT_OPENBOT_CHANNEL_ID;
85
+ })
86
+ : undefined;
87
+ const openBotChannelId = route?.spaceId ?? DEFAULT_OPENBOT_CHANNEL_ID;
82
88
  if (kind === "threadReply" &&
83
89
  !(await args.hasThread(openBotChannelId, slackEvent.thread_ts))) {
84
90
  yield webhookHttpResponse({ status: 200, body: {} });
@@ -95,9 +101,6 @@ export async function* handleSlackWebhook(args) {
95
101
  yield webhookHttpResponse({ status: 200, body: {} });
96
102
  return;
97
103
  }
98
- if (slackEvent.channel && slackEvent.ts) {
99
- args.acknowledge?.({ channel: slackEvent.channel, ts: slackEvent.ts });
100
- }
101
104
  args.ctx.state.threadId = threadId;
102
105
  const slackMeta = {
103
106
  teamId: payload.team_id,
@@ -107,14 +110,81 @@ export async function* handleSlackWebhook(args) {
107
110
  threadTs: slackEvent.thread_ts,
108
111
  };
109
112
  args.ctx.state.channelId = openBotChannelId;
113
+ // Slack wants its answer within seconds; everything below can take longer.
110
114
  yield webhookHttpResponse({ status: 200, body: {} });
115
+ const credentials = args.credentials;
116
+ if (!credentials) {
117
+ console.warn("[slack] Slack isn't connected, so the message was not answered");
118
+ return;
119
+ }
120
+ // Show the person the bot has seen the message.
121
+ if (slackEvent.channel && slackEvent.ts) {
122
+ void addSlackReaction({
123
+ token: credentials.botToken,
124
+ channel: slackEvent.channel,
125
+ timestamp: slackEvent.ts,
126
+ });
127
+ }
128
+ const postToSlack = async (message) => {
129
+ if (!slackEvent.channel)
130
+ return;
131
+ try {
132
+ await postSlackMessage({
133
+ token: credentials.botToken,
134
+ channel: slackEvent.channel,
135
+ text: message,
136
+ threadTs: slackEvent.thread_ts ?? slackEvent.ts,
137
+ });
138
+ }
139
+ catch (error) {
140
+ console.warn("[slack] could not post reply", {
141
+ channel: slackEvent.channel,
142
+ error: error instanceof Error ? error.message : String(error),
143
+ });
144
+ }
145
+ };
146
+ const command = slackEvent.channel ? parseUseSpaceCommand(text) : undefined;
147
+ if (command && slackEvent.channel && args.storage) {
148
+ let answer;
149
+ try {
150
+ answer = await answerUseSpaceCommand({
151
+ command,
152
+ storage: args.storage,
153
+ agentId: args.agentId,
154
+ slackChannelId: slackEvent.channel,
155
+ slackUserId: slackEvent.user,
156
+ credentials,
157
+ });
158
+ }
159
+ catch (error) {
160
+ const message = error instanceof Error ? error.message : String(error);
161
+ answer = `I couldn't change this channel's Space: ${message}`;
162
+ }
163
+ if (answer !== undefined) {
164
+ await postToSlack(answer);
165
+ return;
166
+ }
167
+ }
168
+ let prompt = text;
169
+ if (slackEvent.channel && slackEvent.ts) {
170
+ try {
171
+ prompt = await buildPromptWithSlackContext({
172
+ token: credentials.botToken,
173
+ channel: slackEvent.channel,
174
+ messageTs: slackEvent.ts,
175
+ threadTs: slackEvent.thread_ts,
176
+ userMessage: text,
177
+ });
178
+ }
179
+ catch {
180
+ // Fall back to the raw mention if Slack history is unavailable.
181
+ }
182
+ }
183
+ // Hand the message to Behalf. The host runs it like one typed in OpenBot and calls the
184
+ // plugin's `onOriginEvent` with what it does, so replies reach this Slack thread.
111
185
  yield {
112
186
  type: "agent:invoke",
113
- data: {
114
- agentId: args.agentId,
115
- role: "user",
116
- content: text,
117
- },
187
+ data: { agentId: ROUTING_AGENT_ID, role: "user", content: prompt },
118
188
  meta: {
119
189
  channelId: openBotChannelId,
120
190
  threadId,
@@ -124,4 +194,28 @@ export async function* handleSlackWebhook(args) {
124
194
  ...(slackEvent.user ? { userId: slackEvent.user } : {}),
125
195
  },
126
196
  };
197
+ // The first message from a channel with no binding or mapping says how to pick a Space.
198
+ // It's marked first, so a failed save never turns into a hint on every message, and two
199
+ // messages at once post it once.
200
+ if (slackEvent.channel &&
201
+ args.storage &&
202
+ route?.source === "default" &&
203
+ !(args.config.routingHintsShown ?? []).includes(slackEvent.channel)) {
204
+ const channel = slackEvent.channel;
205
+ try {
206
+ const marked = await updateSlackPluginConfig({
207
+ storage: args.storage,
208
+ agentId: args.agentId,
209
+ update: (config) => withHintedChannel(config, channel),
210
+ });
211
+ if (marked)
212
+ await postToSlack(ROUTING_HINT);
213
+ }
214
+ catch (error) {
215
+ console.warn("[slack] could not save the routing hint", {
216
+ channel,
217
+ error: error instanceof Error ? error.message : String(error),
218
+ });
219
+ }
220
+ }
127
221
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@meetopenbot/slack",
3
- "version": "1.6.1",
3
+ "version": "1.7.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",
@@ -19,7 +19,7 @@
19
19
  "dist"
20
20
  ],
21
21
  "dependencies": {
22
- "@meetopenbot/plugin-sdk": "^2.9.0"
22
+ "@meetopenbot/plugin-sdk": "^2.10.0"
23
23
  },
24
24
  "devDependencies": {
25
25
  "@types/node": "^20.10.1",