Vendor OpenClaw source as Adolf fork baseline
Some checks failed
ClawSweeper Dispatch / dispatch (push) Has been cancelled
CodeQL / Security High (actions) (push) Has been cancelled
CodeQL / Security High (channel-runtime-boundary) (push) Has been cancelled
CodeQL / Security High (core-auth-secrets) (push) Has been cancelled
CodeQL / Security High (mcp-process-tool-boundary) (push) Has been cancelled
CodeQL / Security High (network-ssrf-boundary) (push) Has been cancelled
CodeQL / Security High (plugin-trust-boundary) (push) Has been cancelled
CodeQL / Security High (process-exec-boundary) (push) Has been cancelled
Docs Sync Publish Repo / sync-publish-repo (push) Has been cancelled
Docs / docs (push) Has been cancelled
OpenClaw Stable Main Closeout / Resolve stable release closeout inputs (push) Has been cancelled
OpenClaw Stable Main Closeout / Verify stable main closeout (push) Has been cancelled
Workflow Sanity / no-tabs (push) Has been cancelled
Workflow Sanity / actionlint (push) Has been cancelled
Workflow Sanity / generated-doc-baselines (push) Has been cancelled
CI / runner-admission (push) Has been cancelled
CI / preflight (push) Has been cancelled
CI / security-fast (push) Has been cancelled
CI / pnpm-store-warmup (push) Has been cancelled
CI / build-artifacts (push) Has been cancelled
CI / native-i18n (push) Has been cancelled
CI / ${{ matrix.check_name }} (push) Has been cancelled
CI / ${{ matrix.checkName }} (push) Has been cancelled
CI / checks-node-compat-node22 (push) Has been cancelled
CI / check-bundled-channel-config-metadata (push) Has been cancelled
CI / check-dependencies (push) Has been cancelled
CI / check-guards (push) Has been cancelled
CI / check-lint (push) Has been cancelled
CI / check-prod-types (push) Has been cancelled
CI / check-shrinkwrap (push) Has been cancelled
CI / check-test-types (push) Has been cancelled
CI / check-additional-boundaries-a (push) Has been cancelled
CI / check-additional-boundaries-bcd (push) Has been cancelled
CI / check-additional-extension-bundled (push) Has been cancelled
CI / check-additional-extension-channels (push) Has been cancelled
CI / check-additional-extension-package-boundary (push) Has been cancelled
CI / check-additional-runtime-topology-architecture (push) Has been cancelled
CI / check-session-accessor-boundary (push) Has been cancelled
CI / check-session-transcript-reader-boundary (push) Has been cancelled
CI / check-docs (push) Has been cancelled
CI / skills-python (push) Has been cancelled
CI / macos-swift (push) Has been cancelled
CI / ios-build (push) Has been cancelled
CI / ci-timings-summary (push) Has been cancelled
Native App Locale Refresh / Refresh native fa (push) Has been cancelled
Native App Locale Refresh / Refresh native fr (push) Has been cancelled
Native App Locale Refresh / Refresh native hi (push) Has been cancelled
Native App Locale Refresh / Refresh native id (push) Has been cancelled
Native App Locale Refresh / Refresh native it (push) Has been cancelled
Native App Locale Refresh / Refresh native ja-JP (push) Has been cancelled
Control UI Locale Refresh / plan (push) Has been cancelled
Control UI Locale Refresh / Refresh ${{ matrix.locale }} (push) Has been cancelled
Control UI Locale Refresh / Commit control UI locale refresh (push) Has been cancelled
Live Media Runner Image / Build live media runner image (push) Has been cancelled
Native App Locale Refresh / Refresh native ar (push) Has been cancelled
Native App Locale Refresh / Refresh native de (push) Has been cancelled
Native App Locale Refresh / Refresh native es (push) Has been cancelled
Native App Locale Refresh / Refresh native ko (push) Has been cancelled
Native App Locale Refresh / Refresh native nl (push) Has been cancelled
Native App Locale Refresh / Refresh native pl (push) Has been cancelled
Native App Locale Refresh / Refresh native pt-BR (push) Has been cancelled
Native App Locale Refresh / Refresh native ru (push) Has been cancelled
Native App Locale Refresh / Refresh native sv (push) Has been cancelled
Native App Locale Refresh / Refresh native th (push) Has been cancelled
Native App Locale Refresh / Refresh native tr (push) Has been cancelled
Native App Locale Refresh / Refresh native uk (push) Has been cancelled
Native App Locale Refresh / Refresh native vi (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-CN (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-TW (push) Has been cancelled
Native App Locale Refresh / Commit native locale refresh (push) Has been cancelled
Plugin Init Scaffold Validation / Validate provider scaffold (push) Has been cancelled
Plugin NPM Release / preview_plugins_npm (push) Has been cancelled
Plugin NPM Release / Validate release publish approval (push) Has been cancelled
Plugin NPM Release / preview_plugin_pack (push) Has been cancelled
Plugin NPM Release / publish_plugins_npm (push) Has been cancelled
Sandbox Common Smoke / sandbox-common-smoke (push) Has been cancelled
Website Installer Sync / static (push) Has been cancelled
Website Installer Sync / linux-docker (push) Has been cancelled
Website Installer Sync / macos-installer (push) Has been cancelled
Website Installer Sync / windows-installer (push) Has been cancelled
Website Installer Sync / sync-website (push) Has been cancelled
Some checks failed
ClawSweeper Dispatch / dispatch (push) Has been cancelled
CodeQL / Security High (actions) (push) Has been cancelled
CodeQL / Security High (channel-runtime-boundary) (push) Has been cancelled
CodeQL / Security High (core-auth-secrets) (push) Has been cancelled
CodeQL / Security High (mcp-process-tool-boundary) (push) Has been cancelled
CodeQL / Security High (network-ssrf-boundary) (push) Has been cancelled
CodeQL / Security High (plugin-trust-boundary) (push) Has been cancelled
CodeQL / Security High (process-exec-boundary) (push) Has been cancelled
Docs Sync Publish Repo / sync-publish-repo (push) Has been cancelled
Docs / docs (push) Has been cancelled
OpenClaw Stable Main Closeout / Resolve stable release closeout inputs (push) Has been cancelled
OpenClaw Stable Main Closeout / Verify stable main closeout (push) Has been cancelled
Workflow Sanity / no-tabs (push) Has been cancelled
Workflow Sanity / actionlint (push) Has been cancelled
Workflow Sanity / generated-doc-baselines (push) Has been cancelled
CI / runner-admission (push) Has been cancelled
CI / preflight (push) Has been cancelled
CI / security-fast (push) Has been cancelled
CI / pnpm-store-warmup (push) Has been cancelled
CI / build-artifacts (push) Has been cancelled
CI / native-i18n (push) Has been cancelled
CI / ${{ matrix.check_name }} (push) Has been cancelled
CI / ${{ matrix.checkName }} (push) Has been cancelled
CI / checks-node-compat-node22 (push) Has been cancelled
CI / check-bundled-channel-config-metadata (push) Has been cancelled
CI / check-dependencies (push) Has been cancelled
CI / check-guards (push) Has been cancelled
CI / check-lint (push) Has been cancelled
CI / check-prod-types (push) Has been cancelled
CI / check-shrinkwrap (push) Has been cancelled
CI / check-test-types (push) Has been cancelled
CI / check-additional-boundaries-a (push) Has been cancelled
CI / check-additional-boundaries-bcd (push) Has been cancelled
CI / check-additional-extension-bundled (push) Has been cancelled
CI / check-additional-extension-channels (push) Has been cancelled
CI / check-additional-extension-package-boundary (push) Has been cancelled
CI / check-additional-runtime-topology-architecture (push) Has been cancelled
CI / check-session-accessor-boundary (push) Has been cancelled
CI / check-session-transcript-reader-boundary (push) Has been cancelled
CI / check-docs (push) Has been cancelled
CI / skills-python (push) Has been cancelled
CI / macos-swift (push) Has been cancelled
CI / ios-build (push) Has been cancelled
CI / ci-timings-summary (push) Has been cancelled
Native App Locale Refresh / Refresh native fa (push) Has been cancelled
Native App Locale Refresh / Refresh native fr (push) Has been cancelled
Native App Locale Refresh / Refresh native hi (push) Has been cancelled
Native App Locale Refresh / Refresh native id (push) Has been cancelled
Native App Locale Refresh / Refresh native it (push) Has been cancelled
Native App Locale Refresh / Refresh native ja-JP (push) Has been cancelled
Control UI Locale Refresh / plan (push) Has been cancelled
Control UI Locale Refresh / Refresh ${{ matrix.locale }} (push) Has been cancelled
Control UI Locale Refresh / Commit control UI locale refresh (push) Has been cancelled
Live Media Runner Image / Build live media runner image (push) Has been cancelled
Native App Locale Refresh / Refresh native ar (push) Has been cancelled
Native App Locale Refresh / Refresh native de (push) Has been cancelled
Native App Locale Refresh / Refresh native es (push) Has been cancelled
Native App Locale Refresh / Refresh native ko (push) Has been cancelled
Native App Locale Refresh / Refresh native nl (push) Has been cancelled
Native App Locale Refresh / Refresh native pl (push) Has been cancelled
Native App Locale Refresh / Refresh native pt-BR (push) Has been cancelled
Native App Locale Refresh / Refresh native ru (push) Has been cancelled
Native App Locale Refresh / Refresh native sv (push) Has been cancelled
Native App Locale Refresh / Refresh native th (push) Has been cancelled
Native App Locale Refresh / Refresh native tr (push) Has been cancelled
Native App Locale Refresh / Refresh native uk (push) Has been cancelled
Native App Locale Refresh / Refresh native vi (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-CN (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-TW (push) Has been cancelled
Native App Locale Refresh / Commit native locale refresh (push) Has been cancelled
Plugin Init Scaffold Validation / Validate provider scaffold (push) Has been cancelled
Plugin NPM Release / preview_plugins_npm (push) Has been cancelled
Plugin NPM Release / Validate release publish approval (push) Has been cancelled
Plugin NPM Release / preview_plugin_pack (push) Has been cancelled
Plugin NPM Release / publish_plugins_npm (push) Has been cancelled
Sandbox Common Smoke / sandbox-common-smoke (push) Has been cancelled
Website Installer Sync / static (push) Has been cancelled
Website Installer Sync / linux-docker (push) Has been cancelled
Website Installer Sync / macos-installer (push) Has been cancelled
Website Installer Sync / windows-installer (push) Has been cancelled
Website Installer Sync / sync-website (push) Has been cancelled
Adolf is a fork/vendored clone of github.com/openclaw/openclaw (v2026.6.11), free to diverge. Tree copied sans upstream .git; upstream remote added for future syncs. Node pinned to 24 (.nvmrc); engines already require >=22.19. Preserves docs/ARCHITECTURE.md. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LeqyaxJF2nbRXJtae2kNB2
This commit is contained in:
7
extensions/thread-ownership/api.ts
Normal file
7
extensions/thread-ownership/api.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
// Thread Ownership API module exposes the plugin public contract.
|
||||
export type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
|
||||
export { definePluginEntry, type OpenClawPluginApi } from "openclaw/plugin-sdk/plugin-entry";
|
||||
export {
|
||||
fetchWithSsrFGuard,
|
||||
ssrfPolicyFromDangerouslyAllowPrivateNetwork,
|
||||
} from "openclaw/plugin-sdk/ssrf-runtime";
|
||||
506
extensions/thread-ownership/index.test.ts
Normal file
506
extensions/thread-ownership/index.test.ts
Normal file
@@ -0,0 +1,506 @@
|
||||
// Thread Ownership tests cover index plugin behavior.
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { OpenClawPluginApi } from "./api.js";
|
||||
import register from "./index.js";
|
||||
|
||||
describe("thread-ownership plugin", () => {
|
||||
const hooks: Record<string, Function> = {};
|
||||
const fetchMock = vi.fn() as unknown as typeof globalThis.fetch;
|
||||
let configFile: Record<string, unknown> = {};
|
||||
const originalSlackForwarderUrl = process.env.SLACK_FORWARDER_URL;
|
||||
const originalSlackBotUserId = process.env.SLACK_BOT_USER_ID;
|
||||
const api = {
|
||||
pluginConfig: {},
|
||||
config: {
|
||||
agents: {
|
||||
list: [{ id: "test-agent", default: true, identity: { name: "TestBot" } }],
|
||||
},
|
||||
},
|
||||
runtime: {
|
||||
config: {
|
||||
current: () => configFile,
|
||||
},
|
||||
},
|
||||
id: "thread-ownership",
|
||||
name: "Thread Ownership",
|
||||
logger: { info: vi.fn(), warn: vi.fn(), debug: vi.fn() },
|
||||
on: vi.fn((hookName: string, handler: Function) => {
|
||||
hooks[hookName] = handler;
|
||||
}),
|
||||
};
|
||||
|
||||
function expectOwnershipFetchCall(index: number, url: string, agentId: string) {
|
||||
const call = vi.mocked(globalThis.fetch).mock.calls[index];
|
||||
if (!call) {
|
||||
throw new Error(`expected ownership fetch call ${index}`);
|
||||
}
|
||||
expect(call[0]).toBe(url);
|
||||
const init = call[1];
|
||||
expect(init?.method).toBe("POST");
|
||||
expect(init?.body).toBe(JSON.stringify({ agent_id: agentId }));
|
||||
}
|
||||
|
||||
function requireFirstLogMessage(mock: ReturnType<typeof vi.fn>, label: string): string {
|
||||
const [call] = mock.mock.calls;
|
||||
if (!call || typeof call[0] !== "string") {
|
||||
throw new Error(`expected ${label}`);
|
||||
}
|
||||
return call[0];
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
for (const key of Object.keys(hooks)) {
|
||||
delete hooks[key];
|
||||
}
|
||||
api.pluginConfig = {};
|
||||
configFile = {
|
||||
agents: api.config.agents,
|
||||
};
|
||||
|
||||
process.env.SLACK_FORWARDER_URL = "http://localhost:8750";
|
||||
process.env.SLACK_BOT_USER_ID = "U999";
|
||||
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
if (originalSlackForwarderUrl === undefined) {
|
||||
delete process.env.SLACK_FORWARDER_URL;
|
||||
} else {
|
||||
process.env.SLACK_FORWARDER_URL = originalSlackForwarderUrl;
|
||||
}
|
||||
if (originalSlackBotUserId === undefined) {
|
||||
delete process.env.SLACK_BOT_USER_ID;
|
||||
} else {
|
||||
process.env.SLACK_BOT_USER_ID = originalSlackBotUserId;
|
||||
}
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("message_sending", () => {
|
||||
beforeEach(() => {
|
||||
register.register(api as unknown as OpenClawPluginApi);
|
||||
});
|
||||
|
||||
async function sendSlackThreadMessage() {
|
||||
return await hooks.message_sending(
|
||||
{ content: "hello", replyToId: "1234.5678", metadata: { channelId: "C123" }, to: "C123" },
|
||||
{ channelId: "slack", conversationId: "C123" },
|
||||
);
|
||||
}
|
||||
|
||||
it("allows non-slack channels", async () => {
|
||||
const result = await hooks.message_sending(
|
||||
{ content: "hello", replyToId: "1234.5678", metadata: { channelId: "C123" }, to: "C123" },
|
||||
{ channelId: "discord", conversationId: "C123" },
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
expect(globalThis.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("allows top-level messages (no threadTs)", async () => {
|
||||
const result = await hooks.message_sending(
|
||||
{ content: "hello", metadata: {}, to: "C123" },
|
||||
{ channelId: "slack", conversationId: "C123" },
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
expect(globalThis.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails open when Slack thread routing has no canonical conversation id", async () => {
|
||||
const result = await hooks.message_sending(
|
||||
{ content: "hello", replyToId: "1234.5678", metadata: {}, to: "" },
|
||||
{ channelId: "slack", conversationId: "" },
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
expect(globalThis.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("claims ownership successfully", async () => {
|
||||
vi.mocked(globalThis.fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify({ owner: "test-agent" }), { status: 200 }),
|
||||
);
|
||||
|
||||
const result = await sendSlackThreadMessage();
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
expectOwnershipFetchCall(
|
||||
0,
|
||||
"http://localhost:8750/api/v1/ownership/C123/1234.5678",
|
||||
"test-agent",
|
||||
);
|
||||
});
|
||||
|
||||
it("prefers shared conversationId over non-canonical Slack target shapes", async () => {
|
||||
vi.mocked(globalThis.fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify({ owner: "test-agent" }), { status: 200 }),
|
||||
);
|
||||
|
||||
const result = await hooks.message_sending(
|
||||
{
|
||||
content: "hello",
|
||||
replyToId: "1234.5678",
|
||||
to: "channel:C123",
|
||||
},
|
||||
{ channelId: "slack", conversationId: "C123" },
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
expectOwnershipFetchCall(
|
||||
0,
|
||||
"http://localhost:8750/api/v1/ownership/C123/1234.5678",
|
||||
"test-agent",
|
||||
);
|
||||
});
|
||||
|
||||
it("canonicalizes non-canonical Slack targets when shared conversationId is missing", async () => {
|
||||
vi.mocked(globalThis.fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify({ owner: "test-agent" }), { status: 200 }),
|
||||
);
|
||||
|
||||
const result = await hooks.message_sending(
|
||||
{
|
||||
content: "hello",
|
||||
replyToId: "1234.5678",
|
||||
to: "channel:c123",
|
||||
},
|
||||
{ channelId: "slack", conversationId: "" },
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
expectOwnershipFetchCall(
|
||||
0,
|
||||
"http://localhost:8750/api/v1/ownership/C123/1234.5678",
|
||||
"test-agent",
|
||||
);
|
||||
});
|
||||
|
||||
it("canonicalizes configured ab-test channel allowlists before matching", async () => {
|
||||
api.pluginConfig = { abTestChannels: ["channel:c123"] };
|
||||
register.register(api as unknown as OpenClawPluginApi);
|
||||
vi.mocked(globalThis.fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify({ owner: "test-agent" }), { status: 200 }),
|
||||
);
|
||||
|
||||
const result = await hooks.message_sending(
|
||||
{
|
||||
content: "hello",
|
||||
replyToId: "1234.5678",
|
||||
to: "channel:c123",
|
||||
},
|
||||
{ channelId: "slack", conversationId: "" },
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
expectOwnershipFetchCall(
|
||||
0,
|
||||
"http://localhost:8750/api/v1/ownership/C123/1234.5678",
|
||||
"test-agent",
|
||||
);
|
||||
});
|
||||
|
||||
it("uses live runtime allowlists when deciding whether to claim ownership", async () => {
|
||||
api.pluginConfig = { abTestChannels: ["C123"] };
|
||||
configFile = {
|
||||
...configFile,
|
||||
plugins: {
|
||||
entries: {
|
||||
"thread-ownership": {
|
||||
config: {
|
||||
abTestChannels: ["C999"],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
register.register(api as unknown as OpenClawPluginApi);
|
||||
|
||||
const result = await hooks.message_sending(
|
||||
{
|
||||
content: "hello",
|
||||
replyToId: "1234.5678",
|
||||
to: "C123",
|
||||
},
|
||||
{ channelId: "slack", conversationId: "C123" },
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
expect(globalThis.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not fall back to startup allowlists when live plugin config is removed", async () => {
|
||||
api.pluginConfig = { abTestChannels: ["C999"] };
|
||||
register.register(api as unknown as OpenClawPluginApi);
|
||||
vi.mocked(globalThis.fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify({ owner: "test-agent" }), { status: 200 }),
|
||||
);
|
||||
|
||||
const result = await hooks.message_sending(
|
||||
{
|
||||
content: "hello",
|
||||
replyToId: "1234.5678",
|
||||
to: "C123",
|
||||
},
|
||||
{ channelId: "slack", conversationId: "C123" },
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
expectOwnershipFetchCall(
|
||||
0,
|
||||
"http://localhost:8750/api/v1/ownership/C123/1234.5678",
|
||||
"test-agent",
|
||||
);
|
||||
});
|
||||
|
||||
it("cancels when thread owned by another agent", async () => {
|
||||
vi.mocked(globalThis.fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify({ owner: "other-agent" }), { status: 409 }),
|
||||
);
|
||||
|
||||
const result = await sendSlackThreadMessage();
|
||||
|
||||
expect(result).toEqual({ cancel: true });
|
||||
const infoMessage = requireFirstLogMessage(api.logger.info, "ownership cancel info log");
|
||||
expect(infoMessage).toContain("cancelled send");
|
||||
});
|
||||
|
||||
it("fails open on network error", async () => {
|
||||
vi.mocked(globalThis.fetch).mockRejectedValue(new Error("ECONNREFUSED"));
|
||||
|
||||
const result = await sendSlackThreadMessage();
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
const warningMessage = requireFirstLogMessage(api.logger.warn, "ownership check warning log");
|
||||
expect(warningMessage).toContain("ownership check failed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("message_received @-mention tracking", () => {
|
||||
beforeEach(() => {
|
||||
register.register(api as unknown as OpenClawPluginApi);
|
||||
});
|
||||
|
||||
it("tracks @-mentions and skips ownership check for mentioned threads", async () => {
|
||||
// Simulate receiving a message that @-mentions the agent.
|
||||
await hooks.message_received(
|
||||
{
|
||||
content: "Hey @TestBot help me",
|
||||
threadId: "9999.0001",
|
||||
metadata: { channelId: "C456" },
|
||||
},
|
||||
{ channelId: "slack", conversationId: "C456" },
|
||||
);
|
||||
|
||||
// Now send in the same thread -- should skip the ownership HTTP call.
|
||||
const result = await hooks.message_sending(
|
||||
{ content: "Sure!", replyToId: "9999.0001", metadata: { channelId: "C456" }, to: "C456" },
|
||||
{ channelId: "slack", conversationId: "C456" },
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
expect(globalThis.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("tracks mentions under the shared conversationId when inbound metadata is non-canonical", async () => {
|
||||
await hooks.message_received(
|
||||
{
|
||||
content: "Hey @TestBot help me",
|
||||
threadId: "9999.0002",
|
||||
metadata: { channelId: "channel:c456" },
|
||||
},
|
||||
{ channelId: "slack", conversationId: "C456" },
|
||||
);
|
||||
|
||||
const result = await hooks.message_sending(
|
||||
{
|
||||
content: "Sure!",
|
||||
replyToId: "9999.0002",
|
||||
to: "channel:C456",
|
||||
},
|
||||
{ channelId: "slack", conversationId: "C456" },
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
expect(globalThis.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("canonicalizes inbound non-canonical metadata without shared conversation context", async () => {
|
||||
await hooks.message_received(
|
||||
{
|
||||
content: "Hey @TestBot help me",
|
||||
threadId: "9999.0003",
|
||||
metadata: { channelId: "channel:c456" },
|
||||
},
|
||||
{ channelId: "slack", conversationId: "" },
|
||||
);
|
||||
|
||||
const result = await hooks.message_sending(
|
||||
{
|
||||
content: "Sure!",
|
||||
replyToId: "9999.0003",
|
||||
to: "c456",
|
||||
},
|
||||
{ channelId: "slack", conversationId: "C456" },
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
expect(globalThis.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("ignores @-mentions on non-slack channels", async () => {
|
||||
// Use a unique thread key so module-level state from other tests doesn't interfere.
|
||||
await hooks.message_received(
|
||||
{ content: "Hey @TestBot", threadId: "7777.0001", metadata: { channelId: "C999" } },
|
||||
{ channelId: "discord", conversationId: "C999" },
|
||||
);
|
||||
|
||||
// The mention should not have been tracked, so sending should still call fetch.
|
||||
vi.mocked(globalThis.fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify({ owner: "test-agent" }), { status: 200 }),
|
||||
);
|
||||
|
||||
await hooks.message_sending(
|
||||
{ content: "Sure!", replyToId: "7777.0001", metadata: { channelId: "C999" }, to: "C999" },
|
||||
{ channelId: "slack", conversationId: "C999" },
|
||||
);
|
||||
|
||||
expect(globalThis.fetch).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("tracks bot user ID mentions via <@U999> syntax", async () => {
|
||||
await hooks.message_received(
|
||||
{
|
||||
content: "Hey <@U999> help",
|
||||
threadId: "8888.0001",
|
||||
metadata: { channelId: "C789" },
|
||||
},
|
||||
{ channelId: "slack", conversationId: "C789" },
|
||||
);
|
||||
|
||||
const result = await hooks.message_sending(
|
||||
{ content: "On it!", replyToId: "8888.0001", metadata: { channelId: "C789" }, to: "C789" },
|
||||
{ channelId: "slack", conversationId: "C789" },
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
expect(globalThis.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("tracks agent-name mentions case-insensitively", async () => {
|
||||
await hooks.message_received(
|
||||
{
|
||||
content: "hey @testbot help",
|
||||
threadId: "8888.0002",
|
||||
metadata: { channelId: "C789" },
|
||||
},
|
||||
{ channelId: "slack", conversationId: "C789" },
|
||||
);
|
||||
|
||||
const result = await hooks.message_sending(
|
||||
{ content: "On it!", replyToId: "8888.0002", metadata: { channelId: "C789" }, to: "C789" },
|
||||
{ channelId: "slack", conversationId: "C789" },
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
expect(globalThis.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the live runtime agent identity for ownership claims", async () => {
|
||||
configFile = {
|
||||
...configFile,
|
||||
agents: {
|
||||
list: [{ id: "live-agent", default: true, identity: { name: "LiveBot" } }],
|
||||
},
|
||||
};
|
||||
vi.mocked(globalThis.fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify({ owner: "live-agent" }), { status: 200 }),
|
||||
);
|
||||
|
||||
await hooks.message_sending(
|
||||
{ content: "On it!", replyToId: "8888.0005", metadata: { channelId: "C789" }, to: "C789" },
|
||||
{ channelId: "slack", conversationId: "C789" },
|
||||
);
|
||||
|
||||
expectOwnershipFetchCall(
|
||||
0,
|
||||
"http://localhost:8750/api/v1/ownership/C789/8888.0005",
|
||||
"live-agent",
|
||||
);
|
||||
});
|
||||
|
||||
it("uses the live runtime agent name for mention tracking", async () => {
|
||||
configFile = {
|
||||
...configFile,
|
||||
agents: {
|
||||
list: [{ id: "live-agent", default: true, identity: { name: "LiveBot" } }],
|
||||
},
|
||||
};
|
||||
|
||||
await hooks.message_received(
|
||||
{
|
||||
content: "hey @LiveBot help",
|
||||
threadId: "8888.0006",
|
||||
metadata: { channelId: "C789" },
|
||||
},
|
||||
{ channelId: "slack", conversationId: "C789" },
|
||||
);
|
||||
|
||||
const result = await hooks.message_sending(
|
||||
{ content: "On it!", replyToId: "8888.0006", metadata: { channelId: "C789" }, to: "C789" },
|
||||
{ channelId: "slack", conversationId: "C789" },
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
expect(globalThis.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not treat superset handles as agent-name mentions", async () => {
|
||||
await hooks.message_received(
|
||||
{
|
||||
content: "hey @testbot2 help",
|
||||
threadId: "8888.0003",
|
||||
metadata: { channelId: "C789" },
|
||||
},
|
||||
{ channelId: "slack", conversationId: "C789" },
|
||||
);
|
||||
|
||||
vi.mocked(globalThis.fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify({ owner: "test-agent" }), { status: 200 }),
|
||||
);
|
||||
|
||||
await hooks.message_sending(
|
||||
{ content: "On it!", replyToId: "8888.0003", metadata: { channelId: "C789" }, to: "C789" },
|
||||
{ channelId: "slack", conversationId: "C789" },
|
||||
);
|
||||
|
||||
expect(globalThis.fetch).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not treat email-like text as an agent-name mention", async () => {
|
||||
await hooks.message_received(
|
||||
{
|
||||
content: "send mail to foo@testbot.com",
|
||||
threadId: "8888.0004",
|
||||
metadata: { channelId: "C789" },
|
||||
},
|
||||
{ channelId: "slack", conversationId: "C789" },
|
||||
);
|
||||
|
||||
vi.mocked(globalThis.fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify({ owner: "test-agent" }), { status: 200 }),
|
||||
);
|
||||
|
||||
await hooks.message_sending(
|
||||
{ content: "On it!", replyToId: "8888.0004", metadata: { channelId: "C789" }, to: "C789" },
|
||||
{ channelId: "slack", conversationId: "C789" },
|
||||
);
|
||||
|
||||
expect(globalThis.fetch).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
210
extensions/thread-ownership/index.ts
Normal file
210
extensions/thread-ownership/index.ts
Normal file
@@ -0,0 +1,210 @@
|
||||
// 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,
|
||||
ssrfPolicyFromDangerouslyAllowPrivateNetwork,
|
||||
type OpenClawConfig,
|
||||
type OpenClawPluginApi,
|
||||
} from "./api.js";
|
||||
|
||||
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) {
|
||||
const body = (await resp.json()) as { owner?: string };
|
||||
api.logger.info?.(
|
||||
`thread-ownership: cancelled send to ${channelId}:${threadTs} — owned by ${body.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;
|
||||
});
|
||||
},
|
||||
});
|
||||
31
extensions/thread-ownership/openclaw.plugin.json
Normal file
31
extensions/thread-ownership/openclaw.plugin.json
Normal file
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"id": "thread-ownership",
|
||||
"activation": {
|
||||
"onStartup": true
|
||||
},
|
||||
"name": "Thread Ownership",
|
||||
"description": "Prevents multiple agents from responding in the same Slack thread. Uses HTTP calls to the slack-forwarder ownership API.",
|
||||
"configSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"forwarderUrl": {
|
||||
"type": "string"
|
||||
},
|
||||
"abTestChannels": {
|
||||
"type": "array",
|
||||
"items": { "type": "string" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"uiHints": {
|
||||
"forwarderUrl": {
|
||||
"label": "Forwarder URL",
|
||||
"help": "Base URL of the slack-forwarder ownership API (default: http://slack-forwarder:8750)"
|
||||
},
|
||||
"abTestChannels": {
|
||||
"label": "A/B Test Channels",
|
||||
"help": "Slack channel IDs where thread ownership is enforced"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user