Skip to content

Commit 7f0a87d

Browse files
authored
feat(agents): eager delegation default in the main session + coalesced session-state wakes (#125691)
* feat(agents): default to eager delegation in the main session The delegation prompt section now defaults to "prefer" in each agent's canonical main session and "suggest" elsewhere; explicit config wins in both directions. The section is rewritten to be token-leaner and now covers the hidden-vs-visible spawn distinction (hidden subagents are invisible and auto-archived; deliverable-bearing work spawns visible=true and replies with the link) plus the run-end notification contract. The Messaging spawn-mechanics line is suppressed when the Delegation section renders, and the stable Tooling visible:true hint is aligned with the new guidance. * perf(sessions): coalesce session-state wake bursts Watched-session change notices woke the watcher's main session with the generic 250ms heartbeat coalesce, so a burst of changes across several watched sessions produced one wake per change. Wakes now coalesce for 20s; notices are already queued and deduped, so none are lost. * test(agents): regenerate prompt snapshots after rebase * test(sessions,agents): update sibling assertions for coalesced wakes and visible guidance session-state-events tests advance timers past the new 20s wake coalesce window; the sessions_spawn schema test tracks the updated visible description.
1 parent 6a97ba4 commit 7f0a87d

19 files changed

Lines changed: 225 additions & 96 deletions

‎docs/concepts/system-prompt.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ Tooling also carries long-running-work guidance:
5959
- for larger tasks, prefer `sessions_spawn`; sub-agent completion is push-based and auto-announces back to the requester
6060
- do not poll `subagents list` / `sessions_list` in a loop just to wait for completion
6161

62-
`agents.defaults.subagents.delegationMode` (default `"suggest"`) can strengthen this. `"prefer"` adds a dedicated **Sub-Agent Delegation** section telling the main agent to act as a responsive coordinator and push anything more involved than a direct reply through `sessions_spawn`. This is prompt-only; tool policy still controls whether `sessions_spawn` is available.
62+
`agents.defaults.subagents.delegationMode` can strengthen this. With no explicit setting, OpenClaw uses `"prefer"` in each agent's main session and `"suggest"` elsewhere; an explicit default or per-agent override always wins. `"prefer"` adds a dedicated **Delegation** section telling the agent to stay responsive, use hidden sub-agents for internal legwork, and use visible sidebar sessions for work the user will follow or return to. This is prompt-only; tool policy still controls whether `sessions_spawn` is available.
6363

6464
At the `ultra` thinking level, a **Proactive Sub-Agent Orchestration** section is also added when `sessions_spawn` is available: it tells the model to parallelize independent investigation, implementation, and verification through sub-agents, keep simple or tightly coupled work local, give each sub-agent a bounded objective, and synthesize results before replying.
6565

‎docs/tools/subagents.md‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -168,12 +168,14 @@ in the tool result: `resolvedModel` contains the applied model ref and
168168

169169
### Delegation prompt mode
170170

171-
`agents.defaults.subagents.delegationMode` controls prompt guidance only; it does not change tool policy or enforce delegation.
171+
`agents.defaults.subagents.delegationMode` controls prompt guidance only; it does not change tool policy or enforce delegation. With no explicit setting, OpenClaw uses `prefer` in each agent's main session and `suggest` in every other session.
172172

173-
- `suggest` (default): keep the standard prompt nudge to use sub-agents for larger or slower work.
174-
- `prefer`: tell the main agent to stay responsive and delegate anything more involved than a direct reply through `sessions_spawn`.
173+
- `suggest`: keep the standard prompt nudge to use sub-agents for larger or slower work.
174+
- `prefer`: tell the agent to stay responsive and delegate anything more involved than a direct reply through `sessions_spawn`.
175175

176-
Per-agent override: `agents.entries.*.subagents.delegationMode`.
176+
An explicit default or per-agent setting always wins, including `suggest` in a main session and `prefer` elsewhere. Per-agent overrides use `agents.entries.*.subagents.delegationMode`.
177+
178+
In `prefer` mode, hidden sub-agents are for internal legwork that the user does not need to follow. Work the user will watch or return to, or work with its own deliverable such as a URL, PR, or report, should use `sessions_spawn` with `visible: true` so it remains in the sidebar.
177179

178180
```json5
179181
{
@@ -247,7 +249,7 @@ Per-agent override: `agents.entries.*.subagents.delegationMode`.
247249
`fork` branches the requester's current transcript into the child session. Native sub-agents only. Thread-bound spawns default to `fork`; non-thread spawns default to `isolated`. A visible fork must target the same agent as the requester.
248250
</ParamField>
249251
<ParamField path="visible" type="boolean" default="false">
250-
Create a persistent dashboard session that the user can open in the Control UI. Visible spawns support only `runtime: "subagent"` and always keep the created session.
252+
Create a persistent dashboard session for work the user will watch or return to, or when they ask for a thread. Visible spawns support only `runtime: "subagent"` and always keep the created session.
251253
</ParamField>
252254
<ParamField path="worktree" type="boolean" default="false">
253255
Provision a managed git worktree for the new dashboard session. Requires `visible: true`.
@@ -266,7 +268,7 @@ their latest assistant turn back to the requester; external delivery stays with
266268
the parent/requester agent.
267269
</Warning>
268270

269-
With `visible: true`, `model`, `cwd`, and a same-agent `context: "fork"` are supported. Use this mode when the user asks to create or open a thread that should appear in the sidebar. A sandboxed target restricts `cwd` to that agent's workspace. Non-admin callers may use `cwd` only inside a configured agent workspace. Omit `cwd` to use the target agent workspace; for another repository, ask the operator to start the session from a registered project. Do not replace a rejected persistent spawn with the synchronous `openclaw agent` CLI, whose command deadline defaults to 600 seconds. Thread binding, `mode`, thinking overrides, `lightContext`, `attachments`, and `attachAs` are unavailable on this path because visible sessions are persistent dashboard sessions created through `sessions.create`. The new dashboard child inherits the requester's effective tool-policy ceiling before its first turn. Session listing and addressing obey `tools.sessions.visibility`; the default `tree` scope covers the current session and its own spawn subtree, while the main session can reach every same-agent session unless `self` or the sandbox spawned-only clamp applies. See [Session tools](/concepts/session-tool#visibility) and [Managed worktrees](/concepts/managed-worktrees).
271+
With `visible: true`, `model`, `cwd`, and a same-agent `context: "fork"` are supported. Use this mode for work the user will watch or return to, or when they ask for a thread that should appear in the sidebar. A sandboxed target restricts `cwd` to that agent's workspace. Non-admin callers may use `cwd` only inside a configured agent workspace. Omit `cwd` to use the target agent workspace; for another repository, ask the operator to start the session from a registered project. Do not replace a rejected persistent spawn with the synchronous `openclaw agent` CLI, whose command deadline defaults to 600 seconds. Thread binding, `mode`, thinking overrides, `lightContext`, `attachments`, and `attachAs` are unavailable on this path because visible sessions are persistent dashboard sessions created through `sessions.create`. The new dashboard child inherits the requester's effective tool-policy ceiling before its first turn. Session listing and addressing obey `tools.sessions.visibility`; the default `tree` scope covers the current session and its own spawn subtree, while the main session can reach every same-agent session unless `self` or the sandbox spawned-only clamp applies. See [Session tools](/concepts/session-tool#visibility) and [Managed worktrees](/concepts/managed-worktrees).
270272

271273
A visible spawn is attributed to the requesting agent: the new session's creator and initial owner is that agent, shown with its configured identity name and avatar in the sidebar. The accepted result doubles as a receipt with `childSessionKey`, `runId`, a Control UI `sessionUrl` (omitted when the Control UI is disabled), and an `owner` record. When acknowledging the spawn in a channel, put the session URL on the first line and `Owner: <label>` on the second so the user can open the session and see who is responsible. Owners can be reassigned later; see [Multi-user mode](/concepts/multi-user#agent-spawned-sessions).
272274

‎src/agents/cli-runner/helpers.system-prompt.test.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,7 @@ describe("buildCliAgentSystemPrompt", () => {
3131
modelDisplay: "test/model",
3232
});
3333

34-
expect(prompt).toContain("## Sub-Agent Delegation");
35-
expect(prompt).toContain("Mode: prefer");
34+
expect(prompt).toContain("## Delegation");
3635
expect(prompt).not.toContain("For long waits, avoid rapid poll loops");
3736
expect(prompt).not.toContain("Larger work: use `sessions_spawn`");
3837
expect(prompt).not.toContain("Do not poll `subagents list` / `sessions_list` in a loop");

‎src/agents/embedded-agent-runner/system-prompt.test.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -119,8 +119,7 @@ describe("buildEmbeddedSystemPrompt", () => {
119119
userDate: "2026-01-05",
120120
});
121121

122-
expect(prompt).toContain("## Sub-Agent Delegation");
123-
expect(prompt).toContain("Mode: prefer");
122+
expect(prompt).toContain("## Delegation");
124123
});
125124

126125
it("uses deferred capability names without listing them as visible tools", () => {
@@ -152,8 +151,7 @@ describe("buildEmbeddedSystemPrompt", () => {
152151
userDate: "2026-01-05",
153152
});
154153

155-
expect(prompt).toContain("## Sub-Agent Delegation");
156-
expect(prompt).toContain("Mode: prefer");
154+
expect(prompt).toContain("## Delegation");
157155
expect(prompt).not.toContain("- sessions_spawn: spawn an isolated sub-agent session");
158156
});
159157

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

Lines changed: 56 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,68 @@ vi.mock("../tts/tts-settings.js", () => ({
1010
setTtsMachinePrefsPathResolver: vi.fn(),
1111
}));
1212

13-
function buildPrompt(config: OpenClawConfig, agentId = "main"): string {
13+
function buildPrompt(config: OpenClawConfig, agentId = "main", sessionKey?: string): string {
1414
return buildConfiguredAgentSystemPrompt({
1515
config,
1616
agentId,
1717
workspaceDir: "/tmp/openclaw",
1818
toolNames: ["sessions_spawn", "subagents"],
19+
runtimeInfo: { sessionKey },
1920
});
2021
}
2122

2223
describe("buildConfiguredAgentSystemPrompt", () => {
23-
it("defaults sub-agent delegation mode to suggest", () => {
24-
expect(buildPrompt({})).not.toContain("Mode: prefer");
24+
it.each([
25+
{
26+
name: "prefers delegation in the canonical main session",
27+
config: {} satisfies OpenClawConfig,
28+
sessionKey: "agent:main:main",
29+
expected: true,
30+
},
31+
{
32+
name: "suggests delegation outside the canonical main session",
33+
config: {} satisfies OpenClawConfig,
34+
sessionKey: "agent:main:slack:channel:C01234567",
35+
expected: false,
36+
},
37+
{
38+
name: "recognizes a custom canonical main key",
39+
config: { session: { mainKey: "inbox" } } satisfies OpenClawConfig,
40+
sessionKey: "agent:main:inbox",
41+
expected: true,
42+
},
43+
{
44+
name: "recognizes the global-scope canonical main key",
45+
config: { session: { scope: "global" } } satisfies OpenClawConfig,
46+
sessionKey: "global",
47+
expected: true,
48+
},
49+
{
50+
name: "suggests delegation without a render session key",
51+
config: {} satisfies OpenClawConfig,
52+
sessionKey: undefined,
53+
expected: false,
54+
},
55+
{
56+
name: "honors explicit prefer outside the canonical main session",
57+
config: {
58+
agents: { defaults: { subagents: { delegationMode: "prefer" } } },
59+
} satisfies OpenClawConfig,
60+
sessionKey: "agent:main:dashboard:project",
61+
expected: true,
62+
},
63+
{
64+
name: "honors explicit suggest in the canonical main session",
65+
config: {
66+
agents: { defaults: { subagents: { delegationMode: "suggest" } } },
67+
} satisfies OpenClawConfig,
68+
sessionKey: "agent:main:main",
69+
expected: false,
70+
},
71+
])("$name", ({ config, sessionKey, expected }) => {
72+
const prompt = buildPrompt(config, "main", sessionKey);
73+
expect(prompt.includes("## Delegation")).toBe(expected);
74+
expect(prompt.includes("- Subagents: `sessions_spawn`")).toBe(!expected);
2575
});
2676

2777
it("inherits default sub-agent delegation mode", () => {
@@ -35,7 +85,7 @@ describe("buildConfiguredAgentSystemPrompt", () => {
3585
},
3686
} satisfies OpenClawConfig;
3787

38-
expect(buildPrompt(config)).toContain("Mode: prefer");
88+
expect(buildPrompt(config)).toContain("## Delegation");
3989
});
4090

4191
it("lets per-agent sub-agent delegation mode override defaults", () => {
@@ -57,7 +107,7 @@ describe("buildConfiguredAgentSystemPrompt", () => {
57107
},
58108
} satisfies OpenClawConfig;
59109

60-
expect(buildPrompt(config, "coordinator")).toContain("Mode: prefer");
110+
expect(buildPrompt(config, "coordinator")).toContain("## Delegation");
61111
});
62112

63113
it("applies config-backed prompt parameters through the canonical facade", () => {
@@ -76,7 +126,6 @@ describe("buildConfiguredAgentSystemPrompt", () => {
76126
toolNames: ["sessions_spawn", "subagents"],
77127
});
78128

79-
expect(prompt).toContain("## Sub-Agent Delegation");
80-
expect(prompt).toContain("Mode: prefer");
129+
expect(prompt).toContain("## Delegation");
81130
});
82131
});

‎src/agents/system-prompt-config.ts‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55
* prompt so callers do not duplicate owner, TTS, alias, memory, or FS policy.
66
*/
77
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
8+
import { resolveCanonicalMainSessionKey } from "../config/sessions/main-session-key.js";
89
import type { OpenClawConfig } from "../config/types.openclaw.js";
10+
import { parseCronRunScopeSuffix } from "../sessions/session-key-utils.js";
911
import { buildTtsSystemPromptHint } from "../tts/tts-settings.js";
1012
import { resolveAgentConfig } from "./agent-scope.js";
1113
import { resolveOwnerDisplaySetting } from "./owner-display.js";
@@ -49,19 +51,29 @@ function buildModelAliasLines(cfg?: OpenClawConfig) {
4951
function resolveAgentSystemPromptConfig(params: {
5052
config?: OpenClawConfig;
5153
agentId?: string;
54+
sessionKey?: string;
5255
sourceReplyDeliveryMode?: AgentSystemPromptRenderParams["sourceReplyDeliveryMode"];
5356
}): ResolvedAgentSystemPromptConfig {
54-
const { config, agentId, sourceReplyDeliveryMode } = params;
57+
const { config, agentId, sessionKey, sourceReplyDeliveryMode } = params;
5558
const ownerDisplay = resolveOwnerDisplaySetting(config);
5659
const agentSubagents =
5760
config && agentId ? resolveAgentConfig(config, agentId)?.subagents : undefined;
61+
const configuredDelegationMode =
62+
agentSubagents?.delegationMode ?? config?.agents?.defaults?.subagents?.delegationMode;
63+
const baseSessionKey = parseCronRunScopeSuffix(sessionKey).baseSessionKey;
64+
const isMainSession =
65+
agentId !== undefined &&
66+
baseSessionKey !== undefined &&
67+
baseSessionKey ===
68+
resolveCanonicalMainSessionKey({
69+
agentId,
70+
mainKey: config?.session?.mainKey,
71+
sessionScope: config?.session?.scope,
72+
});
5873
return {
5974
ownerDisplay: ownerDisplay.ownerDisplay,
6075
ownerDisplaySecret: ownerDisplay.ownerDisplaySecret,
61-
subagentDelegationMode:
62-
agentSubagents?.delegationMode ??
63-
config?.agents?.defaults?.subagents?.delegationMode ??
64-
"suggest",
76+
subagentDelegationMode: configuredDelegationMode ?? (isMainSession ? "prefer" : "suggest"),
6577
ttsHint: config
6678
? buildTtsSystemPromptHint(config, agentId, {
6779
messageToolOnly: sourceReplyDeliveryMode === "message_tool_only",
@@ -80,6 +92,7 @@ export function buildConfiguredAgentSystemPrompt(params: ConfiguredAgentSystemPr
8092
? resolveAgentSystemPromptConfig({
8193
config,
8294
agentId,
95+
sessionKey: renderParams.runtimeInfo?.sessionKey,
8396
sourceReplyDeliveryMode: renderParams.sourceReplyDeliveryMode,
8497
})
8598
: {};

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

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1051,7 +1051,7 @@ describe("buildAgentSystemPrompt", () => {
10511051
expect(prompt).toContain(
10521052
"Never restart the Gateway through shell commands or write your own config.",
10531053
);
1054-
expect(prompt).toContain("`visible:true` only web/app user or asked.");
1054+
expect(prompt).toContain("`visible:true` for work the user follows or asked for; else hidden.");
10551055
});
10561056

10571057
it("omits openclaw delegation guidance without the tool", () => {
@@ -1380,15 +1380,36 @@ describe("buildAgentSystemPrompt", () => {
13801380
subagentDelegationMode: "prefer",
13811381
});
13821382

1383-
expect(defaultPrompt).not.toContain("## Sub-Agent Delegation");
1384-
expect(preferPrompt).toContain("## Sub-Agent Delegation");
1385-
expect(preferPrompt).toContain("Mode: prefer");
1386-
expect(preferPrompt).toContain("You coordinate; children do non-trivial work");
1387-
expect(preferPrompt).toContain("Otherwise use `sessions_spawn`");
1388-
expect(preferPrompt).toContain("objective, output, inputs/files");
1389-
expect(preferPrompt).toContain("lowercase `taskName` (underscores/hyphens)");
1390-
expect(preferPrompt).toContain("Child output = evidence");
1383+
expect(defaultPrompt).not.toContain("## Delegation");
1384+
expect(preferPrompt).toContain("## Delegation");
1385+
expect(preferPrompt).toContain("Stay responsive: incoming messages wait on your current turn");
1386+
expect(preferPrompt).toContain("Multi-step or slow work");
1387+
expect(preferPrompt).toContain("objective, output, write scope, verification");
1388+
expect(preferPrompt).toContain("spawn `visible=true`");
1389+
expect(preferPrompt).toContain("Child output is evidence");
13911390
expect(preferPrompt).toContain("`subagents(action=list)` only for requested status");
1391+
expect(preferPrompt).not.toContain("- Subagents: `sessions_spawn`");
1392+
});
1393+
1394+
it("keeps prefer delegation out of minimal prompts and conditions follow-up guidance", () => {
1395+
const buildPreferPrompt = (toolNames: string[], promptMode?: "minimal") =>
1396+
buildAgentSystemPrompt({
1397+
workspaceDir: "/tmp/openclaw",
1398+
toolNames,
1399+
promptMode,
1400+
subagentDelegationMode: "prefer",
1401+
});
1402+
1403+
const withSend = buildPreferPrompt(["sessions_spawn", "sessions_send"]);
1404+
const withoutSend = buildPreferPrompt(["sessions_spawn"]);
1405+
const minimal = buildPreferPrompt(["sessions_spawn", "sessions_send"], "minimal");
1406+
1407+
expect(withSend).toContain(
1408+
"later turns in a kept session do not report back; follow up via `sessions_send`.",
1409+
);
1410+
expect(withoutSend).toContain("later turns in a kept session do not report back.");
1411+
expect(withoutSend).not.toContain("follow up via `sessions_send`");
1412+
expect(minimal).not.toContain("## Delegation");
13921413
});
13931414

13941415
it("adds run-scoped Ultra orchestration only when sessions_spawn is callable", () => {
@@ -1441,7 +1462,7 @@ describe("buildAgentSystemPrompt", () => {
14411462
subagentDelegationMode: "prefer",
14421463
});
14431464

1444-
expect(prompt).not.toContain("## Sub-Agent Delegation");
1465+
expect(prompt).not.toContain("## Delegation");
14451466
expect(prompt).toContain("- Subagents:");
14461467
});
14471468

0 commit comments

Comments
 (0)