@meetopenbot/slack 1.4.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/README.md +30 -5
- package/dist/bindings.js +53 -0
- package/dist/config.js +5 -26
- package/dist/index.js +13 -0
- package/dist/invoke.js +189 -41
- package/dist/needs-input.js +24 -0
- package/dist/post.js +9 -0
- package/dist/reactions.js +32 -0
- package/dist/routing.js +160 -0
- package/dist/webhook.js +10 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -30,23 +30,48 @@ 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
|
|
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
|
|
47
|
-
- **Right side
|
|
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
|
-
|
|
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
|
|
package/dist/bindings.js
ADDED
|
@@ -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
|
-
|
|
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,37 +18,15 @@ export const pluginConfigSchema = {
|
|
|
17
18
|
},
|
|
18
19
|
channelMappings: {
|
|
19
20
|
type: "string",
|
|
20
|
-
description: "Inbound —
|
|
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
|
}
|
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",
|
|
@@ -31,6 +32,17 @@ export const plugin = definePlugin({
|
|
|
31
32
|
const state = details?.state;
|
|
32
33
|
return !!state && typeof state === "object" && Object.keys(state).length > 0;
|
|
33
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
|
+
},
|
|
34
46
|
});
|
|
35
47
|
},
|
|
36
48
|
async *run({ event, handlerCtx, context }) {
|
|
@@ -42,6 +54,7 @@ export const plugin = definePlugin({
|
|
|
42
54
|
config: slackConfig,
|
|
43
55
|
credentials: slackCredentials(context),
|
|
44
56
|
host: context.host,
|
|
57
|
+
storage: context.storage,
|
|
45
58
|
publicBaseUrl: context.publicBaseUrl,
|
|
46
59
|
});
|
|
47
60
|
},
|
package/dist/invoke.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
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 {
|
|
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";
|
|
9
|
+
import { isInteractionEvent, slackNeedsInputNotice, SLACK_THREAD_STATE_KEY, } from "./needs-input.js";
|
|
7
10
|
import { getSlackThreadMeta, isSlackWebhookIngress } from "./webhook.js";
|
|
8
11
|
/**
|
|
9
12
|
* The host connects Slack before `run`. A run without credentials means the host is too
|
|
@@ -13,6 +16,10 @@ export const SLACK_NEEDS_NEWER_RUNTIME = "Slack needs a newer OpenBot runtime to
|
|
|
13
16
|
async function* bridgeSystemAgentRun(args) {
|
|
14
17
|
const runId = `slack_${randomUUID()}`;
|
|
15
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
|
+
: {};
|
|
16
23
|
const eventQueue = [];
|
|
17
24
|
let resolveNext = null;
|
|
18
25
|
let isFinished = false;
|
|
@@ -32,8 +39,7 @@ async function* bridgeSystemAgentRun(args) {
|
|
|
32
39
|
meta: {
|
|
33
40
|
channelId: args.channelId,
|
|
34
41
|
threadId: args.threadId,
|
|
35
|
-
|
|
36
|
-
slack: slackMeta,
|
|
42
|
+
...slackOrigin,
|
|
37
43
|
userName: SLACK_USER_DISPLAY_NAME,
|
|
38
44
|
...(typeof args.meta?.userId === "string" ? { userId: args.meta.userId } : {}),
|
|
39
45
|
},
|
|
@@ -47,11 +53,18 @@ async function* bridgeSystemAgentRun(args) {
|
|
|
47
53
|
...output.meta,
|
|
48
54
|
agentId: ROUTING_AGENT_ID,
|
|
49
55
|
threadId: args.threadId,
|
|
50
|
-
|
|
51
|
-
slack: slackMeta,
|
|
56
|
+
...slackOrigin,
|
|
52
57
|
},
|
|
53
58
|
});
|
|
54
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
|
+
}
|
|
55
68
|
if (resolveNext) {
|
|
56
69
|
resolveNext();
|
|
57
70
|
resolveNext = null;
|
|
@@ -66,8 +79,7 @@ async function* bridgeSystemAgentRun(args) {
|
|
|
66
79
|
meta: {
|
|
67
80
|
agentId: ROUTING_AGENT_ID,
|
|
68
81
|
threadId: args.threadId,
|
|
69
|
-
|
|
70
|
-
slack: slackMeta,
|
|
82
|
+
...slackOrigin,
|
|
71
83
|
},
|
|
72
84
|
});
|
|
73
85
|
})
|
|
@@ -90,6 +102,41 @@ async function* bridgeSystemAgentRun(args) {
|
|
|
90
102
|
}
|
|
91
103
|
await runPromise;
|
|
92
104
|
}
|
|
105
|
+
/**
|
|
106
|
+
* The bot's answer to "use #space here", or undefined when the message isn't that command
|
|
107
|
+
* after all (a bare word that names no Space, like "use pnpm here"). Never creates a Space.
|
|
108
|
+
*/
|
|
109
|
+
async function answerUseSpaceCommand(args) {
|
|
110
|
+
if (!args.command.ref)
|
|
111
|
+
return ROUTING_UNNAMED_CHANNEL;
|
|
112
|
+
const spaces = (await args.storage.getChannels()).map(({ id, name }) => ({ id, name }));
|
|
113
|
+
const found = findSpace(args.command.ref, spaces);
|
|
114
|
+
if (!args.command.explicit && found.kind !== "found")
|
|
115
|
+
return undefined;
|
|
116
|
+
if (!args.slackUserId)
|
|
117
|
+
return ROUTING_FORBIDDEN;
|
|
118
|
+
try {
|
|
119
|
+
const user = await fetchSlackUserFlags({
|
|
120
|
+
token: args.credentials.botToken,
|
|
121
|
+
userId: args.slackUserId,
|
|
122
|
+
});
|
|
123
|
+
if (!canRouteSlackChannel(user, args.credentials.teamId))
|
|
124
|
+
return ROUTING_FORBIDDEN;
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
return ROUTING_FORBIDDEN;
|
|
128
|
+
}
|
|
129
|
+
if (found.kind === "missing")
|
|
130
|
+
return missingSpaceMessage(args.command.ref, spaces);
|
|
131
|
+
if (found.kind === "ambiguous")
|
|
132
|
+
return ambiguousSpaceMessage(args.command.ref, found.spaces);
|
|
133
|
+
await updateSlackPluginConfig({
|
|
134
|
+
storage: args.storage,
|
|
135
|
+
agentId: args.agentId,
|
|
136
|
+
update: (config) => withChannelBinding(config, args.slackChannelId, found.space.id),
|
|
137
|
+
});
|
|
138
|
+
return boundMessage(found.space);
|
|
139
|
+
}
|
|
93
140
|
export async function* handleSlackInvoke(args) {
|
|
94
141
|
const fromWebhook = isSlackWebhookIngress(args.event.meta);
|
|
95
142
|
if (!shouldHandleInvoke(args.event, args.agentId))
|
|
@@ -132,9 +179,69 @@ export async function* handleSlackInvoke(args) {
|
|
|
132
179
|
return;
|
|
133
180
|
}
|
|
134
181
|
const slackMeta = getSlackThreadMeta(args.event.meta);
|
|
135
|
-
const
|
|
136
|
-
|
|
137
|
-
|
|
182
|
+
const slackChannelId = slackMeta?.channel;
|
|
183
|
+
const postToSlack = async (text) => {
|
|
184
|
+
if (!slackChannelId || !text.trim())
|
|
185
|
+
return;
|
|
186
|
+
try {
|
|
187
|
+
await postSlackMessage({
|
|
188
|
+
token: credentials.botToken,
|
|
189
|
+
channel: slackChannelId,
|
|
190
|
+
text,
|
|
191
|
+
threadTs: slackMeta?.threadTs ?? slackMeta?.ts,
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
catch (error) {
|
|
195
|
+
console.warn("[slack] could not post reply", {
|
|
196
|
+
channel: slackChannelId,
|
|
197
|
+
error: error instanceof Error ? error.message : String(error),
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
// Each reply shows in the OpenBot thread and is posted to the Slack thread it answers.
|
|
202
|
+
const reply = (output) => postToSlack(output.data.content ?? "");
|
|
203
|
+
const botOutput = (content) => ({
|
|
204
|
+
type: "agent:output",
|
|
205
|
+
data: { content },
|
|
206
|
+
meta: {
|
|
207
|
+
agentId: ROUTING_AGENT_ID,
|
|
208
|
+
threadId,
|
|
209
|
+
source: "slack",
|
|
210
|
+
slack: slackMeta,
|
|
211
|
+
},
|
|
212
|
+
});
|
|
213
|
+
const command = slackChannelId ? parseUseSpaceCommand(userMessage) : undefined;
|
|
214
|
+
if (command && slackChannelId && args.storage) {
|
|
215
|
+
let answer;
|
|
216
|
+
try {
|
|
217
|
+
answer = await answerUseSpaceCommand({
|
|
218
|
+
command,
|
|
219
|
+
storage: args.storage,
|
|
220
|
+
agentId: args.agentId,
|
|
221
|
+
slackChannelId,
|
|
222
|
+
slackUserId: slackMeta?.user,
|
|
223
|
+
credentials,
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
catch (error) {
|
|
227
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
228
|
+
answer = `I couldn't change this channel's Space: ${message}`;
|
|
229
|
+
}
|
|
230
|
+
if (answer !== undefined) {
|
|
231
|
+
const output = botOutput(answer);
|
|
232
|
+
yield output;
|
|
233
|
+
await reply(output);
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
const route = slackChannelId
|
|
238
|
+
? await resolveSlackSpace({
|
|
239
|
+
slackChannelId,
|
|
240
|
+
config: args.config,
|
|
241
|
+
storage: args.storage,
|
|
242
|
+
})
|
|
243
|
+
: undefined;
|
|
244
|
+
const channelId = route?.spaceId ?? args.ctx.state.channelId;
|
|
138
245
|
if (!channelId)
|
|
139
246
|
return;
|
|
140
247
|
let prompt = userMessage;
|
|
@@ -152,25 +259,14 @@ export async function* handleSlackInvoke(args) {
|
|
|
152
259
|
// Fall back to the raw mention if Slack history is unavailable.
|
|
153
260
|
}
|
|
154
261
|
}
|
|
155
|
-
//
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
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
|
-
};
|
|
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);
|
|
174
270
|
try {
|
|
175
271
|
for await (const output of bridgeSystemAgentRun({
|
|
176
272
|
host: args.host,
|
|
@@ -181,24 +277,44 @@ export async function* handleSlackInvoke(args) {
|
|
|
181
277
|
publicBaseUrl: args.publicBaseUrl,
|
|
182
278
|
})) {
|
|
183
279
|
yield output;
|
|
184
|
-
|
|
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
|
+
}
|
|
185
287
|
}
|
|
186
288
|
}
|
|
187
289
|
catch (error) {
|
|
188
290
|
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
|
-
};
|
|
291
|
+
const output = botOutput(`Slack agent error: ${message}`);
|
|
199
292
|
yield output;
|
|
200
293
|
await reply(output);
|
|
201
294
|
}
|
|
295
|
+
// The first message from a channel with no binding or mapping says how to pick a Space.
|
|
296
|
+
// It's marked first, so a failed save never turns into a hint on every message, and
|
|
297
|
+
// two messages at once post it once.
|
|
298
|
+
if (route?.source === "default" &&
|
|
299
|
+
slackChannelId &&
|
|
300
|
+
args.storage &&
|
|
301
|
+
!(args.config.routingHintsShown ?? []).includes(slackChannelId)) {
|
|
302
|
+
try {
|
|
303
|
+
const marked = await updateSlackPluginConfig({
|
|
304
|
+
storage: args.storage,
|
|
305
|
+
agentId: args.agentId,
|
|
306
|
+
update: (config) => withHintedChannel(config, slackChannelId),
|
|
307
|
+
});
|
|
308
|
+
if (marked)
|
|
309
|
+
await postToSlack(ROUTING_HINT);
|
|
310
|
+
}
|
|
311
|
+
catch (error) {
|
|
312
|
+
console.warn("[slack] could not save the routing hint", {
|
|
313
|
+
channel: slackChannelId,
|
|
314
|
+
error: error instanceof Error ? error.message : String(error),
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
}
|
|
202
318
|
return;
|
|
203
319
|
}
|
|
204
320
|
if (!credentials) {
|
|
@@ -210,6 +326,38 @@ export async function* handleSlackInvoke(args) {
|
|
|
210
326
|
});
|
|
211
327
|
return;
|
|
212
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
|
+
}
|
|
213
361
|
const model = resolveSlackModel(args.config);
|
|
214
362
|
let provider;
|
|
215
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
|
+
}
|
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,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/routing.js
ADDED
|
@@ -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,6 @@
|
|
|
1
1
|
import { decodeWebhookRawBody, getWebhookHeader, webhookHttpResponse, } from "@meetopenbot/plugin-sdk";
|
|
2
|
-
import {
|
|
2
|
+
import { resolveSlackSpace } from "./bindings.js";
|
|
3
|
+
import { DEFAULT_OPENBOT_CHANNEL_ID, SLACK_USER_DISPLAY_NAME, resolveSlackSigningSecret, } from "./config.js";
|
|
3
4
|
import { slackMessageKind } from "./message-kind.js";
|
|
4
5
|
import { verifySlackSignature } from "./verify.js";
|
|
5
6
|
const seenSlackEvents = new Map();
|
|
@@ -72,7 +73,11 @@ export async function* handleSlackWebhook(args) {
|
|
|
72
73
|
return;
|
|
73
74
|
}
|
|
74
75
|
const openBotChannelId = slackEvent.channel
|
|
75
|
-
?
|
|
76
|
+
? (await resolveSlackSpace({
|
|
77
|
+
slackChannelId: slackEvent.channel,
|
|
78
|
+
config: args.config,
|
|
79
|
+
storage: args.storage,
|
|
80
|
+
})).spaceId
|
|
76
81
|
: DEFAULT_OPENBOT_CHANNEL_ID;
|
|
77
82
|
if (kind === "threadReply" &&
|
|
78
83
|
!(await args.hasThread(openBotChannelId, slackEvent.thread_ts))) {
|
|
@@ -90,6 +95,9 @@ export async function* handleSlackWebhook(args) {
|
|
|
90
95
|
yield webhookHttpResponse({ status: 200, body: {} });
|
|
91
96
|
return;
|
|
92
97
|
}
|
|
98
|
+
if (slackEvent.channel && slackEvent.ts) {
|
|
99
|
+
args.acknowledge?.({ channel: slackEvent.channel, ts: slackEvent.ts });
|
|
100
|
+
}
|
|
93
101
|
args.ctx.state.threadId = threadId;
|
|
94
102
|
const slackMeta = {
|
|
95
103
|
teamId: payload.team_id,
|