Skip to content

Commit d6f70a9

Browse files
authored
fix(plugins): native commands execute the selected plugin (#121544)
* fix(plugins): preserve selected command identity * test(telegram): use scoped command registries * test(telegram): isolate command runtime fixtures * test(telegram): warm native command runtime * refactor(plugins): keep command metadata private * fix(plugins): accept synchronous command handlers * fix(plugins): scope command drain bypass to live execution * test(telegram): use scoped command registry fixtures * test(telegram): isolate native menu runtime fixtures * test(telegram): isolate login session store * test(telegram): surface login flow failures * test(telegram): preload native login module * test(telegram): scope native command registries * fix(plugins): complete command dispatch contracts * fix(plugins): break command dispatch import cycles * fix(plugins): stabilize command dispatch contracts * fix(channels): keep plugin dispatch options internal * fix(plugins): keep command dispatch carrier opaque * test(channels): align delivery adapter fixtures * test(delivery): align custody ownership coverage * test(delivery): align latest queue reconciliation * test(channels): drop obsolete delivery wrappers * fix(plugins): rebind channel reload starts * fix(plugins): scope command catalog reloads * fix(ci): align current runtime contracts * chore(plugin-sdk): refresh API baseline
1 parent bdd3543 commit d6f70a9

83 files changed

Lines changed: 3216 additions & 1823 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.

‎docs/.generated/plugin-sdk-api-baseline.jsonl‎

Lines changed: 105 additions & 96 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

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

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -921,6 +921,33 @@ unrelated inbound runtime helpers.
921921
an adapter test that proves the mode skips a wildcard `toolsBySender` entry
922922
without dropping the matching base `tools` restriction.
923923

924+
### Native plugin command ownership
925+
926+
Channel plugins that publish provider-native command catalogs should use
927+
`openclaw/plugin-sdk/plugin-command-runtime`. Create one runtime while
928+
planning the catalog, merge its candidates with built-in and skill entries,
929+
and retain the winning candidate object in the registered handler closure.
930+
Once the provider catalog is finalized, call
931+
`retainNativeCatalog(provider)` when at least one plugin candidate remains;
932+
if listener registration can fail synchronously, call it after those
933+
listeners are installed. This records the current channel-account lifecycle
934+
so a registry reload restarts only accounts whose handlers retain that
935+
registry generation.
936+
Call `prepareDispatch(rawArgs)` only on that winner and execute the returned
937+
dispatch with `dispatch.execute(context)`. Carry an explicit
938+
`{ kind: "non-plugin" }` decision for retained built-in and skill winners.
939+
This keeps the advertised command and
940+
its executable plugin registration on the same registry generation.
941+
942+
Candidates expose only immutable display/auth/progress metadata plus an
943+
opaque process-local dispatch. They do not expose handlers, plugin roots,
944+
or registry rows. Dispatches cannot cross runtime factories or channels,
945+
and a registry replacement makes new executions return an unavailable
946+
result instead of rematching command text against the replacement registry.
947+
A command already admitted before retirement may finish on its captured
948+
generation. Do not serialize candidates or dispatches; project only their
949+
display fields into provider API payloads.
950+
924951
</Step>
925952

926953
<Step title="Wire the entry point">

‎docs/plugins/sdk-subpaths.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,7 @@ Use `isLoopbackHost(host)` when a plugin must accept only the local machine. It
228228
| `plugin-sdk/channel-runtime-context` | Generic channel runtime-context registration and lookup helpers |
229229
| `plugin-sdk/matrix` | Deprecated Matrix compatibility facade for older third-party channel packages; new plugins should import `plugin-sdk/run-command` directly |
230230
| `plugin-sdk/runtime-store` | `createPluginRuntimeStore` |
231+
| `plugin-sdk/plugin-command-runtime` | Registry-generation-bound native plugin command candidates, terminal catalog decisions, and exact selected dispatch execution |
231232
| `plugin-sdk/plugin-runtime` | Deprecated broad barrel for plugin command/hook/http/interactive helpers; prefer focused plugin runtime subpaths |
232233
| `plugin-sdk/hook-runtime` | Deprecated broad barrel for webhook/internal hook pipeline helpers; prefer focused hook/plugin runtime subpaths |
233234
| `plugin-sdk/lazy-runtime` | Lazy runtime import/binding helpers such as `createLazyRuntimeModule`, `createLazyRuntimeMethod`, and `createLazyRuntimeSurface` |

‎extensions/discord/src/monitor/message-handler.process-progress.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
import type { StatusReactionController } from "openclaw/plugin-sdk/channel-feedback";
2-
import type { ChannelInboundTurnPlan } from "openclaw/plugin-sdk/channel-inbound";
32
// Discord plugin module owns progress-window state and agent-event rendering.
43
import { createChannelProgressReceiptTracker } from "openclaw/plugin-sdk/channel-outbound";
4+
import type { GetReplyOptions } from "openclaw/plugin-sdk/reply-runtime";
55
import { getSessionEntry, resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime";
66
import type { createDiscordDraftPreviewController } from "./message-handler.draft-preview.js";
77
import type { DiscordMessagePreflightContext } from "./message-handler.preflight.js";
88

9-
type ReplyOptions = NonNullable<ChannelInboundTurnPlan["replyOptions"]>;
9+
type ReplyOptions = Omit<GetReplyOptions, "onBlockReply">;
1010
type CallbackPayload<K extends keyof ReplyOptions> =
1111
NonNullable<ReplyOptions[K]> extends (...args: infer Args) => unknown ? Args[0] : never;
1212
type DraftPreview = ReturnType<typeof createDiscordDraftPreviewController>;

‎extensions/discord/src/monitor/native-command-agent-reply.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ import {
77
import { resolveChannelStreamingBlockEnabled } from "openclaw/plugin-sdk/channel-outbound";
88
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
99
import { getAgentScopedMediaLocalRoots } from "openclaw/plugin-sdk/media-runtime";
10+
import {
11+
PLUGIN_COMMAND_DISPATCH,
12+
type PluginCommandCatalogDecision,
13+
} from "openclaw/plugin-sdk/plugin-command-runtime";
1014
import { resolveChunkMode, resolveTextChunkLimit } from "openclaw/plugin-sdk/reply-chunking";
1115
import type { ReplyPayload } from "openclaw/plugin-sdk/reply-dispatch-runtime";
1216
import type { createSubsystemLogger } from "openclaw/plugin-sdk/runtime-env";
@@ -52,6 +56,7 @@ export async function dispatchDiscordNativeAgentReply(params: {
5256
responseEphemeral?: boolean;
5357
suppressReplies?: boolean;
5458
log: ReturnType<typeof createSubsystemLogger>;
59+
pluginCommandDispatch: PluginCommandCatalogDecision;
5560
}): Promise<DispatchDiscordNativeAgentReplyResult> {
5661
const blockStreamingEnabled = resolveChannelStreamingBlockEnabled(params.discordConfig);
5762

@@ -139,6 +144,7 @@ export async function dispatchDiscordNativeAgentReply(params: {
139144
},
140145
replyOptions: {
141146
skillFilter: params.channelConfig?.skills,
147+
[PLUGIN_COMMAND_DISPATCH]: params.pluginCommandDispatch,
142148
disableBlockStreaming:
143149
typeof blockStreamingEnabled === "boolean" ? !blockStreamingEnabled : undefined,
144150
},

‎extensions/discord/src/monitor/native-command-arg-ui.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@ async function handleDiscordCommandArgInteraction(params: {
124124
preferFollowUp: true,
125125
threadBindings: ctx.threadBindings,
126126
responseEphemeral: resolveDiscordSlashCommandConfig(ctx.discordConfig?.slashCommand).ephemeral,
127+
pluginCommandDispatch: { kind: "non-plugin" },
127128
});
128129
}
129130

‎extensions/discord/src/monitor/native-command-dispatch.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Discord plugin module implements native command dispatch behavior.
22
import type { ChatCommandDefinition, CommandArgs } from "openclaw/plugin-sdk/command-auth-native";
33
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
4+
import type { PluginCommandCatalogDecision } from "openclaw/plugin-sdk/plugin-command-runtime";
45
import type { ReplyPayload } from "openclaw/plugin-sdk/reply-dispatch-runtime";
56
import type { ResolvedAgentRoute } from "openclaw/plugin-sdk/routing";
67
import type {
@@ -25,6 +26,7 @@ type DispatchDiscordCommandInteractionParams = {
2526
threadBindings: ThreadBindingManager;
2627
responseEphemeral?: boolean;
2728
suppressReplies?: boolean;
29+
pluginCommandDispatch: PluginCommandCatalogDecision;
2830
};
2931

3032
export type DispatchDiscordCommandInteractionResult = {

‎extensions/discord/src/monitor/native-command-model-picker-apply.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ export async function applyDiscordModelPickerSelection(params: {
6565
preferFollowUp: true,
6666
threadBindings: params.threadBindings,
6767
suppressReplies: true,
68+
pluginCommandDispatch: { kind: "non-plugin" },
6869
}),
6970
12000,
7071
);

‎extensions/discord/src/monitor/native-command.options.test.ts‎

Lines changed: 109 additions & 114 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import {
77
setRuntimeConfigSnapshot,
88
} from "openclaw/plugin-sdk/runtime-config-snapshot";
99
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
10-
import { nativeCommandRuntime } from "./native-command.runtime.js";
1110

1211
const { loadModelCatalogMock, logVerboseMock } = vi.hoisted(() => ({
1312
loadModelCatalogMock: vi.fn(),
@@ -435,78 +434,73 @@ describe("createDiscordNativeCommand option wiring", () => {
435434
});
436435

437436
it("keeps plugin command autocomplete aligned with dispatch owner checks", async () => {
438-
const restoreMatchPluginCommand = nativeCommandRuntime.matchPluginCommand;
439-
nativeCommandRuntime.matchPluginCommand = (prompt) =>
440-
prompt === "/pair" ? ({ command: { name: "pair" }, args: "" } as never) : null;
441-
try {
442-
const command = createDiscordNativeCommand({
443-
command: {
444-
name: "pair",
445-
description: "Pair",
446-
acceptsArgs: true,
447-
args: [
448-
{
449-
name: "mode",
450-
description: "Pairing mode",
451-
type: "string",
452-
preferAutocomplete: true,
453-
choices: () => [
454-
{ label: "fast", value: "fast" },
455-
{ label: "secure", value: "secure" },
456-
],
457-
},
458-
],
459-
},
460-
cfg: createAllowedGuildAutocompleteConfig({
461-
ownerAllowFrom: ["user:owner-user"],
437+
const command = createDiscordNativeCommand({
438+
command: {
439+
name: "pair",
440+
description: "Pair",
441+
acceptsArgs: true,
442+
args: [
443+
{
444+
name: "mode",
445+
description: "Pairing mode",
446+
type: "string",
447+
preferAutocomplete: true,
448+
choices: () => [
449+
{ label: "fast", value: "fast" },
450+
{ label: "secure", value: "secure" },
451+
],
452+
},
453+
],
454+
requireAuth: true,
455+
prepareDispatch: () => ({
456+
kind: "plugin" as const,
457+
invocation: {
458+
runtime: { execute: vi.fn() },
459+
selection: Object.freeze({}),
460+
},
462461
}),
463-
discordConfig: {
464-
groupPolicy: "allowlist",
465-
guilds: {
466-
"guild-1": {
467-
channels: {
468-
"channel-1": {
469-
enabled: true,
470-
requireMention: false,
471-
},
462+
} as never,
463+
cfg: createAllowedGuildAutocompleteConfig({
464+
ownerAllowFrom: ["user:owner-user"],
465+
}),
466+
discordConfig: {
467+
groupPolicy: "allowlist",
468+
guilds: {
469+
"guild-1": {
470+
channels: {
471+
"channel-1": {
472+
enabled: true,
473+
requireMention: false,
472474
},
473475
},
474476
},
475477
},
476-
accountId: "default",
477-
sessionPrefix: "discord:slash",
478-
ephemeralDefault: true,
479-
threadBindings: createNoopThreadBindingManager("default"),
480-
});
481-
const mode = requireOption(command, "mode");
482-
const autocomplete = requireAutocomplete(
483-
mode,
484-
"plugin mode option did not wire autocomplete",
485-
);
486-
const respond = await runAutocomplete(autocomplete, {
487-
userId: "blocked-user",
488-
username: "blocked",
489-
globalName: "Blocked",
490-
channelType: ChannelType.GuildText,
491-
channelId: "channel-1",
492-
channelName: "general",
493-
guildId: "guild-1",
494-
focusedValue: "",
495-
});
496-
497-
expect(respond).toHaveBeenCalledWith([
498-
{ name: "fast", value: "fast" },
499-
{ name: "secure", value: "secure" },
500-
]);
501-
} finally {
502-
nativeCommandRuntime.matchPluginCommand = restoreMatchPluginCommand;
503-
}
478+
},
479+
accountId: "default",
480+
sessionPrefix: "discord:slash",
481+
ephemeralDefault: true,
482+
threadBindings: createNoopThreadBindingManager("default"),
483+
});
484+
const mode = requireOption(command, "mode");
485+
const autocomplete = requireAutocomplete(mode, "plugin mode option did not wire autocomplete");
486+
const respond = await runAutocomplete(autocomplete, {
487+
userId: "blocked-user",
488+
username: "blocked",
489+
globalName: "Blocked",
490+
channelType: ChannelType.GuildText,
491+
channelId: "channel-1",
492+
channelName: "general",
493+
guildId: "guild-1",
494+
focusedValue: "",
495+
});
496+
497+
expect(respond).toHaveBeenCalledWith([
498+
{ name: "fast", value: "fast" },
499+
{ name: "secure", value: "secure" },
500+
]);
504501
});
505502

506503
it("refreshes autocomplete authorization and dynamic choices between invocations", async () => {
507-
const restoreMatchPluginCommand = nativeCommandRuntime.matchPluginCommand;
508-
nativeCommandRuntime.matchPluginCommand = (prompt) =>
509-
prompt === "/scope" ? ({ command: { name: "scope" }, args: "" } as never) : null;
510504
const sourceCfg = {
511505
session: { dmScope: "main" },
512506
channels: {
@@ -526,56 +520,57 @@ describe("createDiscordNativeCommand option wiring", () => {
526520
},
527521
},
528522
} as OpenClawConfig;
529-
try {
530-
const command = createDiscordNativeCommand({
531-
command: {
532-
name: "scope",
533-
description: "Scope",
534-
acceptsArgs: true,
535-
args: [
536-
{
537-
name: "value",
538-
description: "Scope value",
539-
type: "string",
540-
preferAutocomplete: true,
541-
choices: ({ cfg }) => {
542-
const dmScope = cfg?.session?.dmScope ?? "missing";
543-
return [{ label: dmScope, value: dmScope }];
544-
},
523+
const command = createDiscordNativeCommand({
524+
command: {
525+
name: "scope",
526+
description: "Scope",
527+
acceptsArgs: true,
528+
args: [
529+
{
530+
name: "value",
531+
description: "Scope value",
532+
type: "string",
533+
preferAutocomplete: true,
534+
choices: ({ cfg }: { cfg?: OpenClawConfig }) => {
535+
const dmScope = cfg?.session?.dmScope ?? "missing";
536+
return [{ label: dmScope, value: dmScope }];
545537
},
546-
],
547-
},
548-
cfg: sourceCfg,
549-
discordConfig: sourceCfg.channels?.discord ?? {},
550-
accountId: "default",
551-
sessionPrefix: "discord:slash",
552-
ephemeralDefault: true,
553-
threadBindings: createNoopThreadBindingManager("default"),
554-
});
555-
const value = requireOption(command, "value");
556-
const autocomplete = requireAutocomplete(
557-
value,
558-
"scope value option did not wire autocomplete",
559-
);
560-
const autocompleteParams = {
561-
userId: "owner",
562-
channelType: ChannelType.DM,
563-
channelId: "dm-1",
564-
channelName: "dm-1",
565-
focusedValue: "",
566-
} as const;
567-
568-
const blockedRespond = await runAutocomplete(autocomplete, autocompleteParams);
569-
expect(blockedRespond).toHaveBeenCalledWith([]);
570-
571-
setRuntimeConfigSnapshot(runtimeCfg, runtimeCfg);
572-
const refreshedRespond = await runAutocomplete(autocomplete, autocompleteParams);
573-
expect(refreshedRespond).toHaveBeenCalledWith([
574-
{ name: "per-channel-peer", value: "per-channel-peer" },
575-
]);
576-
} finally {
577-
nativeCommandRuntime.matchPluginCommand = restoreMatchPluginCommand;
578-
}
538+
},
539+
],
540+
requireAuth: true,
541+
prepareDispatch: () => ({
542+
kind: "plugin" as const,
543+
invocation: {
544+
runtime: { execute: vi.fn() },
545+
selection: Object.freeze({}),
546+
},
547+
}),
548+
} as never,
549+
cfg: sourceCfg,
550+
discordConfig: sourceCfg.channels?.discord ?? {},
551+
accountId: "default",
552+
sessionPrefix: "discord:slash",
553+
ephemeralDefault: true,
554+
threadBindings: createNoopThreadBindingManager("default"),
555+
});
556+
const value = requireOption(command, "value");
557+
const autocomplete = requireAutocomplete(value, "scope value option did not wire autocomplete");
558+
const autocompleteParams = {
559+
userId: "owner",
560+
channelType: ChannelType.DM,
561+
channelId: "dm-1",
562+
channelName: "dm-1",
563+
focusedValue: "",
564+
} as const;
565+
566+
const blockedRespond = await runAutocomplete(autocomplete, autocompleteParams);
567+
expect(blockedRespond).toHaveBeenCalledWith([]);
568+
569+
setRuntimeConfigSnapshot(runtimeCfg, runtimeCfg);
570+
const refreshedRespond = await runAutocomplete(autocomplete, autocompleteParams);
571+
expect(refreshedRespond).toHaveBeenCalledWith([
572+
{ name: "per-channel-peer", value: "per-channel-peer" },
573+
]);
579574
});
580575

581576
it("returns no autocomplete choices outside the Discord allowlist when commands.useAccessGroups is false and commands.allowFrom is not configured", async () => {

0 commit comments

Comments
 (0)