Skip to content

Commit 927a97c

Browse files
authored
fix: keep automation delivery owned in multi-agent fleets (#123283)
* fix: preserve automation owner during channel bootstrap * fix: retain scoped runtime during cron delivery * style: format cron delivery regression * chore: defer release changelog entry
1 parent 12ada43 commit 927a97c

17 files changed

Lines changed: 220 additions & 29 deletions

‎docs/gateway/config-agents.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -548,7 +548,7 @@ Periodic heartbeat runs.
548548
- `every`: duration string (ms/s/m/h). Default: `30m` (API-key auth) or `1h` (OAuth auth). Set to `0m` to disable.
549549
- `agentId`: explicit owner for ambient heartbeat runs when no `agents.entries.*.heartbeat` block exists. A shared heartbeat block without `agentId` keeps the existing all-agent enrollment behavior.
550550
- Cadence is written into a system-owned cron monitor row. Run `openclaw doctor --fix` to materialize a missing or stale row. If cron is disabled, scheduled heartbeats do not run and the gateway logs a startup warning.
551-
- The heartbeat object is strict. Its supported fields are `every`, `activeHours`, `model`, `session`, `target`, `directPolicy`, `to`, `accountId`, `prompt`, `timeoutSeconds`, `lightContext`, and `isolatedSession`.
551+
- The heartbeat object is strict. Its supported fields are `agentId`, `every`, `activeHours`, `model`, `session`, `target`, `directPolicy`, `to`, `accountId`, `prompt`, `timeoutSeconds`, `lightContext`, and `isolatedSession`.
552552
- `timeoutSeconds`: maximum time in seconds allowed for a heartbeat agent turn before it is aborted. Leave unset to use `agents.defaults.timeoutSeconds` when set, otherwise the heartbeat cadence capped at 600 seconds.
553553
- `directPolicy`: direct/DM delivery policy. `allow` (default) permits direct-target delivery. `block` suppresses direct-target delivery and emits `reason=dm-blocked`.
554554
- `target`: `owner` (default) sends only to a direct-message identity from `commands.ownerAllowFrom` or channel `allowFrom`. `last` explicitly follows the latest conversation, including groups. `none` keeps results internal.

‎src/channels/turn/durable-delivery.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,7 @@ export async function deliverInboundReplyWithMessageSendContextCore(
178178
try {
179179
support = await resolveOutboundDurableFinalDeliverySupport({
180180
cfg: params.cfg,
181+
agentId: params.agentId,
181182
channel,
182183
requirements: requiredCapabilities,
183184
});

‎src/cron/isolated-agent/delivery-target.runtime.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,16 @@ export { resolveFirstBoundAccountId } from "../../routing/bound-account-read.js"
1818
export async function resolveChannelTargetForDelivery(params: {
1919
cfg: OpenClawConfig;
2020
channel: ChannelId;
21+
agentId: string;
2122
input: string;
2223
accountId?: string | null;
2324
}): Promise<{ ok: true; target: ResolvedMessagingTarget } | { ok: false; error: Error }> {
2425
// Delivery may be the first channel touch after startup; allow bootstrap so
2526
// plugin config and account metadata are available before target resolution.
26-
resolveOutboundChannelPlugin({
27+
const plugin = resolveOutboundChannelPlugin({
2728
channel: params.channel,
2829
cfg: params.cfg,
30+
agentId: params.agentId,
2931
allowBootstrap: true,
3032
});
3133
try {
@@ -35,6 +37,7 @@ export async function resolveChannelTargetForDelivery(params: {
3537
input: params.input,
3638
accountId: params.accountId,
3739
unknownTargetMode: "normalized",
40+
plugin,
3841
});
3942
} catch (err) {
4043
return {
@@ -57,23 +60,26 @@ export async function resolveOutboundSessionRouteForDelivery(params: {
5760
}): Promise<OutboundSessionRoute | null> {
5861
// Route lookup also bootstraps the plugin so canonical thread/session mapping
5962
// matches the send-time channel runtime.
60-
resolveOutboundChannelPlugin({
63+
const plugin = resolveOutboundChannelPlugin({
6164
channel: params.channel,
6265
cfg: params.cfg,
66+
agentId: params.agentId,
6367
allowBootstrap: true,
6468
});
65-
return await resolveOutboundSessionRoute(params);
69+
return await resolveOutboundSessionRoute({ ...params, plugin });
6670
}
6771

6872
/** Returns whether a channel can canonicalize outbound cron delivery sessions. */
6973
export function channelCanResolveOutboundSessionRoute(params: {
7074
cfg: OpenClawConfig;
7175
channel: ChannelId;
76+
agentId: string;
7277
}): boolean {
7378
return Boolean(
7479
resolveOutboundChannelPlugin({
7580
channel: params.channel,
7681
cfg: params.cfg,
82+
agentId: params.agentId,
7783
allowBootstrap: true,
7884
})?.messaging?.resolveOutboundSessionRoute,
7985
);

‎src/cron/isolated-agent/delivery-target.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,7 @@ export async function resolveDeliveryTarget(
345345
const targetResolution = await deliveryTargetRuntime.resolveChannelTargetForDelivery({
346346
cfg,
347347
channel,
348+
agentId,
348349
input: toCandidate,
349350
accountId,
350351
});
@@ -402,6 +403,7 @@ export async function resolveDeliveryTarget(
402403
const routeCanCanonicalizeTarget = deliveryTargetRuntime.channelCanResolveOutboundSessionRoute({
403404
cfg,
404405
channel,
406+
agentId,
405407
});
406408
const routeShouldCanonicalizeTarget =
407409
route && (route.threadId !== undefined || route.to !== routeTargetCandidate);

‎src/infra/outbound/agent-delivery.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,7 @@ export async function resolveAgentDeliveryPlanWithSessionRoute(
187187
resolveOutboundChannelPlugin({
188188
channel: resolvedChannel,
189189
cfg: params.cfg,
190+
agentId: params.agentId,
190191
allowBootstrap: true,
191192
});
192193
if (!plugin) {

‎src/infra/outbound/channel-bootstrap.runtime.test.ts‎

Lines changed: 138 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Covers lazy outbound channel bootstrap, retry guards, auto-enable config, and
22
// send-capable active registry short-circuiting.
33
import { afterEach, describe, expect, it, vi } from "vitest";
4+
import { AgentSelectionRequiredError } from "../../agents/agent-scope-config.js";
45
import type { OpenClawConfig } from "../../config/types.openclaw.js";
56
import { createEmptyPluginRegistry } from "../../plugins/registry-empty.js";
67
import {
@@ -24,7 +25,10 @@ vi.mock("../../plugins/loader.js", () => ({
2425

2526
const { bootstrapOutboundChannelPlugin, resetOutboundChannelBootstrapStateForTests } =
2627
await import("./channel-bootstrap.runtime.js");
27-
const { resolveOutboundDurableFinalDeliverySupport } = await import("./deliver-channel.js");
28+
const { resolveChannelOutboundDirectiveOptions, resolveOutboundDurableFinalDeliverySupport } =
29+
await import("./deliver-channel.js");
30+
const { resolveChannelTargetForDelivery, resolveOutboundSessionRouteForDelivery } =
31+
await import("../../cron/isolated-agent/delivery-target.runtime.js");
2832

2933
const discordConfig = {
3034
channels: {
@@ -38,6 +42,19 @@ const updatedDiscordConfig = {
3842
},
3943
} satisfies OpenClawConfig;
4044

45+
const explicitFleetDiscordConfig = {
46+
agents: {
47+
ownership: "explicit",
48+
entries: {
49+
ops: { workspace: "/tmp/openclaw-ops" },
50+
research: { workspace: "/tmp/openclaw-research" },
51+
},
52+
},
53+
channels: {
54+
discord: {},
55+
},
56+
} satisfies OpenClawConfig;
57+
4158
function installDiscordSetupShell(): void {
4259
const registry = createEmptyPluginRegistry();
4360
registry.channels = [
@@ -69,6 +86,126 @@ describe("bootstrapOutboundChannelPlugin", () => {
6986
expect(loaderMocks.loadPluginRegistryHandle).toHaveBeenCalledTimes(1);
7087
});
7188

89+
it("uses the admitted agent workspace during outbound preparation", async () => {
90+
installDiscordSetupShell();
91+
const handle = createEmptyPluginRegistry();
92+
handle.channels = [
93+
{
94+
pluginId: "discord",
95+
plugin: {
96+
id: "discord",
97+
meta: {},
98+
outbound: {
99+
extractMarkdownImages: true,
100+
sendText: async () => ({ messageId: "1" }),
101+
},
102+
},
103+
source: "runtime",
104+
},
105+
] as never;
106+
loaderMocks.loadPluginRegistryHandle.mockReturnValue(handle);
107+
108+
await expect(
109+
resolveChannelOutboundDirectiveOptions({
110+
channel: "discord",
111+
cfg: explicitFleetDiscordConfig,
112+
agentId: "ops",
113+
}),
114+
).resolves.toEqual({ extractMarkdownImages: true });
115+
116+
expect(loaderMocks.resolveDiscoverableScopedChannelPluginIds).toHaveBeenCalledWith(
117+
expect.objectContaining({ workspaceDir: "/tmp/openclaw-ops" }),
118+
);
119+
});
120+
121+
it("still rejects ownerless bootstrap in an explicit multi-agent fleet", () => {
122+
installDiscordSetupShell();
123+
124+
expect(() =>
125+
bootstrapOutboundChannelPlugin({
126+
channel: "discord",
127+
cfg: explicitFleetDiscordConfig,
128+
}),
129+
).toThrow(AgentSelectionRequiredError);
130+
});
131+
132+
it("caches bootstrap outcomes per admitted agent", () => {
133+
installDiscordSetupShell();
134+
loaderMocks.loadPluginRegistryHandle.mockReturnValue(createEmptyPluginRegistry());
135+
136+
bootstrapOutboundChannelPlugin({
137+
channel: "discord",
138+
cfg: explicitFleetDiscordConfig,
139+
agentId: "ops",
140+
});
141+
bootstrapOutboundChannelPlugin({
142+
channel: "discord",
143+
cfg: explicitFleetDiscordConfig,
144+
agentId: "research",
145+
});
146+
147+
expect(loaderMocks.loadPluginRegistryHandle).toHaveBeenCalledTimes(2);
148+
expect(loaderMocks.resolveDiscoverableScopedChannelPluginIds).toHaveBeenNthCalledWith(
149+
2,
150+
expect.objectContaining({ workspaceDir: "/tmp/openclaw-research" }),
151+
);
152+
});
153+
154+
it("carries the admitted agent runtime into cron target and session resolution", async () => {
155+
installDiscordSetupShell();
156+
const resolveTarget = vi.fn(async () => ({
157+
to: "channel:ops",
158+
kind: "channel" as const,
159+
source: "directory" as const,
160+
}));
161+
const resolveOutboundSessionRoute = vi.fn(() => ({
162+
sessionKey: "agent:ops:discord:channel:ops",
163+
baseSessionKey: "agent:ops:discord:channel:ops",
164+
recipientSessionExact: true as const,
165+
peer: { kind: "channel" as const, id: "ops" },
166+
chatType: "channel" as const,
167+
from: "discord:channel:ops",
168+
to: "channel:ops",
169+
}));
170+
const handle = createEmptyPluginRegistry();
171+
handle.channels = [
172+
{
173+
pluginId: "discord",
174+
plugin: {
175+
id: "discord",
176+
meta: {},
177+
outbound: { sendText: async () => ({ messageId: "1" }) },
178+
messaging: {
179+
targetResolver: { resolveTarget },
180+
resolveOutboundSessionRoute,
181+
},
182+
},
183+
source: "runtime",
184+
},
185+
] as never;
186+
loaderMocks.loadPluginRegistryHandle.mockReturnValue(handle);
187+
188+
await expect(
189+
resolveChannelTargetForDelivery({
190+
cfg: explicitFleetDiscordConfig,
191+
channel: "discord",
192+
agentId: "ops",
193+
input: "ops",
194+
}),
195+
).resolves.toMatchObject({ ok: true, target: { to: "channel:ops" } });
196+
await expect(
197+
resolveOutboundSessionRouteForDelivery({
198+
cfg: explicitFleetDiscordConfig,
199+
channel: "discord",
200+
agentId: "ops",
201+
target: "channel:ops",
202+
}),
203+
).resolves.toMatchObject({ sessionKey: "agent:ops:discord:channel:ops" });
204+
205+
expect(resolveTarget).toHaveBeenCalledTimes(1);
206+
expect(resolveOutboundSessionRoute).toHaveBeenCalledTimes(1);
207+
});
208+
72209
it("skips bootstrap when the selected channel entry can already send", () => {
73210
const registry = createEmptyPluginRegistry();
74211
registry.channels = [

‎src/infra/outbound/channel-bootstrap.runtime.ts‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { loadPluginRegistryHandle } from "../../plugins/loader.js";
1010
import type { PluginChannelRegistration } from "../../plugins/registry-types.js";
1111
import type { PluginRegistry } from "../../plugins/registry.js";
1212
import { getActivePluginRegistry, getActivePluginRegistryVersion } from "../../plugins/runtime.js";
13+
import { normalizeAgentId } from "../../routing/session-key.js";
1314
import { pruneMapToMaxSize } from "../map-size.js";
1415

1516
const MAX_BOOTSTRAP_CONFIG_GENERATIONS = 64;
@@ -19,12 +20,12 @@ const bootstrapRegistriesByConfig = new Map<string, Map<string, PluginRegistry |
1920

2021
function cacheBootstrapOutcome(
2122
registries: Map<string, PluginRegistry | null>,
22-
channel: string,
23+
key: string,
2324
outcome: PluginRegistry | null,
2425
): void {
2526
// Reinsert every outcome, including null, so reads and writes share LRU ordering.
26-
registries.delete(channel);
27-
registries.set(channel, outcome);
27+
registries.delete(key);
28+
registries.set(key, outcome);
2829
pruneMapToMaxSize(registries, MAX_BOOTSTRAP_CHANNEL_OUTCOMES_PER_CONFIG);
2930
}
3031

@@ -83,6 +84,7 @@ function resolveSendCapableRegistry(
8384
export function bootstrapOutboundChannelPlugin(params: {
8485
channel: string;
8586
cfg?: OpenClawConfig;
87+
agentId?: string;
8688
}): PluginRegistry | undefined {
8789
const cfg = params.cfg;
8890
if (!cfg) {
@@ -95,16 +97,21 @@ export function bootstrapOutboundChannelPlugin(params: {
9597
return activeSendRegistry;
9698
}
9799

100+
// Outbound callers already know the admitted run owner. Preserve it here so
101+
// explicit fleets do not fall back to forbidden ambient-agent selection.
102+
const agentId = params.agentId?.trim()
103+
? normalizeAgentId(params.agentId)
104+
: resolveDefaultAgentId(cfg);
105+
const outcomeKey = `${agentId}\0${params.channel}`;
98106
const registries = resolveBootstrapRegistries(cfg);
99-
const cachedRegistry = registries.get(params.channel);
107+
const cachedRegistry = registries.get(outcomeKey);
100108
if (cachedRegistry !== undefined) {
101-
cacheBootstrapOutcome(registries, params.channel, cachedRegistry);
109+
cacheBootstrapOutcome(registries, outcomeKey, cachedRegistry);
102110
return resolveSendCapableRegistry(cachedRegistry, params.channel);
103111
}
104112

105113
const autoEnabled = applyPluginAutoEnable({ config: cfg });
106-
const defaultAgentId = resolveDefaultAgentId(autoEnabled.config);
107-
const workspaceDir = resolveAgentWorkspaceDir(autoEnabled.config, defaultAgentId);
114+
const workspaceDir = resolveAgentWorkspaceDir(autoEnabled.config, agentId);
108115
const pluginIds = resolveDiscoverableScopedChannelPluginIds({
109116
config: autoEnabled.config,
110117
activationSourceConfig: cfg,
@@ -131,6 +138,6 @@ export function bootstrapOutboundChannelPlugin(params: {
131138
} catch {
132139
// Best-effort bootstrap; the caller reports the unavailable channel.
133140
}
134-
cacheBootstrapOutcome(registries, params.channel, sendRegistry ?? null);
141+
cacheBootstrapOutcome(registries, outcomeKey, sendRegistry ?? null);
135142
return sendRegistry;
136143
}

‎src/infra/outbound/channel-resolution.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ function getOutboundRuntimeRegistry(): PluginRegistry | null {
3131
function normalizeOutboundChannelForResolution(params: {
3232
channel: string;
3333
cfg?: OpenClawConfig;
34+
agentId?: string;
3435
allowBootstrap?: boolean;
3536
}): {
3637
channel?: string;
@@ -63,6 +64,7 @@ function normalizeOutboundChannelForResolution(params: {
6364
const bootstrapRegistry = bootstrapOutboundChannelPlugin({
6465
channel: normalized,
6566
cfg: params.cfg,
67+
agentId: params.agentId,
6668
});
6769
const bootstrappedRuntimePlugin = resolveActivatedOutboundPluginFromRuntimeRegistry(
6870
normalized,
@@ -193,6 +195,7 @@ function resolveActivatedOutboundPluginFromRuntimeRegistry(
193195
export function resolveOutboundChannelPlugin(params: {
194196
channel: string;
195197
cfg?: OpenClawConfig;
198+
agentId?: string;
196199
allowBootstrap?: boolean;
197200
}): ChannelPlugin | undefined {
198201
const {
@@ -229,7 +232,11 @@ export function resolveOutboundChannelPlugin(params: {
229232
return undefined;
230233
}
231234

232-
const registry = bootstrapOutboundChannelPlugin({ channel: normalized, cfg: params.cfg });
235+
const registry = bootstrapOutboundChannelPlugin({
236+
channel: normalized,
237+
cfg: params.cfg,
238+
agentId: params.agentId,
239+
});
233240
return resolveRuntimeOutboundPluginCandidate({
234241
loaded: resolveLoaded(),
235242
runtime: resolveActivatedOutboundPluginFromRuntimeRegistry(normalized, registry),
@@ -243,6 +250,7 @@ export function resolveOutboundChannelPlugin(params: {
243250
export function resolveOutboundChannelMessageAdapter(params: {
244251
channel: string;
245252
cfg?: OpenClawConfig;
253+
agentId?: string;
246254
allowBootstrap?: boolean;
247255
}): ChannelMessageAdapterShape | undefined {
248256
const {
@@ -264,7 +272,11 @@ export function resolveOutboundChannelMessageAdapter(params: {
264272
if (current || params.allowBootstrap !== true || didBootstrap) {
265273
return current;
266274
}
267-
const registry = bootstrapOutboundChannelPlugin({ channel: normalized, cfg: params.cfg });
275+
const registry = bootstrapOutboundChannelPlugin({
276+
channel: normalized,
277+
cfg: params.cfg,
278+
agentId: params.agentId,
279+
});
268280
return (
269281
resolveSendCapableMessageAdapter(getLoadedChannelPlugin(normalized)) ??
270282
resolveValueFromRuntimeRegistry(normalized, resolveSendCapableMessageAdapter, registry) ??

‎src/infra/outbound/deferred-delivery-admission.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,12 @@ import { resolveOutboundChannelMessageAdapter } from "./channel-resolution.js";
77

88
export function resolveDeferredDeliveryAdmission(
99
params: ChannelMessageDeferredDeliveryAdmissionContext,
10+
owner?: { agentId?: string },
1011
): ChannelMessageDeferredDeliveryAdmissionResult {
1112
const adapter = resolveOutboundChannelMessageAdapter({
1213
channel: params.channel,
1314
cfg: params.cfg,
15+
agentId: owner?.agentId,
1416
allowBootstrap: true,
1517
});
1618
return adapter?.durableFinal?.admitDeferredDelivery?.(params) ?? { status: "allowed" };

0 commit comments

Comments
 (0)