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