Skip to content

Commit 1931666

Browse files
authored
fix(agents): consolidate ambient owner resolution (#126504)
1 parent 53fb822 commit 1931666

48 files changed

Lines changed: 260 additions & 300 deletions

Some content is hidden

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

‎docs/gateway/config-agents.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -588,7 +588,7 @@ Selects the agent whose model and credentials own ambient OpenClaw system work:
588588
}
589589
```
590590

591-
An explicit request `agentId` always wins. Delegated consults with a requesting agent keep that requester as their owner. The four reads above opt in individually; other agent-scoped Gateway methods, such as `tools.*`, `commands.*`, chat history, and session-catalog reads, do not use this setting as a general default. Surfaces that pick one agent's view also keep requiring an explicit choice, because silently adopting this owner would hide the other agents: `openclaw sessions` (add `--agent <id>` or `--all-agents`), `openclaw hooks` status, `openclaw models`, stored session lookup by id, and TUI startup. When `systemAgent.agentId` is absent, a sole configured agent resolves implicitly; ambient work in a multi-agent fleet then fails with an actionable error, except queued-delivery recovery, which records the failing delivery and keeps draining the rest of the queue. Upgrade-only ownership lives at `agents.defaults.authInheritance.agentId` for inherited credentials and `agents.defaults.sessionStore.agentId` for retired `main` session rows or unscoped rows in a fixed `session.store`.
591+
An explicit request `agentId` always wins, followed by `systemAgent.agentId`, a retained legacy default owner, and finally the sole configured agent. Delegated consults with a requesting agent keep that requester as their owner. The four reads above opt in individually; other agent-scoped Gateway methods, such as `tools.*`, `commands.*`, chat history, and session-catalog reads, do not use this setting as a general default. Surfaces that pick one agent's view also keep requiring an explicit choice, because silently adopting this owner would hide the other agents: `openclaw sessions` (add `--agent <id>` or `--all-agents`), `openclaw hooks` status, `openclaw models`, stored session lookup by id, and TUI startup. Ambient work in an ownerless multi-agent fleet fails with an actionable error, except queued-delivery recovery, which records the failing delivery and keeps draining the rest of the queue. Upgrade-only ownership lives at `agents.defaults.authInheritance.agentId` for inherited credentials and `agents.defaults.sessionStore.agentId` for retired `main` session rows or unscoped rows in a fixed `session.store`.
592592

593593
### `agents.defaults.compaction`
594594

‎docs/gateway/heartbeat.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ Outside heartbeats, stray `HEARTBEAT_OK` at the start/end of a message is stripp
135135

136136
- `agents.defaults.heartbeat` sets global heartbeat behavior.
137137
- `agents.entries.*.heartbeat` merges on top; if any agent has a `heartbeat` block, **only those agents** run heartbeats.
138-
- Ambient ownership resolves through `agents.defaults.heartbeat.agentId`, the legacy default owner, `agents.defaults.systemAgent.agentId`, then the sole agent; when no per-agent or default heartbeat block applies and that chain leaves a multi-agent roster ownerless, heartbeats stay disabled and emit validation and Gateway warnings.
138+
- Ambient ownership resolves through `agents.defaults.heartbeat.agentId`, `agents.defaults.systemAgent.agentId`, the legacy default owner, then the sole agent; when no per-agent or default heartbeat block applies and that chain leaves a multi-agent roster ownerless, heartbeats stay disabled and emit validation and Gateway warnings.
139139
- `channels.defaults.heartbeatVisibility` sets visibility defaults for all channels.
140140
- `channels.<channel>.heartbeatVisibility` overrides channel defaults.
141141
- `channels.<channel>.accounts.<id>.heartbeatVisibility` (multi-account channels) overrides per-channel settings.

‎docs/tools/custodian-skills.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ read_when:
1010

1111
Custodian skills are release-versioned operational playbooks shipped with OpenClaw. They live under `custodian-skills/` in the package and load at the bundled-skill precedence tier, but only for the agent resolved by `agents.defaults.systemAgent.agentId`.
1212

13-
When that setting is absent, OpenClaw uses the existing system-agent fallback: the sole configured agent, or legacy `main` when no explicit agent roster exists. If several agents are configured and no system agent is selected, no agent receives the library. For every other agent, Custodian skills are absent from discovery, snapshots, slash-command catalogs, sandbox sync, and the model-facing skills prompt.
13+
When that setting is absent, OpenClaw falls back to a retained legacy default owner, the sole configured agent, or legacy `main` when no explicit agent roster exists. If several agents are configured without a system agent or retained legacy owner, no agent receives the library. For every other agent, Custodian skills are absent from discovery, snapshots, slash-command catalogs, sandbox sync, and the model-facing skills prompt.
1414

1515
Normal skill controls still apply. `skills.entries.<name>.enabled: false` disables an individual Custodian skill, and agent skill allowlists can narrow the final set. See [Skills config](/tools/skills-config).
1616

‎src/agents/agent-scope-config.test.ts‎

Lines changed: 74 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,9 @@ import {
1212
resolveDefaultAgentDir,
1313
resolveDefaultAgentId,
1414
resolveSoleAgentId,
15-
resolveSystemAgentTargetAgentId,
1615
tryResolveAmbientOwnerAgentId,
1716
tryResolveDefaultAgentId,
1817
tryResolveSoleAgentId,
19-
tryResolveSystemAgentTargetAgentId,
2018
} from "./agent-scope-config.js";
2119

2220
vi.unmock("./agent-scope-config.js");
@@ -65,62 +63,95 @@ describe("agent roster resolution", () => {
6563
);
6664
});
6765

68-
it("requires an explicit system owner when a roster has multiple agents", () => {
69-
expect(
70-
resolveSystemAgentTargetAgentId({
66+
const ambientOwnerCases: Array<{
67+
name: string;
68+
config: OpenClawConfig;
69+
requestedAgentId?: string;
70+
expected: string;
71+
}> = [
72+
{
73+
name: "configured system agent before a legacy marker",
74+
config: {
7175
agents: {
72-
defaults: { systemAgent: { agentId: "ops" } },
73-
entries: { main: { default: true }, ops: {} },
76+
defaults: { systemAgent: { agentId: "beta" } },
77+
entries: { alpha: { default: true }, beta: {} },
7478
},
75-
}),
76-
).toBe("ops");
77-
expect(resolveSystemAgentTargetAgentId({ agents: { entries: { ops: {} } } })).toBe("ops");
78-
expect(
79-
tryResolveSystemAgentTargetAgentId({
79+
} satisfies OpenClawConfig,
80+
expected: "beta",
81+
},
82+
{
83+
name: "configured system agent before a retained migrated legacy owner",
84+
config: migratePersistedImplicitMainRoster({
8085
agents: {
81-
defaults: { systemAgent: { agentId: "ops" } },
82-
entries: { main: {}, ops: {} },
86+
defaults: { systemAgent: { agentId: "beta" } },
87+
entries: { alpha: { default: true }, beta: {} },
8388
},
84-
}),
85-
).toBe("ops");
86-
expect(tryResolveSystemAgentTargetAgentId({ agents: { entries: { ops: {} } } })).toBe("ops");
87-
expect(
88-
tryResolveSystemAgentTargetAgentId({ agents: { entries: { main: {}, ops: {} } } }),
89-
).toBeUndefined();
90-
expect(() =>
91-
resolveSystemAgentTargetAgentId({
92-
agents: { entries: { main: { default: true }, ops: {} } },
93-
}),
94-
).toThrow("Set agents.defaults.systemAgent.agentId");
95-
});
96-
97-
it("resolves ambient owners through the system-agent chain", () => {
98-
const systemOwnedFleet = {
99-
agents: {
100-
ownership: "explicit" as const,
101-
defaults: { systemAgent: { agentId: "ops" } },
102-
entries: { ops: { agentDir: "/tmp/openclaw-ops-agent" }, research: {} },
103-
},
104-
} satisfies OpenClawConfig;
105-
106-
expect(tryResolveAmbientOwnerAgentId(systemOwnedFleet)).toBe("ops");
107-
expect(resolveAmbientOwnerAgentId(systemOwnedFleet)).toBe("ops");
108-
// Ambient dir resolution is the shared producer behind auth, model, and
109-
// doctor surfaces; before the system-agent leg it threw for these rosters.
110-
expect(resolveDefaultAgentDir(systemOwnedFleet)).toBe("/tmp/openclaw-ops-agent");
111-
89+
}).config as OpenClawConfig,
90+
expected: "beta",
91+
},
92+
{
93+
name: "legacy marker without a configured system agent",
94+
config: {
95+
agents: { entries: { alpha: { default: true }, beta: {} } },
96+
} satisfies OpenClawConfig,
97+
expected: "alpha",
98+
},
99+
{
100+
name: "sole agent",
101+
config: { agents: { entries: { solo: {} } } } satisfies OpenClawConfig,
102+
expected: "solo",
103+
},
104+
{
105+
name: "explicit requested agent before every configured owner",
106+
config: {
107+
agents: {
108+
defaults: { systemAgent: { agentId: "beta" } },
109+
entries: { alpha: { default: true }, beta: {}, gamma: {} },
110+
},
111+
} satisfies OpenClawConfig,
112+
requestedAgentId: " GAMMA ",
113+
expected: "gamma",
114+
},
115+
];
116+
117+
it.each(ambientOwnerCases)(
118+
"resolves ambient owner: $name",
119+
({ config, requestedAgentId, expected }) => {
120+
expect(tryResolveAmbientOwnerAgentId(config, requestedAgentId)).toBe(expected);
121+
expect(resolveAmbientOwnerAgentId(config, requestedAgentId)).toBe(expected);
122+
},
123+
);
124+
125+
it("fails closed with context when an ambient owner is ambiguous", () => {
112126
const ownerlessFleet = {
113127
agents: { ownership: "explicit" as const, entries: { ops: {}, research: {} } },
114128
} satisfies OpenClawConfig;
115129

116130
expect(tryResolveAmbientOwnerAgentId(ownerlessFleet)).toBeUndefined();
117131
expect(() => resolveAmbientOwnerAgentId(ownerlessFleet)).toThrow(AgentSelectionRequiredError);
118132
expect(() =>
119-
resolveAmbientOwnerAgentId(ownerlessFleet, {
133+
resolveAmbientOwnerAgentId(ownerlessFleet, undefined, {
120134
surface: "Talk relay ownership",
121135
hint: "Set talk.agentId.",
122136
}),
123137
).toThrow("Talk relay ownership");
138+
expect(() =>
139+
resolveAmbientOwnerAgentId(ownerlessFleet, undefined, {
140+
surface: "Talk relay ownership",
141+
hint: "Set talk.agentId.",
142+
}),
143+
).toThrow("Set talk.agentId.");
144+
});
145+
146+
it("resolves the default agent directory through the ambient owner", () => {
147+
const config = {
148+
agents: {
149+
defaults: { systemAgent: { agentId: "beta" } },
150+
entries: { alpha: { default: true }, beta: { agentDir: "/tmp/openclaw-beta-agent" } },
151+
},
152+
} satisfies OpenClawConfig;
153+
154+
expect(resolveDefaultAgentDir(config)).toBe("/tmp/openclaw-beta-agent");
124155
});
125156

126157
it("resolves defaults only for the rosterless implicit main agent", () => {

‎src/agents/agent-scope-config.ts‎

Lines changed: 9 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -219,48 +219,27 @@ export function tryResolveLegacyCompatibilityAgentId(cfg: OpenClawConfig): strin
219219
: tryResolveDefaultAgentId(cfg);
220220
}
221221

222-
/** Resolves the configured owner for ambient system work and explicit consults. */
223-
export function tryResolveSystemAgentTargetAgentId(
222+
/** Resolves the owner for ambient system work and explicit requests. */
223+
export function tryResolveAmbientOwnerAgentId(
224224
cfg: OpenClawConfig,
225225
requestedAgentId?: string,
226226
): string | undefined {
227-
const configuredAgentId =
227+
const explicitAgentId =
228228
normalizeOptionalString(requestedAgentId) ??
229229
normalizeOptionalString(cfg.agents?.defaults?.systemAgent?.agentId);
230-
return configuredAgentId ? normalizeAgentId(configuredAgentId) : tryResolveSoleAgentId(cfg);
231-
}
232-
233-
export function resolveSystemAgentTargetAgentId(
234-
cfg: OpenClawConfig,
235-
requestedAgentId?: string,
236-
context?: AgentSelectionContext,
237-
): string {
238-
const resolvedAgentId = tryResolveSystemAgentTargetAgentId(cfg, requestedAgentId);
239-
if (resolvedAgentId) {
240-
return resolvedAgentId;
241-
}
242-
return normalizeAgentId(
243-
resolveSoleAgentId(
244-
cfg,
245-
context ?? {
246-
surface: "system-agent consult routing",
247-
hint: "Set agents.defaults.systemAgent.agentId or pass an explicit consult agent id.",
248-
},
249-
),
250-
);
251-
}
252-
253-
/** Resolves the ambient system owner: shipped legacy default first, then the system-agent target. */
254-
export function tryResolveAmbientOwnerAgentId(cfg: OpenClawConfig): string | undefined {
255-
return tryResolveLegacyCompatibilityAgentId(cfg) ?? tryResolveSystemAgentTargetAgentId(cfg);
230+
// The documented system-agent owner is explicit config, so it precedes a stripped legacy marker.
231+
return explicitAgentId
232+
? normalizeAgentId(explicitAgentId)
233+
: tryResolveLegacyCompatibilityAgentId(cfg);
256234
}
257235

258236
/** Ambient owner for surfaces that must fail loudly rather than act on the wrong agent. */
259237
export function resolveAmbientOwnerAgentId(
260238
cfg: OpenClawConfig,
239+
requestedAgentId?: string,
261240
context?: AgentSelectionContext,
262241
): string {
263-
return tryResolveAmbientOwnerAgentId(cfg) ?? resolveSoleAgentId(cfg, context);
242+
return tryResolveAmbientOwnerAgentId(cfg, requestedAgentId) ?? resolveSoleAgentId(cfg, context);
264243
}
265244

266245
/**

‎src/agents/agent-scope.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,6 @@ export {
5252
resolveSoleAgentId,
5353
tryResolveAmbientOwnerAgentId,
5454
tryResolveLegacyCompatibilityAgentId,
55-
tryResolveSystemAgentTargetAgentId,
5655
tryResolveSoleAgentId,
5756
tryResolveDefaultAgentId,
5857
AgentSelectionRequiredError,

‎src/agents/context.lookup.test.ts‎

Lines changed: 28 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -377,23 +377,24 @@ describe("lookupContextTokens", () => {
377377
await flushAsyncWarmup();
378378

379379
expect(contextTestState.loadModelCatalogOwnerSnapshot).toHaveBeenCalledOnce();
380-
expect(contextTestState.loadModelCatalogOwnerSnapshot).toHaveBeenCalledWith(
381-
expect.objectContaining({
382-
config,
383-
agentDir: expect.any(String),
384-
readOnly: true,
385-
}),
386-
);
387-
expect(contextTestState.loadModelCatalogOwnerSnapshot.mock.calls[0]?.[0]).not.toHaveProperty(
388-
"workspaceDir",
389-
);
380+
expect(contextTestState.loadModelCatalogOwnerSnapshot).toHaveBeenCalledWith({
381+
config,
382+
readOnly: true,
383+
});
390384
expect(lookupContextTokens("anthropic/claude-opus-4.7-20260219")).toBe(
391385
ANTHROPIC_CONTEXT_1M_TOKENS,
392386
);
393387
});
394388

395389
it("keeps ordinary cache loading on the exact owner path", async () => {
396-
const config = createContextOverrideConfig("anthropic", "claude-opus-4.7-20260219", 200_000);
390+
const config = {
391+
...createContextOverrideConfig("anthropic", "claude-opus-4.7-20260219", 200_000),
392+
agents: {
393+
ownership: "explicit" as const,
394+
defaults: { systemAgent: { agentId: "beta" } },
395+
entries: { alpha: {}, beta: {} },
396+
},
397+
} satisfies OpenClawConfig;
397398
mockDiscoveryDeps([
398399
{
399400
id: "anthropic/claude-opus-4.7-20260219",
@@ -405,17 +406,25 @@ describe("lookupContextTokens", () => {
405406
const { ensureContextWindowCacheLoaded, lookupContextTokens } = await importContextModule();
406407
await ensureContextWindowCacheLoaded(config);
407408

408-
expect(contextTestState.loadModelCatalogOwnerSnapshot).toHaveBeenCalledWith(
409-
expect.objectContaining({ config, readOnly: true }),
410-
);
409+
expect(contextTestState.loadModelCatalogOwnerSnapshot).toHaveBeenCalledWith({
410+
config,
411+
readOnly: true,
412+
});
411413
expect(contextTestState.getPublishedModelCatalogOwnerSnapshot).not.toHaveBeenCalled();
412414
expect(
413415
lookupContextTokens("anthropic/claude-opus-4.7-20260219", { allowAsyncLoad: false }),
414416
).toBe(ANTHROPIC_CONTEXT_1M_TOKENS);
415417
});
416418

417419
it("warms from the current Gateway-published owner without hashing a fallback owner key", async () => {
418-
const requestedConfig = createContextOverrideConfig("synthetic", "stale-model", 111_000);
420+
const requestedConfig = {
421+
...createContextOverrideConfig("synthetic", "stale-model", 111_000),
422+
agents: {
423+
ownership: "explicit" as const,
424+
defaults: { systemAgent: { agentId: "beta" } },
425+
entries: { alpha: {}, beta: {} },
426+
},
427+
} satisfies OpenClawConfig;
419428
const publishedConfig = createContextOverrideConfig("synthetic", "current-model", 222_000);
420429
contextTestState.getPublishedModelCatalogOwnerSnapshot.mockReturnValueOnce({
421430
config: publishedConfig,
@@ -430,15 +439,10 @@ describe("lookupContextTokens", () => {
430439
await importContextModule();
431440
await prewarmContextWindowCacheAfterReady({ config: requestedConfig });
432441

433-
expect(contextTestState.getPublishedModelCatalogOwnerSnapshot).toHaveBeenCalledWith(
434-
expect.objectContaining({
435-
config: requestedConfig,
436-
allowGatewaySubagentBinding: true,
437-
}),
438-
);
439-
expect(
440-
contextTestState.getPublishedModelCatalogOwnerSnapshot.mock.calls[0]?.[0],
441-
).not.toHaveProperty("readOnly");
442+
expect(contextTestState.getPublishedModelCatalogOwnerSnapshot).toHaveBeenCalledWith({
443+
config: requestedConfig,
444+
allowGatewaySubagentBinding: true,
445+
});
442446
expect(contextTestState.loadModelCatalogOwnerSnapshot).not.toHaveBeenCalled();
443447
expect(
444448
lookupContextTokens("current-model", {

‎src/agents/context.ts‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import { getRuntimeConfig } from "../config/config.js";
55
import type { OpenClawConfig } from "../config/types.openclaw.js";
66
import { computeBackoff, type BackoffPolicy } from "../infra/backoff.js";
7-
import { resolveAgentDir, resolveDefaultAgentId } from "./agent-scope.js";
87
import {
98
applyConfiguredContextWindows,
109
type ContextWindowCatalog,
@@ -120,11 +119,8 @@ function ensureContextWindowCacheLoadedFromOwner(params: {
120119
: await (async () => {
121120
const { loadPreparedModelCatalogOwnerSnapshot } =
122121
await loadPreparedModelCatalogRuntime();
123-
const defaultAgentId = resolveDefaultAgentId(cfg);
124122
return await loadPreparedModelCatalogOwnerSnapshot({
125123
config: cfg,
126-
agentId: defaultAgentId,
127-
agentDir: resolveAgentDir(cfg, defaultAgentId),
128124
readOnly: true,
129125
}).then(
130126
(value) => ({ status: "fulfilled" as const, value }),
@@ -187,11 +183,8 @@ export async function prewarmContextWindowCacheAfterReady(params: {
187183
if (shouldStop()) {
188184
return;
189185
}
190-
const defaultAgentId = resolveDefaultAgentId(params.config);
191186
const owner = getPublishedPreparedModelCatalogOwnerSnapshot({
192187
config: params.config,
193-
agentId: defaultAgentId,
194-
agentDir: resolveAgentDir(params.config, defaultAgentId),
195188
allowGatewaySubagentBinding: true,
196189
});
197190
if (!owner) {

‎src/agents/heartbeat-system-prompt.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,31 @@ describe("resolveHeartbeatPromptForSystemPrompt", () => {
1818
).toBeDefined();
1919
});
2020

21+
it.each([
22+
{
23+
name: "explicit fleet",
24+
config: {
25+
agents: {
26+
ownership: "explicit" as const,
27+
defaults: { systemAgent: { agentId: "beta" } },
28+
entries: { alpha: {}, beta: {} },
29+
},
30+
},
31+
},
32+
{
33+
name: "legacy-marked fleet",
34+
config: {
35+
agents: {
36+
defaults: { systemAgent: { agentId: "beta" } },
37+
entries: { alpha: { default: true }, beta: {} },
38+
},
39+
},
40+
},
41+
])("includes ambient heartbeat guidance only for the system owner in an $name", ({ config }) => {
42+
expect(resolveHeartbeatPromptForSystemPrompt({ config, agentId: "beta" })).toBeDefined();
43+
expect(resolveHeartbeatPromptForSystemPrompt({ config, agentId: "alpha" })).toBeUndefined();
44+
});
45+
2146
it("omits the heartbeat section when the default cadence is disabled", () => {
2247
expect(
2348
resolveHeartbeatPromptForSystemPrompt({

0 commit comments

Comments
 (0)