-
-
Notifications
You must be signed in to change notification settings - Fork 80.9k
Expand file tree
/
Copy pathindex.ts
More file actions
228 lines (207 loc) · 7.93 KB
/
Copy pathindex.ts
File metadata and controls
228 lines (207 loc) · 7.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// Thread Ownership plugin entrypoint registers its OpenClaw integration.
import { resolveLivePluginConfigObject } from "openclaw/plugin-sdk/plugin-config-runtime";
import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
import { escapeRegExp } from "openclaw/plugin-sdk/text-utility-runtime";
import {
definePluginEntry,
fetchWithSsrFGuard,
readProviderJsonResponse,
ssrfPolicyFromDangerouslyAllowPrivateNetwork,
type OpenClawConfig,
type OpenClawPluginApi,
} from "./api.js";
const THREAD_OWNERSHIP_CONFLICT_BODY_LIMIT_BYTES = 64 * 1024;
type ThreadOwnershipConfig = {
forwarderUrl?: string;
abTestChannels?: string[];
};
type AgentEntry = NonNullable<NonNullable<OpenClawConfig["agents"]>["list"]>[number];
type ThreadOwnershipMessageSendingResult = { cancel: true } | undefined;
// In-memory set of {channel}:{thread} keys where this agent was @-mentioned.
// Entries expire after 5 minutes.
const mentionedThreads = new Map<string, number>();
const MENTION_TTL_MS = 5 * 60 * 1000;
function isThreadOwnershipConfig(value: unknown): value is ThreadOwnershipConfig {
return value !== null && typeof value === "object";
}
function resolveThreadToken(value: unknown): string {
return typeof value === "string" || typeof value === "number" ? String(value) : "";
}
function resolveSlackConversationId(value: unknown): string {
const raw = normalizeOptionalString(value) ?? "";
if (!raw) {
return "";
}
const trimmed = raw.trim();
const match = /^(?:slack:)?channel:(.+)$/i.exec(trimmed);
const resolved = match?.[1]?.trim() || trimmed;
return /^[CDGUW][A-Z0-9]+$/i.test(resolved) ? resolved.toUpperCase() : resolved;
}
function cleanExpiredMentions(): void {
const now = Date.now();
for (const [key, ts] of mentionedThreads) {
if (now - ts > MENTION_TTL_MS) {
mentionedThreads.delete(key);
}
}
}
function containsAgentNameMention(text: string, agentName: string): boolean {
const trimmedName = agentName.trim();
if (!trimmedName) {
return false;
}
return new RegExp(`(^|[^\\w])@${escapeRegExp(trimmedName)}(?=$|[^\\w])`, "i").test(text);
}
function resolveOwnershipAgent(config: OpenClawConfig): { id: string; name: string } {
const list = Array.isArray(config.agents?.list)
? config.agents.list.filter(
(entry): entry is AgentEntry => entry !== null && typeof entry === "object",
)
: [];
const selected = list.find((entry) => entry.default === true) ?? list[0];
const id = normalizeOptionalString(selected?.id) ?? "unknown";
const identityName = normalizeOptionalString(selected?.identity?.name) ?? "";
const fallbackName = normalizeOptionalString(selected?.name) ?? "";
const name = identityName || fallbackName;
return { id, name };
}
export default definePluginEntry({
id: "thread-ownership",
name: "Thread Ownership",
description: "Slack thread claim coordination for multi-agent setups",
register(api: OpenClawPluginApi) {
const resolveCurrentState = () => {
const currentConfig = (api.runtime.config?.current?.() ?? api.config) as OpenClawConfig;
const livePluginCfg = resolveLivePluginConfigObject(
api.runtime.config?.current
? () => api.runtime.config.current() as OpenClawConfig
: undefined,
"thread-ownership",
isThreadOwnershipConfig(api.pluginConfig)
? (api.pluginConfig as Record<string, unknown>)
: undefined,
);
const pluginCfg = isThreadOwnershipConfig(livePluginCfg) ? livePluginCfg : {};
return {
currentConfig,
forwarderUrl: (
pluginCfg.forwarderUrl ??
process.env.SLACK_FORWARDER_URL ??
"http://slack-forwarder:8750"
).replace(/\/$/, ""),
abTestChannels: new Set(
(
pluginCfg.abTestChannels ??
process.env.THREAD_OWNERSHIP_CHANNELS?.split(",").filter(Boolean) ??
[]
)
.map((entry) => resolveSlackConversationId(entry))
.filter(Boolean),
),
botUserId: process.env.SLACK_BOT_USER_ID ?? "",
agent: resolveOwnershipAgent(currentConfig),
};
};
api.on("message_received", async (event, ctx) => {
if (ctx.channelId !== "slack") {
return;
}
const { agent, botUserId } = resolveCurrentState();
const text = event.content ?? "";
const threadTs =
resolveThreadToken(event.threadId) ||
resolveThreadToken(event.metadata?.threadId) ||
resolveThreadToken(event.metadata?.threadTs);
const channelId =
resolveSlackConversationId(ctx.conversationId) ||
resolveSlackConversationId(event.metadata?.channelId) ||
"";
if (!threadTs || !channelId) {
return;
}
const mentioned =
containsAgentNameMention(text, agent.name) ||
(botUserId && text.includes(`<@${botUserId}>`));
if (mentioned) {
cleanExpiredMentions();
mentionedThreads.set(`${channelId}:${threadTs}`, Date.now());
}
});
api.on("message_sending", async (event, ctx): Promise<ThreadOwnershipMessageSendingResult> => {
if (ctx.channelId !== "slack") {
return undefined;
}
const { abTestChannels, agent, forwarderUrl } = resolveCurrentState();
const threadTs =
resolveThreadToken(event.replyToId) ||
resolveThreadToken(event.threadId) ||
resolveThreadToken(event.metadata?.threadId) ||
resolveThreadToken(event.metadata?.threadTs);
const channelId =
resolveSlackConversationId(ctx.conversationId) ||
resolveSlackConversationId(event.metadata?.channelId) ||
resolveSlackConversationId(event.to) ||
"";
if (!threadTs || !channelId) {
return undefined;
}
if (abTestChannels.size > 0 && !abTestChannels.has(channelId)) {
return undefined;
}
cleanExpiredMentions();
if (mentionedThreads.has(`${channelId}:${threadTs}`)) {
return undefined;
}
try {
// The forwarder is an internal service (e.g. a Docker container); allow private-network
// access but pin DNS so DNS-rebinding attacks cannot pivot to a different internal host.
const { response: resp, release } = await fetchWithSsrFGuard({
url: `${forwarderUrl}/api/v1/ownership/${channelId}/${threadTs}`,
init: {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ agent_id: agent.id }),
},
timeoutMs: 3000,
policy: ssrfPolicyFromDangerouslyAllowPrivateNetwork(true),
auditContext: "thread-ownership",
});
try {
if (resp.ok) {
return undefined;
}
if (resp.status === 409) {
let owner = "unknown";
try {
const body = await readProviderJsonResponse<{ owner?: unknown }>(
resp,
"thread-ownership forwarder conflict",
{ maxBytes: THREAD_OWNERSHIP_CONFLICT_BODY_LIMIT_BYTES },
);
if (typeof body.owner === "string" && body.owner) {
owner = body.owner;
}
} catch (error) {
// A 409 is authoritative even when its body is malformed or oversized.
api.logger.warn?.(
`thread-ownership: conflict body unreadable (${String(error)}), cancelling send`,
);
}
api.logger.info?.(
`thread-ownership: cancelled send to ${channelId}:${threadTs} — owned by ${owner}`,
);
return { cancel: true };
}
api.logger.warn?.(`thread-ownership: unexpected status ${resp.status}, allowing send`);
} finally {
await release();
}
} catch (err) {
api.logger.warn?.(
`thread-ownership: ownership check failed (${String(err)}), allowing send`,
);
}
return undefined;
});
},
});