Skip to content

Commit feda957

Browse files
authored
fix(gateway): bind channel completion dispatch (#126113)
* fix(gateway): bind channel completion dispatch * fix(plugin-sdk): scope harness completion dispatch * test(agents): cover scoped completion dispatch
1 parent 3666fa6 commit feda957

17 files changed

Lines changed: 175 additions & 42 deletions

‎extensions/qa-channel/src/gateway.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ export async function startQaGatewayAccount(
4444
config: ctx.cfg as CoreConfig,
4545
message,
4646
buildContext,
47+
...(channelRuntime ? { channelRuntime } : {}),
4748
});
4849
const captureInboundError = (error: unknown) => {
4950
inboundError ??= error instanceof Error ? error : new Error(String(error));

‎extensions/qa-channel/src/inbound.ts‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
type QaBusMessage,
2323
} from "./bus-client.js";
2424
import { sendQaChannelMediaBatch } from "./outbound.js";
25+
import type { PluginRuntime } from "./runtime-api.js";
2526
import { getQaChannelRuntime } from "./runtime.js";
2627
import type { CoreConfig, ResolvedQaChannelAccount } from "./types.js";
2728

@@ -266,8 +267,9 @@ export async function handleQaInbound(params: {
266267
config: CoreConfig;
267268
message: QaBusMessage;
268269
buildContext?: typeof buildChannelInboundEventContext;
270+
channelRuntime?: PluginRuntime["channel"];
269271
}) {
270-
const runtime = getQaChannelRuntime();
272+
const channelRuntime = params.channelRuntime ?? getQaChannelRuntime().channel;
271273
const inbound = params.message;
272274
const target = buildQaTarget({
273275
chatType: inbound.conversation.kind,
@@ -297,12 +299,9 @@ export async function handleQaInbound(params: {
297299
});
298300
const isGroup = inbound.conversation.kind !== "direct";
299301
const wasMentioned = isGroup
300-
? runtime.channel.mentions.matchesMentionPatterns(
302+
? channelRuntime.mentions.matchesMentionPatterns(
301303
inbound.text,
302-
runtime.channel.mentions.buildMentionRegexes(
303-
params.config as OpenClawConfig,
304-
route.agentId,
305-
),
304+
channelRuntime.mentions.buildMentionRegexes(params.config as OpenClawConfig, route.agentId),
306305
)
307306
: undefined;
308307
const groupConfig = isGroup
@@ -422,7 +421,7 @@ export async function handleQaInbound(params: {
422421
},
423422
});
424423

425-
await runtime.channel.inbound.dispatch({
424+
await channelRuntime.inbound.dispatch({
426425
cfg: params.config as OpenClawConfig,
427426
channel: params.channelId,
428427
accountId: params.account.accountId,

‎src/agents/embedded-agent-runner/run/run-attempt-dispatch.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { getGatewayContextResolver } from "../../../plugins/runtime/gateway-request-scope.js";
12
import { createAgentHarnessTaskRuntimeScope } from "../../../tasks/agent-harness-task-runtime-scope.js";
23
import type { ToolOutcomeObserver } from "../../agent-tools.before-tool-call.js";
34
import type { AuthProfileStore } from "../../auth-profiles.js";
@@ -381,6 +382,7 @@ export async function dispatchEmbeddedRunAttempt(input: {
381382
? {
382383
agentHarnessTaskRuntimeScope: createAgentHarnessTaskRuntimeScope({
383384
requesterSessionKey: params.sessionKey,
385+
gatewayContextResolver: getGatewayContextResolver(params.admittedRunContext),
384386
}),
385387
}
386388
: {}),

‎src/agents/subagents/announce/subagent-announce-delivery.runtime.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import type {
55
GatewayRequestContext,
66
GatewayRequestHandlers,
77
} from "../../../gateway/server-methods/types.js";
8+
import { withPluginRuntimeGatewayContextResolver } from "../../../plugins/runtime/gateway-request-scope.js";
89
import { dispatchSubagentAnnounceAgent } from "./subagent-announce-delivery.runtime.js";
910

1011
function createContext(handlers: GatewayRequestHandlers): GatewayRequestContext {
@@ -59,4 +60,37 @@ describe("subagent announce Gateway instance dispatch", () => {
5960
),
6061
).resolves.toEqual({ runId: "announce-run", status: "ok", summary: "delivered" });
6162
});
63+
64+
it("delivers through a lifecycle-fenced instance resolver scope", async () => {
65+
const context = createContext({
66+
agent: ({ respond }) => respond(true, { raw: true }),
67+
});
68+
const idempotencyKey = "scoped-subagent-announce";
69+
context.dedupe.set(`agent:${idempotencyKey}`, {
70+
ts: Date.now(),
71+
ok: true,
72+
payload: { runId: "scoped-announce-run", status: "ok", summary: "delivered" },
73+
});
74+
75+
await expect(
76+
withPluginRuntimeGatewayContextResolver(
77+
() => context,
78+
() =>
79+
dispatchSubagentAnnounceAgent(
80+
{
81+
message: "Process one completed child result.",
82+
idempotencyKey,
83+
},
84+
{
85+
expectFinal: true,
86+
forceSyntheticClient: true,
87+
},
88+
),
89+
),
90+
).resolves.toEqual({
91+
runId: "scoped-announce-run",
92+
status: "ok",
93+
summary: "delivered",
94+
});
95+
});
6296
});

‎src/auto-reply/dispatch.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,10 @@ import {
2323
import { withReplyDispatcher } from "./dispatch-dispatcher.js";
2424
import type { CommandSessionMetadataChange } from "./reply/command-session-metadata.js";
2525
import { dispatchReplyFromConfig } from "./reply/dispatch-from-config.js";
26-
import type { DispatchFromConfigResult } from "./reply/dispatch-from-config.types.js";
26+
import type {
27+
DispatchFromConfigResult,
28+
DispatchReplyFromConfig,
29+
} from "./reply/dispatch-from-config.types.js";
2730
import type {
2831
InternalGetReplyFromConfig,
2932
InternalGetReplyOptions,
@@ -200,6 +203,7 @@ export async function dispatchInboundMessage(params: {
200203
toolsAllow?: string[];
201204
replyOptions?: InternalDispatchReplyOptions;
202205
replyResolver?: InternalGetReplyFromConfig;
206+
dispatchReplyFromConfig?: DispatchReplyFromConfig;
203207
onSessionMetadataChanges?: (changes: CommandSessionMetadataChange[]) => void;
204208
replyPayloadRunState?: ReplyPayloadRunState;
205209
/** Observe-only turns run the agent without entering outbound hook stages. */
@@ -240,7 +244,7 @@ export async function dispatchInboundMessage(params: {
240244
measureDiagnosticsTimelineSpan(
241245
"auto_reply.dispatch_reply_from_config",
242246
() =>
243-
dispatchReplyFromConfig({
247+
(params.dispatchReplyFromConfig ?? dispatchReplyFromConfig)({
244248
ctx: finalized,
245249
cfg: params.cfg,
246250
dispatcher: params.dispatcher,
@@ -269,6 +273,7 @@ type BufferedInboundDispatcherParams = {
269273
toolsAllow?: string[];
270274
replyOptions?: InternalDispatchReplyOptions;
271275
replyResolver?: InternalGetReplyFromConfig;
276+
dispatchReplyFromConfig?: DispatchReplyFromConfig;
272277
onSessionMetadataChanges?: (changes: CommandSessionMetadataChange[]) => void;
273278
};
274279

@@ -348,6 +353,7 @@ async function dispatchInboundMessageWithBufferedDispatcherCore(
348353
dispatcher,
349354
toolsAllow: params.toolsAllow,
350355
replyResolver: params.replyResolver,
356+
dispatchReplyFromConfig: params.dispatchReplyFromConfig,
351357
replyOptions: {
352358
...params.replyOptions,
353359
...replyOptions,

‎src/auto-reply/reply/agent-runner-execution.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,10 @@ import { formatErrorMessage } from "../../infra/errors.js";
3939
import { recordMessageToolRunOutcome } from "../../infra/message-tool-run-outcome-store.js";
4040
import { logSessionTurnCreated } from "../../logging/diagnostic.js";
4141
import { createSubsystemLogger } from "../../logging/subsystem.js";
42-
import { bindGatewayContextResolver } from "../../plugins/runtime/gateway-request-scope.js";
42+
import {
43+
bindGatewayContextResolver,
44+
getPluginRuntimeGatewayRequestScope,
45+
} from "../../plugins/runtime/gateway-request-scope.js";
4346
import { isInternalMessageChannel } from "../../utils/message-channel.js";
4447
import type { ReplyPayload } from "../types.js";
4548
import {
@@ -527,7 +530,9 @@ async function executeAgentTurnInternal(
527530
};
528531
const runId = params.opts?.runId ?? crypto.randomUUID();
529532
const admittedRunContext: { current?: AdmittedRunContext } = {};
530-
const gatewayContextResolver = readChannelContextGatewayContextResolver(params.sessionCtx);
533+
const gatewayContextResolver =
534+
readChannelContextGatewayContextResolver(params.sessionCtx) ??
535+
getPluginRuntimeGatewayRequestScope()?.resolveGatewayContext;
531536
const preparedRunAdmission = prepareChannelRunAdmission({
532537
cfg: resolveQueuedReplyRuntimeConfig(params.followupRun.run.config),
533538
runId,

‎src/channels/turn/lifecycle.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -625,6 +625,7 @@ async function dispatchChannelTurnWithDeliveryOwner(
625625
},
626626
onError: delivery.onError,
627627
},
628+
dispatchReplyFromConfig: params.dispatchReplyFromConfig,
628629
toolsAllow: params.toolsAllow,
629630
replyOptions,
630631
replyResolver: params.replyResolver,

‎src/channels/turn/types.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@ import type {
44
TurnAdoptionLifecycle,
55
} from "../../auto-reply/get-reply-options.types.js";
66
import type { ReplyPayload } from "../../auto-reply/reply-payload.js";
7-
import type { DispatchFromConfigResult } from "../../auto-reply/reply/dispatch-from-config.types.js";
7+
import type {
8+
DispatchFromConfigResult,
9+
DispatchReplyFromConfig,
10+
} from "../../auto-reply/reply/dispatch-from-config.types.js";
811
import type { GetReplyFromConfig } from "../../auto-reply/reply/get-reply.types.js";
912
import type { HistoryEntry, HistoryMediaEntry } from "../../auto-reply/reply/history.types.js";
1013
import type { DispatchReplyWithBufferedBlockDispatcher } from "../../auto-reply/reply/provider-dispatcher.types.js";
@@ -328,6 +331,8 @@ export type AssembledChannelTurn = {
328331
toolsAllow?: string[];
329332
replyOptions?: ChannelTurnReplyOptions;
330333
replyResolver?: GetReplyFromConfig;
334+
/** Instance-bound reply dispatcher supplied by the owning plugin runtime. */
335+
dispatchReplyFromConfig?: DispatchReplyFromConfig;
331336
sessionInitRetry?: {
332337
delaysMs: readonly number[];
333338
signal?: AbortSignal;

‎src/gateway/server-plugin-in-process-dispatch.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,8 @@ function resolveInProcessGatewayDispatch(
6868
options?: DispatchGatewayMethodInProcessOptions,
6969
): ResolvedInProcessGatewayDispatch {
7070
const scope = getPluginRuntimeGatewayRequestScope();
71-
const context = scope?.context ?? options?.resolveGatewayContext?.();
71+
const context =
72+
options?.resolveGatewayContext?.() ?? scope?.resolveGatewayContext?.() ?? scope?.context;
7273
const isWebchatConnect = scope?.isWebchatConnect ?? (() => false);
7374
if (!context) {
7475
throw new Error(
@@ -188,7 +189,8 @@ export async function dispatchGatewayMethodInProcessRaw(
188189
export function getInProcessGatewayRequestContext(
189190
resolveGatewayContext?: GatewayContextResolver,
190191
): GatewayRequestContext | undefined {
191-
return getPluginRuntimeGatewayRequestScope()?.context ?? resolveGatewayContext?.();
192+
const scope = getPluginRuntimeGatewayRequestScope();
193+
return resolveGatewayContext?.() ?? scope?.resolveGatewayContext?.() ?? scope?.context;
192194
}
193195

194196
export async function dispatchGatewayMethodInProcess<T>(

‎src/gateway/server-plugins-node-runtime.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@ import type { GatewayContextResolver, GatewayRequestContext } from "./server-met
55
export function hasInProcessGatewayContext(
66
resolveGatewayContext?: GatewayContextResolver,
77
): boolean {
8-
return Boolean(getPluginRuntimeGatewayRequestScope()?.context ?? resolveGatewayContext?.());
8+
const scope = getPluginRuntimeGatewayRequestScope();
9+
return Boolean(resolveGatewayContext?.() ?? scope?.resolveGatewayContext?.() ?? scope?.context);
910
}
1011

1112
export function projectGatewayRuntimeNodes(

0 commit comments

Comments
 (0)