Skip to content

Commit 0b85966

Browse files
authored
fix gateway conversation route ownership (#126424)
1 parent 90d1c43 commit 0b85966

128 files changed

Lines changed: 4405 additions & 330 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎config/assertion-safety-baseline.txt‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1200,7 +1200,6 @@ extensions/slack/src/monitor/message-handler/dispatch-helpers.ts 2
12001200
extensions/slack/src/monitor/message-handler/dispatch-streaming.ts 6
12011201
extensions/slack/src/monitor/message-handler/dispatch.ts 2
12021202
extensions/slack/src/monitor/message-handler/prepare-dm-history.ts 1
1203-
extensions/slack/src/monitor/message-handler/prepare-routing.ts 1
12041203
extensions/slack/src/monitor/message-handler/prepare-thread-context.ts 1
12051204
extensions/slack/src/monitor/message-handler/prepare.ts 3
12061205
extensions/slack/src/monitor/message-handler/preview-finalize.ts 3
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
73cfbac3e2ef8a75d561165d9798c805e0a8c726c1bcd1c814c7cae777194b2b sqlite-session-transcript-schema-baseline.sql
1+
fecbb8adccfa0be0b452f646d3bee8d5a17faeb2c2d8a2300fb75ef173c709cd sqlite-session-transcript-schema-baseline.sql

‎docs/plugins/sdk-channel-plugins.md‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -350,11 +350,41 @@ normalizes numeric thread ids the same way core does, so prefer it over ad hoc
350350
should expose `messaging.resolveOutboundSessionRoute(...)` so core gets
351351
provider-native session and thread identity without parser shims.
352352

353+
### Conversation route ownership
354+
355+
Implement `messaging.resolveConversationRouteOwner(...)` when generic route
356+
matching cannot reproduce the channel's configured and runtime binding rules.
357+
The resolver receives the current config, account, and recorded conversation
358+
identity, including a delivery `target` when it differs from the routing peer.
359+
It must reuse the same precedence and provider identity grammar as inbound
360+
routing.
361+
362+
Ownership inspection is synchronous and read-only. Do not refresh binding
363+
liveness, perform network requests, or infer missing provider facts. Return:
364+
365+
- `{ kind: "agent", agentId }` for an agent-owned route.
366+
- `{ kind: "plugin", pluginId, fallbackAgentId }` for a plugin-owned runtime
367+
binding. `fallbackAgentId` is the route used when that plugin has no active
368+
inbound claim handler.
369+
- `{ kind: "unavailable" }` when authoritative owner state is temporarily
370+
unavailable and the caller should retry.
371+
- `null` when the supplied identity is invalid or cannot be authorized.
372+
- `undefined` to delegate to core's generic owner resolution.
373+
374+
Keep temporary unavailability distinct from `null`: an adapter restart is not
375+
proof that a previously bound conversation is unowned.
376+
Use `inspectConversationBinding(...)` from
377+
`openclaw/plugin-sdk/conversation-binding-inspection-runtime` when the resolver needs this
378+
available/unavailable distinction.
379+
353380
### Account-scoped conversation binding support
354381

355382
Set `conversationBindings.supportsCurrentConversationBinding` when the channel
356383
supports generic current-conversation bindings. `createChatChannelPlugin(...)`
357-
sets this static capability to `true` by default.
384+
sets this static capability to `true` by default. Channels whose monitor owns a custom binding
385+
adapter must also set `bindingStore: "adapter"`; core then fails closed while
386+
that adapter is unavailable instead of reading or writing generic binding rows.
387+
Older `createManager`-only plugins retain the same adapter-owned behavior.
358388

359389
If support differs by configured account, also implement
360390
`conversationBindings.isCurrentConversationBindingSupported({ accountId })`.

‎docs/reference/database-schemas.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,12 @@ operator's explicit offline-device abandonment decision so restart recovery
3838
cannot accidentally resume remote reconciliation. Older readers ignore the
3939
column and can reopen the same database safely.
4040

41+
Conversation associations use the same rule for the nullable bare
42+
`route_context_json TEXT` column. The database-open repair ensures the column
43+
for updated binaries. Older readers ignore it and can reopen and update the
44+
same database safely; their association update invalidates context captured by
45+
a newer writer so it cannot be replayed after re-upgrade.
46+
4147
Installing OpenClaw manually through npm bypasses the updater guard. Database open checks still refuse an incompatible build.
4248

4349
## Preflight a target release

‎extensions/discord/src/channel.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ import {
5959
probeDiscordStatusAccount,
6060
} from "./channel.loaders.js";
6161
import { openDiscordCommandDeployHashStore } from "./command-deploy-store.js";
62+
import { inspectDiscordConversationRouteOwner } from "./conversation-route-owner.js";
6263
import { shouldSuppressLocalDiscordExecApprovalPrompt } from "./exec-approvals.js";
6364
import {
6465
resolveDiscordGroupRequireMention,
@@ -259,6 +260,7 @@ export const discordPlugin: ChannelPlugin<ResolvedDiscordAccount, DiscordProbe>
259260
],
260261
},
261262
messaging: {
263+
resolveConversationRouteOwner: inspectDiscordConversationRouteOwner,
262264
targetPrefixes: ["discord"],
263265
directTargetStyle: "user-prefixed",
264266
targetIdComparison: "lowercase",
@@ -424,6 +426,7 @@ export const discordPlugin: ChannelPlugin<ResolvedDiscordAccount, DiscordProbe>
424426
},
425427
conversationBindings: {
426428
supportsCurrentConversationBinding: true,
429+
bindingStore: "adapter",
427430
defaultTopLevelPlacement,
428431
createManager: async ({ cfg, accountId }) =>
429432
(await loadDiscordThreadBindingsManagerModule()).createThreadBindingManager({

‎extensions/discord/src/conversation-identity.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,18 @@ export function resolveDiscordConversationIdentity(params: {
3434
: buildDiscordConversationIdentity("channel", params.channelId);
3535
}
3636

37+
export function resolveDiscordRuntimeBindingConversationId(params: {
38+
isDirectMessage: boolean;
39+
isGroupDm: boolean;
40+
userId?: string | null;
41+
channelId: string;
42+
}): string {
43+
if (params.isDirectMessage && !params.isGroupDm) {
44+
return buildDiscordConversationIdentity("user", params.userId) ?? params.channelId;
45+
}
46+
return params.channelId;
47+
}
48+
3749
export function resolveDiscordCurrentConversationIdentity(params: {
3850
chatType?: string | null;
3951
from?: string | null;
Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
import {
2+
registerSessionBindingAdapter,
3+
type SessionBindingAdapter,
4+
testing as sessionBindingTesting,
5+
unregisterSessionBindingAdapter,
6+
} from "openclaw/plugin-sdk/conversation-runtime";
7+
import {
8+
createTestRegistry,
9+
resetPluginRuntimeStateForTest,
10+
setActivePluginRegistry,
11+
} from "openclaw/plugin-sdk/plugin-test-runtime";
12+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
13+
import { inspectDiscordConversationRouteOwner } from "./conversation-route-owner.js";
14+
15+
describe("inspectDiscordConversationRouteOwner", () => {
16+
let adapter: SessionBindingAdapter;
17+
18+
beforeEach(() => {
19+
resetPluginRuntimeStateForTest();
20+
setActivePluginRegistry(
21+
createTestRegistry([
22+
{
23+
pluginId: "discord",
24+
source: "test",
25+
plugin: {
26+
id: "discord",
27+
meta: { aliases: [] },
28+
conversationBindings: {
29+
supportsCurrentConversationBinding: true,
30+
createManager: () => ({ stop: () => undefined }),
31+
},
32+
},
33+
},
34+
]),
35+
);
36+
sessionBindingTesting.resetSessionBindingAdaptersForTests();
37+
adapter = {
38+
channel: "discord",
39+
accountId: "default",
40+
listBySession: () => [],
41+
resolveByConversation: () => null,
42+
};
43+
registerSessionBindingAdapter(adapter);
44+
});
45+
46+
afterEach(() => {
47+
resetPluginRuntimeStateForTest();
48+
sessionBindingTesting.resetSessionBindingAdaptersForTests();
49+
});
50+
51+
it("uses the direct-user runtime identity without touching liveness", () => {
52+
const touch = vi.fn();
53+
const resolveByConversation = vi.fn((conversation) => ({
54+
bindingId: "binding-direct",
55+
targetSessionKey: "agent:finance:bound",
56+
targetKind: "session" as const,
57+
conversation,
58+
status: "active" as const,
59+
boundAt: 1,
60+
}));
61+
registerSessionBindingAdapter({
62+
channel: "discord",
63+
accountId: "default",
64+
listBySession: () => [],
65+
resolveByConversation,
66+
touch,
67+
});
68+
69+
expect(
70+
inspectDiscordConversationRouteOwner({
71+
cfg: {},
72+
accountId: "default",
73+
conversation: { kind: "direct", peerId: "user-1", nativeChannelId: "dm-1" },
74+
}),
75+
).toEqual({ kind: "agent", agentId: "finance" });
76+
expect(resolveByConversation).toHaveBeenCalledWith(
77+
expect.objectContaining({ conversationId: "user:user-1" }),
78+
);
79+
expect(touch).not.toHaveBeenCalled();
80+
});
81+
82+
it.each([
83+
{ kind: "group" as const, peerId: "group-dm-1" },
84+
{ kind: "channel" as const, peerId: "channel-1" },
85+
])("uses the native channel runtime identity for $kind conversations", ({ kind, peerId }) => {
86+
const resolveByConversation = vi.fn(() => null);
87+
registerSessionBindingAdapter({
88+
channel: "discord",
89+
accountId: "default",
90+
listBySession: () => [],
91+
resolveByConversation,
92+
});
93+
94+
inspectDiscordConversationRouteOwner({
95+
cfg: {},
96+
accountId: "default",
97+
conversation: { kind, peerId, nativeChannelId: peerId },
98+
});
99+
100+
expect(resolveByConversation).toHaveBeenCalledWith(
101+
expect.objectContaining({ conversationId: peerId }),
102+
);
103+
});
104+
105+
it("reports temporary adapter unavailability only while bindings are enabled", () => {
106+
unregisterSessionBindingAdapter({ channel: "discord", accountId: "default", adapter });
107+
const conversation = { kind: "channel" as const, peerId: "channel-1" };
108+
109+
expect(
110+
inspectDiscordConversationRouteOwner({ cfg: {}, accountId: "default", conversation }),
111+
).toEqual({ kind: "unavailable" });
112+
expect(
113+
inspectDiscordConversationRouteOwner({
114+
cfg: { channels: { discord: { threadBindings: { enabled: false } } } },
115+
accountId: "default",
116+
conversation,
117+
}),
118+
).toEqual({ kind: "agent", agentId: "main" });
119+
});
120+
121+
it("preserves explicit plugin ownership independently of the target session key", () => {
122+
registerSessionBindingAdapter({
123+
channel: "discord",
124+
accountId: "default",
125+
listBySession: () => [],
126+
resolveByConversation: (conversation) => ({
127+
bindingId: "binding-plugin",
128+
targetSessionKey: "agent:review:looks-owned",
129+
targetKind: "session",
130+
conversation,
131+
status: "active",
132+
boundAt: 1,
133+
metadata: {
134+
pluginBindingOwner: "plugin",
135+
pluginId: "review-plugin",
136+
pluginRoot: "/plugins/review",
137+
},
138+
}),
139+
});
140+
141+
expect(
142+
inspectDiscordConversationRouteOwner({
143+
cfg: {},
144+
accountId: "default",
145+
conversation: { kind: "channel", peerId: "channel-1" },
146+
}),
147+
).toEqual({ kind: "plugin", pluginId: "review-plugin", fallbackAgentId: "main" });
148+
});
149+
});
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
2+
import { resolveThreadBindingSpawnPolicy } from "openclaw/plugin-sdk/conversation-runtime";
3+
import { resolveDiscordRuntimeBindingConversationId } from "./conversation-identity.js";
4+
import { resolveDiscordConversationBindingRoute } from "./monitor/conversation-binding-route.js";
5+
import { resolveDiscordConversationRoute } from "./monitor/route-resolution.js";
6+
7+
export function inspectDiscordConversationRouteOwner(params: {
8+
cfg: OpenClawConfig;
9+
accountId: string;
10+
conversation: {
11+
kind: "direct" | "group" | "channel";
12+
peerId: string;
13+
threadId?: string;
14+
nativeChannelId?: string;
15+
context?: {
16+
parentPeerId?: string;
17+
guildId?: string;
18+
memberRoleIds?: string[];
19+
};
20+
};
21+
}) {
22+
const direct = params.conversation.kind === "direct";
23+
const nativeConversationId = params.conversation.nativeChannelId ?? params.conversation.peerId;
24+
const threadConversationId = direct ? undefined : params.conversation.threadId;
25+
const runtimeConversationId =
26+
threadConversationId ??
27+
resolveDiscordRuntimeBindingConversationId({
28+
isDirectMessage: direct,
29+
isGroupDm: params.conversation.kind === "group",
30+
userId: direct ? params.conversation.peerId : undefined,
31+
channelId: nativeConversationId,
32+
});
33+
const route = resolveDiscordConversationRoute({
34+
cfg: params.cfg,
35+
accountId: params.accountId,
36+
guildId: params.conversation.context?.guildId,
37+
memberRoleIds: params.conversation.context?.memberRoleIds,
38+
peer: { kind: params.conversation.kind, id: params.conversation.peerId },
39+
parentConversationId: params.conversation.context?.parentPeerId,
40+
});
41+
const { runtimeRoute, configuredRoute } = resolveDiscordConversationBindingRoute({
42+
cfg: params.cfg,
43+
route,
44+
accountId: params.accountId,
45+
runtimeConversationId,
46+
configuredConversationId: threadConversationId ?? nativeConversationId,
47+
parentConversationId: params.conversation.context?.parentPeerId,
48+
touchBinding: false,
49+
});
50+
if (
51+
!runtimeRoute.bindingOwnerAvailable &&
52+
resolveThreadBindingSpawnPolicy({
53+
cfg: params.cfg,
54+
channel: "discord",
55+
accountId: params.accountId,
56+
kind: "subagent",
57+
}).enabled
58+
) {
59+
return { kind: "unavailable" as const };
60+
}
61+
if (runtimeRoute.pluginId) {
62+
return {
63+
kind: "plugin" as const,
64+
pluginId: runtimeRoute.pluginId,
65+
fallbackAgentId: route.agentId,
66+
};
67+
}
68+
return {
69+
kind: "agent" as const,
70+
agentId: runtimeRoute.boundAgentId ?? configuredRoute?.boundAgentId ?? route.agentId,
71+
};
72+
}

‎extensions/discord/src/monitor/agent-components.dispatch.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import {
3636
} from "./inbound-context.js";
3737
import { buildDirectLabel, buildGuildLabel } from "./reply-context.js";
3838
import { deliverDiscordReply } from "./reply-delivery.js";
39+
import { buildDiscordConversationRouteContext } from "./route-resolution.js";
3940

4041
const loadConversationRuntime = createLazyRuntimeModule(
4142
() => import("./agent-components.runtime.js"),
@@ -202,6 +203,14 @@ export async function dispatchDiscordComponentEvent(params: {
202203
SessionKey: sessionKey,
203204
AccountId: accountId,
204205
ChatType: chatType,
206+
...buildDiscordConversationRouteContext({
207+
isDirectMessage: interactionCtx.isDirectMessage,
208+
isGroupDm: interactionCtx.isGroupDm,
209+
directUserId: interactionCtx.userId,
210+
conversationId: interactionCtx.channelId,
211+
isThread: channelCtx.isThread,
212+
parentConversationId: channelCtx.parentId,
213+
}),
205214
ConversationLabel: fromLabel,
206215
SenderName: senderName,
207216
SenderId: interactionCtx.userId,

0 commit comments

Comments
 (0)