@meetopenbot/slack 1.5.0 → 1.6.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,7 @@
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
5
  import { handleSlackWebhook } from "./webhook.js";
5
6
  export const plugin = definePlugin({
6
7
  name: "Slack",
@@ -32,6 +33,16 @@ export const plugin = definePlugin({
32
33
  return !!state && typeof state === "object" && Object.keys(state).length > 0;
33
34
  },
34
35
  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
+ },
35
46
  });
36
47
  },
37
48
  async *run({ event, handlerCtx, context }) {
package/dist/invoke.js CHANGED
@@ -6,6 +6,7 @@ import { resolveSlackModel, ROUTING_AGENT_ID, SLACK_USER_DISPLAY_NAME, } from ".
6
6
  import { buildPromptWithSlackContext } from "./context.js";
7
7
  import { fetchSlackUserFlags, postSlackMessage } from "./post.js";
8
8
  import { ambiguousSpaceMessage, boundMessage, canRouteSlackChannel, findSpace, missingSpaceMessage, parseUseSpaceCommand, ROUTING_FORBIDDEN, ROUTING_HINT, ROUTING_UNNAMED_CHANNEL, withChannelBinding, withHintedChannel, } from "./routing.js";
9
+ import { isInteractionEvent, slackNeedsInputNotice, SLACK_THREAD_STATE_KEY, } from "./needs-input.js";
9
10
  import { getSlackThreadMeta, isSlackWebhookIngress } from "./webhook.js";
10
11
  /**
11
12
  * The host connects Slack before `run`. A run without credentials means the host is too
@@ -15,6 +16,10 @@ export const SLACK_NEEDS_NEWER_RUNTIME = "Slack needs a newer OpenBot runtime to
15
16
  async function* bridgeSystemAgentRun(args) {
16
17
  const runId = `slack_${randomUUID()}`;
17
18
  const slackMeta = getSlackThreadMeta(args.meta);
19
+ // Only a run that answers a Slack message is marked as Slack's; a reply typed in OpenBot is not.
20
+ const slackOrigin = isSlackWebhookIngress(args.meta)
21
+ ? { source: "slack", slack: slackMeta }
22
+ : {};
18
23
  const eventQueue = [];
19
24
  let resolveNext = null;
20
25
  let isFinished = false;
@@ -34,8 +39,7 @@ async function* bridgeSystemAgentRun(args) {
34
39
  meta: {
35
40
  channelId: args.channelId,
36
41
  threadId: args.threadId,
37
- source: "slack",
38
- slack: slackMeta,
42
+ ...slackOrigin,
39
43
  userName: SLACK_USER_DISPLAY_NAME,
40
44
  ...(typeof args.meta?.userId === "string" ? { userId: args.meta.userId } : {}),
41
45
  },
@@ -49,11 +53,18 @@ async function* bridgeSystemAgentRun(args) {
49
53
  ...output.meta,
50
54
  agentId: ROUTING_AGENT_ID,
51
55
  threadId: args.threadId,
52
- source: "slack",
53
- slack: slackMeta,
56
+ ...slackOrigin,
54
57
  },
55
58
  });
56
59
  }
60
+ else if (isInteractionEvent(outEvent) && !outEvent.meta?.parentToolCallId) {
61
+ // The run isn't stored, so a card it waits on would never reach OpenBot and the
62
+ // thread would sit on "Working…" with nothing to answer. Pass cards on to be stored.
63
+ eventQueue.push({
64
+ ...outEvent,
65
+ meta: { ...outEvent.meta, threadId: args.threadId },
66
+ });
67
+ }
57
68
  if (resolveNext) {
58
69
  resolveNext();
59
70
  resolveNext = null;
@@ -68,8 +79,7 @@ async function* bridgeSystemAgentRun(args) {
68
79
  meta: {
69
80
  agentId: ROUTING_AGENT_ID,
70
81
  threadId: args.threadId,
71
- source: "slack",
72
- slack: slackMeta,
82
+ ...slackOrigin,
73
83
  },
74
84
  });
75
85
  })
@@ -249,6 +259,14 @@ export async function* handleSlackInvoke(args) {
249
259
  // Fall back to the raw mention if Slack history is unavailable.
250
260
  }
251
261
  }
262
+ // Remember the thread came from Slack, so replies typed in OpenBot still go to Behalf.
263
+ await args.storage
264
+ ?.patchThreadState({
265
+ channelId,
266
+ threadId,
267
+ state: { [SLACK_THREAD_STATE_KEY]: { channel: slackChannelId, threadTs: threadId } },
268
+ })
269
+ .catch(() => undefined);
252
270
  try {
253
271
  for await (const output of bridgeSystemAgentRun({
254
272
  host: args.host,
@@ -259,7 +277,13 @@ export async function* handleSlackInvoke(args) {
259
277
  publicBaseUrl: args.publicBaseUrl,
260
278
  })) {
261
279
  yield output;
262
- await reply(output);
280
+ if (output.type === "agent:output")
281
+ await reply(output);
282
+ else {
283
+ const notice = slackNeedsInputNotice(output);
284
+ if (notice)
285
+ await postToSlack(notice);
286
+ }
263
287
  }
264
288
  }
265
289
  catch (error) {
@@ -302,6 +326,38 @@ export async function* handleSlackInvoke(args) {
302
326
  });
303
327
  return;
304
328
  }
329
+ // A reply typed in OpenBot into a thread that started in Slack is for Behalf, not for the
330
+ // Slack specialist, which only has Slack tools.
331
+ const metaChannelId = args.event.meta?.channelId;
332
+ const channelId = typeof metaChannelId === "string" ? metaChannelId : undefined;
333
+ if (args.host?.runAgent && channelId && args.storage) {
334
+ const details = await args.storage.getThreadDetails({ channelId, threadId }).catch(() => null);
335
+ const state = details?.state;
336
+ if (state?.[SLACK_THREAD_STATE_KEY]) {
337
+ try {
338
+ for await (const output of bridgeSystemAgentRun({
339
+ host: args.host,
340
+ channelId,
341
+ threadId,
342
+ userMessage,
343
+ meta: args.event.meta,
344
+ publicBaseUrl: args.publicBaseUrl,
345
+ })) {
346
+ yield output;
347
+ }
348
+ }
349
+ catch (error) {
350
+ const message = error instanceof Error ? error.message : String(error);
351
+ yield agentOutput({
352
+ agentId: ROUTING_AGENT_ID,
353
+ content: `Agent error: ${message}`,
354
+ threadId,
355
+ meta: args.event.meta,
356
+ });
357
+ }
358
+ return;
359
+ }
360
+ }
305
361
  const model = resolveSlackModel(args.config);
306
362
  let provider;
307
363
  try {
@@ -0,0 +1,24 @@
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
+ /**
8
+ * What to tell the Slack thread when Behalf stops to ask for something (approval, a question,
9
+ * a connection to set up). The card itself only exists in OpenBot, so without this the Slack
10
+ * thread would go quiet. Undefined for anything that isn't a new open card.
11
+ */
12
+ export function slackNeedsInputNotice(event) {
13
+ if (event.type !== "client:ui:widget")
14
+ return undefined;
15
+ const widget = event.data;
16
+ if (widget.state && widget.state !== "open")
17
+ return undefined;
18
+ const hasInput = (Array.isArray(widget.actions) && widget.actions.length > 0) ||
19
+ ("fields" in widget && Array.isArray(widget.fields) && widget.fields.length > 0);
20
+ if (!hasInput)
21
+ return undefined;
22
+ const title = widget.title?.trim();
23
+ return `I need your input to continue${title ? `: ${title}` : ""}. Open this conversation in OpenBot to answer, and I'll carry on from there.`;
24
+ }
@@ -0,0 +1,32 @@
1
+ /** The reaction that tells a Slack user the bot saw their message and is working on it. */
2
+ export const SLACK_WORKING_REACTION = "eyes";
3
+ /** Slack errors that mean the reaction is already where we want it, or can't matter. */
4
+ const HARMLESS_REACTION_ERRORS = new Set(["already_reacted", "message_not_found"]);
5
+ /**
6
+ * Adds a reaction to a message. Never throws: a missing reaction must not hold up or fail
7
+ * the answer, so failures are logged and dropped.
8
+ */
9
+ export async function addSlackReaction(args) {
10
+ const doFetch = args.fetchImpl ?? fetch;
11
+ try {
12
+ const res = await doFetch("https://slack.com/api/reactions.add", {
13
+ method: "POST",
14
+ headers: {
15
+ Authorization: `Bearer ${args.token}`,
16
+ "Content-Type": "application/json",
17
+ },
18
+ body: JSON.stringify({
19
+ channel: args.channel,
20
+ timestamp: args.timestamp,
21
+ name: args.name ?? SLACK_WORKING_REACTION,
22
+ }),
23
+ });
24
+ const body = (await res.json());
25
+ if (!body.ok && !HARMLESS_REACTION_ERRORS.has(body.error ?? "")) {
26
+ console.warn("[slack] could not add reaction", body.error ?? res.status);
27
+ }
28
+ }
29
+ catch (error) {
30
+ console.warn("[slack] could not add reaction", error);
31
+ }
32
+ }
package/dist/webhook.js CHANGED
@@ -95,6 +95,9 @@ export async function* handleSlackWebhook(args) {
95
95
  yield webhookHttpResponse({ status: 200, body: {} });
96
96
  return;
97
97
  }
98
+ if (slackEvent.channel && slackEvent.ts) {
99
+ args.acknowledge?.({ channel: slackEvent.channel, ts: slackEvent.ts });
100
+ }
98
101
  args.ctx.state.threadId = threadId;
99
102
  const slackMeta = {
100
103
  teamId: payload.team_id,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@meetopenbot/slack",
3
- "version": "1.5.0",
3
+ "version": "1.6.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",