Skip to content

Commit 4f31cbb

Browse files
committed
refactor: share parent fork policy
1 parent d049af6 commit 4f31cbb

18 files changed

Lines changed: 233 additions & 68 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5808,7 +5808,7 @@ Docs: https://docs.openclaw.ai
58085808
- Slack/Threading: when `replyToMode="all"` auto-threads top-level Slack DMs, seed the thread session key from the message `ts` so the initial message and later replies share the same isolated `:thread:` session instead of falling back to base DM context. (#26849) Thanks @calder-sandy.
58095809
- Agents/Subagents delivery: refactor subagent completion announce dispatch into an explicit queue/direct/fallback state machine, recover outbound channel-plugin resolution in cold/stale plugin-registry states across announce/message/gateway send paths, finalize cleanup bookkeeping when announce flow rejects, and treat Telegram sends without `message_id` as delivery failures (instead of false-success `"unknown"` IDs). (#26867, #25961, #26803, #25069, #26741) Thanks @SmithLabsLLC and @docaohieu2808.
58105810
- Telegram/Webhook: pre-initialize webhook bots, switch webhook processing to callback-mode JSON handling, and preserve full near-limit payload reads under delayed handlers to prevent webhook request hangs and dropped updates. (#26156).
5811-
- Slack/Session threads: prevent oversized parent-session inheritance from silently bricking new thread sessions, surface embedded context-overflow empty-result failures to users, and add configurable `session.parentForkMaxTokens` (default `100000`, `0` disables). (#26912) Thanks @markshields-tl.
5811+
- Slack/Session threads: prevent oversized parent-session inheritance from silently bricking new thread sessions, surface embedded context-overflow empty-result failures to users, and share the PI parent-fork fallback between channel threads and subagents. The legacy `session.parentForkMaxTokens` compatibility guard remains available but is no longer the preferred tuning surface. (#26912) Thanks @markshields-tl.
58125812
- Cron/Message multi-account routing: honor explicit `delivery.accountId` for isolated cron delivery resolution, and when `message.send` omits `accountId`, fall back to the sending agent's bound channel account instead of defaulting to the global account. (#27015, #26975) Thanks @lbo728 and @stakeswky.
58135813
- Gateway/Message media roots: thread `agentId` through gateway `send` RPC and prefer explicit `agentId` over session/default resolution so non-default agent workspace media sends no longer fail with `LocalMediaAccessError`; added regression coverage for agent precedence and blank-agent fallback. (#23249) Thanks @Sid-Qin.
58145814
- Followups/Routing: when explicit origin routing fails, allow same-channel fallback dispatch (while still blocking cross-channel fallback) so followup replies do not get dropped on transient origin-adapter failures. (#26109) Thanks @Sid-Qin.
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
d0b1fc318d2f737c91c21ffffae2fe12197b4ba6d49859c4786ecbc586cf5a82 config-baseline.json
2-
3f9c52903905d82d4b4ca9dbda530cac2e059870b08c69965099ebcd09a270a3 config-baseline.core.json
1+
f40d6dea3b81c42d5af9e340f091d34b9e39321d171fade6115da594ba90522f config-baseline.json
2+
40b1f91714d6f17e2718ea5d34c135550f5a39fe47f781cddc153cf3a59fe2e7 config-baseline.core.json
33
f42329d45c095881bd226bdb192c235980658fd250606d0c0badc2b12f12f5d3 config-baseline.channel.json
44
af71b84b2411d8ccabcc6e09de0ee41f8212ff9869a6677698b6e7e3afdfaa47 config-baseline.plugin.json

‎docs/gateway/config-agents.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1174,7 +1174,6 @@ See [Multi-Agent Sandbox & Tools](/tools/multi-agent-sandbox-tools) for preceden
11741174
},
11751175
resetTriggers: ["/new", "/reset"],
11761176
store: "~/.openclaw/agents/{agentId}/sessions/sessions.json",
1177-
parentForkMaxTokens: 100000, // skip parent-thread fork above this token count (0 disables)
11781177
maintenance: {
11791178
mode: "warn", // warn | enforce
11801179
pruneAfter: "30d",
@@ -1211,9 +1210,10 @@ See [Multi-Agent Sandbox & Tools](/tools/multi-agent-sandbox-tools) for preceden
12111210
- **`identityLinks`**: map canonical ids to provider-prefixed peers for cross-channel session sharing. Dock commands such as `/dock_discord` use the same map to switch the active session's reply route to another linked channel peer; see [Channel docking](/concepts/channel-docking).
12121211
- **`reset`**: primary reset policy. `daily` resets at `atHour` local time; `idle` resets after `idleMinutes`. When both configured, whichever expires first wins. Daily reset freshness uses the session row's `sessionStartedAt`; idle reset freshness uses `lastInteractionAt`. Background/system-event writes such as heartbeat, cron wakeups, exec notifications, and gateway bookkeeping can update `updatedAt`, but they do not keep daily/idle sessions fresh.
12131212
- **`resetByType`**: per-type overrides (`direct`, `group`, `thread`). Legacy `dm` accepted as alias for `direct`.
1214-
- **`parentForkMaxTokens`**: max parent-session `totalTokens` allowed when creating a forked thread session (default `100000`).
1215-
- If parent `totalTokens` is above this value, OpenClaw starts a fresh thread session instead of inheriting parent transcript history.
1216-
- Set `0` to disable this guard and always allow parent forking.
1213+
- **`parentForkMaxTokens`**: deprecated compatibility guard for the historical parent fork ceiling (default `100000`).
1214+
- Channel thread sessions and subagent `context="fork"` now use the same parent fork decision path.
1215+
- When the active parent branch is too large, OpenClaw starts with isolated context instead of failing or inheriting unusable history.
1216+
- Set `0` only if you intentionally want to disable this guard.
12171217
- **`mainKey`**: legacy field. Runtime always uses `"main"` for the main direct-chat bucket.
12181218
- **`agentToAgent.maxPingPongTurns`**: maximum reply-back turns between agents during agent-to-agent exchanges (integer, range: `0`–`5`). `0` disables ping-pong chaining.
12191219
- **`sendPolicy`**: match by `channel`, `chatType` (`direct|group|channel`, with legacy `dm` alias), `keyPrefix`, or `rawKeyPrefix`. First deny wins.

‎docs/reference/session-management-compaction.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ Rules of thumb:
148148
- **Daily reset** (default 4:00 AM local time on the gateway host) creates a new `sessionId` on the next message after the reset boundary.
149149
- **Idle expiry** (`session.reset.idleMinutes` or legacy `session.idleMinutes`) creates a new `sessionId` when a message arrives after the idle window. When daily + idle are both configured, whichever expires first wins.
150150
- **System events** (heartbeat, cron wakeups, exec notifications, gateway bookkeeping) may mutate the session row but do not extend daily/idle reset freshness. Reset rollover discards queued system-event notices for the previous session before the fresh prompt is built.
151-
- **Thread parent fork guard** (`session.parentForkMaxTokens`, default `100000`) skips parent transcript forking when the parent session is already too large; the new thread starts fresh. Set `0` to disable.
151+
- **Parent fork policy** uses PI's active branch when creating a thread or subagent fork. If that branch is too large, OpenClaw starts the child with isolated context instead of failing or inheriting unusable history. The legacy `session.parentForkMaxTokens` key remains as a deprecated compatibility guard; set `0` only if you intentionally want to disable it.
152152

153153
Implementation detail: the decision happens in `initSessionState()` in `src/auto-reply/reply/session.ts`.
154154

‎src/agents/openclaw-tools.subagents.sessions-spawn.test-harness.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,10 @@ export async function getSessionsSpawnTool(opts: CreateOpenClawToolsOpts) {
194194
compact: async () => ({ ok: true, compacted: false }),
195195
ingest: async () => ({ ingested: false }),
196196
}),
197-
resolveParentForkMaxTokens: () => 100_000,
197+
resolveParentForkDecision: async () => ({
198+
status: "fork",
199+
maxTokens: 100_000,
200+
}),
198201
forkSessionFromParent: async () => ({
199202
sessionId: "forked-session-id",
200203
sessionFile: "/tmp/forked-session.jsonl",

‎src/agents/subagent-spawn.context.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,37 @@ describe("sessions_spawn context modes", () => {
115115
);
116116
});
117117

118+
it("falls back to isolated context when requested fork is too large", async () => {
119+
const store: SessionStore = {
120+
main: {
121+
sessionId: "parent-session-id",
122+
sessionFile: "/tmp/parent-session.jsonl",
123+
updatedAt: 1,
124+
totalTokens: 170_000,
125+
},
126+
};
127+
usePersistentStoreMock(store);
128+
const prepareSubagentSpawn = vi.fn(async () => undefined);
129+
resolveContextEngineMock.mockResolvedValue({ prepareSubagentSpawn });
130+
131+
const result = await spawnSubagentDirect(
132+
{ task: "inspect the current thread", context: "fork" },
133+
{ agentSessionKey: "main" },
134+
);
135+
136+
expect(result).toMatchObject({ status: "accepted", runId: "run-1" });
137+
expect(result.note).toContain("Parent context is too large to fork");
138+
expect(forkSessionFromParentMock).not.toHaveBeenCalled();
139+
expect(prepareSubagentSpawn).toHaveBeenCalledWith(
140+
expect.objectContaining({
141+
parentSessionKey: "main",
142+
childSessionKey: result.childSessionKey,
143+
contextMode: "isolated",
144+
parentSessionId: "parent-session-id",
145+
}),
146+
);
147+
});
148+
118149
it("forks by default for thread-bound subagent sessions", async () => {
119150
const store: SessionStore = {
120151
main: {

‎src/agents/subagent-spawn.runtime.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ export { getRuntimeConfig } from "../config/config.js";
66
export { mergeSessionEntry, updateSessionStore } from "../config/sessions.js";
77
export {
88
forkSessionFromParent,
9-
resolveParentForkMaxTokens,
9+
resolveParentForkDecision,
10+
type ParentForkDecision,
1011
} from "../auto-reply/reply/session-fork.js";
1112
export { ensureContextEnginesInitialized } from "../context-engine/init.js";
1213
export { resolveContextEngine } from "../context-engine/registry.js";

‎src/agents/subagent-spawn.test-helpers.ts‎

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ export async function loadSubagentSpawnModuleForTest(params: {
121121
updateSessionStoreMock?: MockFn;
122122
forkSessionFromParentMock?: MockFn;
123123
resolveContextEngineMock?: MockFn;
124-
resolveParentForkMaxTokensMock?: MockFn;
124+
resolveParentForkDecisionMock?: MockFn;
125125
pruneLegacyStoreKeysMock?: MockFn;
126126
registerSubagentRunMock?: MockFn;
127127
emitSessionLifecycleEventMock?: MockFn;
@@ -182,7 +182,37 @@ export async function loadSubagentSpawnModuleForTest(params: {
182182
ensureContextEnginesInitialized:
183183
params.ensureContextEnginesInitializedMock ?? (() => undefined),
184184
resolveContextEngine: params.resolveContextEngineMock ?? (async () => ({})),
185-
resolveParentForkMaxTokens: params.resolveParentForkMaxTokensMock ?? (() => 100_000),
185+
resolveParentForkDecision:
186+
params.resolveParentForkDecisionMock ??
187+
(async (forkParams: {
188+
cfg?: { session?: { parentForkMaxTokens?: unknown } };
189+
parentEntry?: { totalTokens?: unknown };
190+
}) => {
191+
const configured = forkParams.cfg?.session?.parentForkMaxTokens;
192+
const maxTokens =
193+
typeof configured === "number" && Number.isFinite(configured) && configured >= 0
194+
? Math.floor(configured)
195+
: 100_000;
196+
const parentTokens =
197+
typeof forkParams.parentEntry?.totalTokens === "number" &&
198+
Number.isFinite(forkParams.parentEntry.totalTokens)
199+
? Math.floor(forkParams.parentEntry.totalTokens)
200+
: undefined;
201+
if (maxTokens > 0 && typeof parentTokens === "number" && parentTokens > maxTokens) {
202+
return {
203+
status: "skip",
204+
reason: "parent-too-large",
205+
maxTokens,
206+
parentTokens,
207+
message: `Parent context is too large to fork (${parentTokens}/${maxTokens} tokens); starting with isolated context instead.`,
208+
};
209+
}
210+
return {
211+
status: "fork",
212+
maxTokens,
213+
...(typeof parentTokens === "number" ? { parentTokens } : {}),
214+
};
215+
}),
186216
mergeSessionEntry: (
187217
current: Record<string, unknown> | undefined,
188218
next: Record<string, unknown>,

‎src/agents/subagent-spawn.ts‎

Lines changed: 43 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -56,13 +56,13 @@ import {
5656
normalizeDeliveryContext,
5757
pruneLegacyStoreKeys,
5858
ensureContextEnginesInitialized,
59+
resolveParentForkDecision,
5960
resolveAgentConfig,
6061
resolveContextEngine,
6162
resolveDisplaySessionKey,
6263
resolveGatewaySessionStoreTarget,
6364
resolveInternalSessionKey,
6465
resolveMainSessionAlias,
65-
resolveParentForkMaxTokens,
6666
resolveSandboxRuntimeStatus,
6767
updateSessionStore,
6868
isAdminOnlyMethod,
@@ -96,7 +96,7 @@ type SubagentSpawnDeps = {
9696
getRuntimeConfig: typeof getRuntimeConfig;
9797
ensureContextEnginesInitialized: typeof ensureContextEnginesInitialized;
9898
resolveContextEngine: typeof resolveContextEngine;
99-
resolveParentForkMaxTokens: typeof resolveParentForkMaxTokens;
99+
resolveParentForkDecision: typeof resolveParentForkDecision;
100100
updateSessionStore: typeof updateSessionStore;
101101
};
102102

@@ -107,7 +107,7 @@ const defaultSubagentSpawnDeps: SubagentSpawnDeps = {
107107
getRuntimeConfig,
108108
ensureContextEnginesInitialized,
109109
resolveContextEngine,
110-
resolveParentForkMaxTokens,
110+
resolveParentForkDecision,
111111
updateSessionStore,
112112
};
113113

@@ -306,13 +306,20 @@ function resolveStoreEntryByKeys(
306306
}
307307

308308
type PreparedSpawnContext =
309-
| { status: "ok"; mode: "isolated"; parentEntry?: SessionEntry; childEntry?: SessionEntry }
309+
| {
310+
status: "ok";
311+
mode: "isolated";
312+
parentEntry?: SessionEntry;
313+
childEntry?: SessionEntry;
314+
forkFallbackNote?: string;
315+
}
310316
| {
311317
status: "ok";
312318
mode: "fork";
313319
parentEntry: SessionEntry;
314320
childEntry?: SessionEntry;
315321
forked: { sessionId: string; sessionFile: string };
322+
forkFallbackNote?: never;
316323
}
317324
| { status: "error"; error: string };
318325

@@ -338,7 +345,7 @@ async function prepareSubagentSessionContext(params: {
338345

339346
let parentEntry: SessionEntry | undefined;
340347
let childEntry: SessionEntry | undefined;
341-
const forkMaxTokens = subagentSpawnDeps.resolveParentForkMaxTokens(params.cfg);
348+
let forkFallbackNote: string | undefined;
342349
const sessionsDir = path.dirname(parentTarget.storePath);
343350

344351
try {
@@ -356,14 +363,14 @@ async function prepareSubagentSessionContext(params: {
356363
'context="fork" requested but the requester session transcript is not available.',
357364
);
358365
}
359-
const parentTokens =
360-
typeof parentEntry.totalTokens === "number" && Number.isFinite(parentEntry.totalTokens)
361-
? parentEntry.totalTokens
362-
: 0;
363-
if (forkMaxTokens > 0 && parentTokens > forkMaxTokens) {
364-
throw new Error(
365-
`context="fork" requested but requester context is too large to fork (${parentTokens}/${forkMaxTokens} tokens). Use context="isolated" or compact first.`,
366-
);
366+
const forkDecision = await subagentSpawnDeps.resolveParentForkDecision({
367+
cfg: params.cfg,
368+
parentEntry,
369+
storePath: parentTarget.storePath,
370+
});
371+
if (forkDecision.status === "skip") {
372+
forkFallbackNote = forkDecision.message;
373+
return null;
367374
}
368375

369376
const fork = await subagentSpawnDeps.forkSessionFromParent({
@@ -392,6 +399,15 @@ async function prepareSubagentSessionContext(params: {
392399

393400
if (params.contextMode === "fork") {
394401
if (!parentEntry || !forked) {
402+
if (forkFallbackNote) {
403+
return {
404+
status: "ok",
405+
mode: "isolated",
406+
parentEntry,
407+
childEntry,
408+
forkFallbackNote,
409+
};
410+
}
395411
return {
396412
status: "error",
397413
error: 'context="fork" requested but OpenClaw could not prepare forked context.',
@@ -405,7 +421,13 @@ async function prepareSubagentSessionContext(params: {
405421
forked,
406422
};
407423
}
408-
return { status: "ok", mode: "isolated", parentEntry, childEntry };
424+
return {
425+
status: "ok",
426+
mode: "isolated",
427+
parentEntry,
428+
childEntry,
429+
...(forkFallbackNote ? { forkFallbackNote } : {}),
430+
};
409431
} catch (err) {
410432
return { status: "error", error: summarizeError(err) };
411433
}
@@ -1276,15 +1298,18 @@ export async function spawnSubagentDirect(
12761298
label: label || undefined,
12771299
});
12781300

1301+
const acceptedNote = resolveSubagentSpawnAcceptedNote({
1302+
spawnMode,
1303+
agentSessionKey: ctx.agentSessionKey,
1304+
});
12791305
return {
12801306
status: "accepted",
12811307
childSessionKey,
12821308
runId: childRunId,
12831309
mode: spawnMode,
1284-
note: resolveSubagentSpawnAcceptedNote({
1285-
spawnMode,
1286-
agentSessionKey: ctx.agentSessionKey,
1287-
}),
1310+
note: preparedSpawnContext.forkFallbackNote
1311+
? `${acceptedNote} ${preparedSpawnContext.forkFallbackNote}`
1312+
: acceptedNote,
12881313
modelApplied: resolvedModel ? modelApplied : undefined,
12891314
attachments: attachmentsReceipt,
12901315
};

‎src/auto-reply/reply/session-fork.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,30 @@ import type { OpenClawConfig } from "../../config/types.openclaw.js";
99
const DEFAULT_PARENT_FORK_MAX_TOKENS = 100_000;
1010
let sessionForkRuntimePromise: Promise<typeof import("./session-fork.runtime.js")> | null = null;
1111

12+
export type ParentForkDecision =
13+
| {
14+
status: "fork";
15+
maxTokens: number;
16+
parentTokens?: number;
17+
}
18+
| {
19+
status: "skip";
20+
reason: "parent-too-large";
21+
maxTokens: number;
22+
parentTokens: number;
23+
message: string;
24+
};
25+
1226
function loadSessionForkRuntime(): Promise<typeof import("./session-fork.runtime.js")> {
1327
sessionForkRuntimePromise ??= import("./session-fork.runtime.js");
1428
return sessionForkRuntimePromise;
1529
}
1630

31+
/**
32+
* Deprecated compatibility guard for deployments that explicitly tuned the
33+
* historical thread fork ceiling. New behavior should use the shared parent
34+
* fork decision helper so channel threads and subagents degrade the same way.
35+
*/
1736
export function resolveParentForkMaxTokens(cfg: OpenClawConfig): number {
1837
const configured = cfg.session?.parentForkMaxTokens;
1938
if (typeof configured === "number" && Number.isFinite(configured) && configured >= 0) {
@@ -22,6 +41,45 @@ export function resolveParentForkMaxTokens(cfg: OpenClawConfig): number {
2241
return DEFAULT_PARENT_FORK_MAX_TOKENS;
2342
}
2443

44+
export function formatParentForkTooLargeMessage(params: {
45+
parentTokens: number;
46+
maxTokens: number;
47+
}): string {
48+
return (
49+
`Parent context is too large to fork (${params.parentTokens}/${params.maxTokens} tokens); ` +
50+
"starting with isolated context instead."
51+
);
52+
}
53+
54+
export async function resolveParentForkDecision(params: {
55+
cfg: OpenClawConfig;
56+
parentEntry: SessionEntry;
57+
storePath: string;
58+
}): Promise<ParentForkDecision> {
59+
const maxTokens = resolveParentForkMaxTokens(params.cfg);
60+
if (maxTokens <= 0) {
61+
return { status: "fork", maxTokens };
62+
}
63+
const parentTokens = await resolveParentForkTokenCount({
64+
parentEntry: params.parentEntry,
65+
storePath: params.storePath,
66+
});
67+
if (typeof parentTokens === "number" && parentTokens > maxTokens) {
68+
return {
69+
status: "skip",
70+
reason: "parent-too-large",
71+
maxTokens,
72+
parentTokens,
73+
message: formatParentForkTooLargeMessage({ parentTokens, maxTokens }),
74+
};
75+
}
76+
return {
77+
status: "fork",
78+
maxTokens,
79+
...(typeof parentTokens === "number" ? { parentTokens } : {}),
80+
};
81+
}
82+
2583
export async function forkSessionFromParent(params: {
2684
parentEntry: SessionEntry;
2785
agentId: string;

0 commit comments

Comments
 (0)