Skip to content

Commit a6cb2fb

Browse files
authored
fix(agents): preserve context engine session ownership (#124376)
* fix(agents): preserve context engine session ownership Unbound legacy context-engine hooks no longer execute LLM calls under the default agent. Explicit, agent-scoped, main-alias, and persisted session ownership remain supported. * test(ci): avoid scheduler pid file race
1 parent e8e7598 commit a6cb2fb

21 files changed

Lines changed: 313 additions & 58 deletions

‎src/agents/embedded-agent-runner/compact.hooks.test.ts‎

Lines changed: 54 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,9 @@ import { tmpdir } from "node:os";
55
import { join } from "node:path";
66
import { expectDefined } from "@openclaw/normalization-core";
77
import type { AgentMessage } from "openclaw/plugin-sdk/agent-core";
8-
import { beforeAll, beforeEach, describe, expect, it, vi, type Mock } from "vitest";
8+
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi, type Mock } from "vitest";
99
import { createDeferred } from "../../../test/helpers/promise.js";
10+
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
1011
import { createReplyOperation } from "../../auto-reply/reply/reply-run-registry.js";
1112
import { upsertSessionEntryCore } from "../../config/sessions/session-accessor.js";
1213
import type { PluginManifestRecord } from "../../plugins/manifest-registry.js";
@@ -78,6 +79,8 @@ let compactTesting: typeof import("./compact.js").testing;
7879
let onSessionTranscriptUpdate: typeof import("../../sessions/transcript-events.js").onSessionTranscriptUpdate;
7980
let onInternalSessionTranscriptUpdate: typeof import("../../sessions/transcript-events.js").onInternalSessionTranscriptUpdate;
8081

82+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
83+
8184
const TEST_SESSION_ID = "session-1";
8285
const TEST_SESSION_KEY = "agent:main:session-1";
8386
const TEST_SESSION_FILE = "/tmp/session.jsonl";
@@ -2793,7 +2796,9 @@ describe("compactEmbeddedAgentSession hooks (ownsCompaction engine)", () => {
27932796
expect(result.result).not.toHaveProperty("summary");
27942797
});
27952798

2796-
it("binds context-engine compaction runtime LLM to the session agent", async () => {
2799+
it("fails closed for a fallback-owned legacy compaction target", async () => {
2800+
const legacySessionId = "legacy-session-47";
2801+
const legacyStorePath = join(tempDirs.make("openclaw-legacy-compaction-"), "openclaw.sqlite");
27972802
resolveSessionAgentIdsMock.mockReturnValueOnce({
27982803
defaultAgentId: "main",
27992804
sessionAgentId: "lossless-agent",
@@ -2808,7 +2813,14 @@ describe("compactEmbeddedAgentSession hooks (ownsCompaction engine)", () => {
28082813
},
28092814
},
28102815
},
2816+
sessionId: legacySessionId,
28112817
sessionKey: "legacy-topic-47",
2818+
sessionTarget: {
2819+
agentId: "lossless-agent",
2820+
sessionId: legacySessionId,
2821+
sessionKey: "legacy-topic-47",
2822+
storePath: legacyStorePath,
2823+
},
28122824
}),
28132825
);
28142826

@@ -2835,6 +2847,46 @@ describe("compactEmbeddedAgentSession hooks (ownsCompaction engine)", () => {
28352847
await expect(
28362848
runtimeContext.llm?.complete?.({
28372849
messages: [{ role: "user", content: "summarize" }],
2850+
}),
2851+
).rejects.toThrow("not bound to an active session agent");
2852+
});
2853+
2854+
it("binds a queued legacy compaction from its explicit owner field", async () => {
2855+
const legacySessionId = "explicit-legacy-session-48";
2856+
await compactEmbeddedAgentSession(
2857+
wrappedCompactionArgs({
2858+
config: { agents: { defaults: { model: "openai/gpt-5.5" } } },
2859+
contextEngineAgentId: "lossless-agent",
2860+
sessionId: legacySessionId,
2861+
sessionKey: "legacy-topic-48",
2862+
sessionTarget: {
2863+
agentId: "lossless-agent",
2864+
sessionId: legacySessionId,
2865+
sessionKey: "legacy-topic-48",
2866+
storePath: join(tempDirs.make("openclaw-explicit-legacy-compaction-"), "openclaw.sqlite"),
2867+
},
2868+
}),
2869+
);
2870+
2871+
const compactInput = (
2872+
contextEngineCompactMock.mock.calls as unknown as Array<
2873+
[
2874+
{
2875+
runtimeContext?: {
2876+
llm?: {
2877+
complete?: (params: {
2878+
messages: Array<{ role: "user"; content: string }>;
2879+
agentId?: string;
2880+
}) => Promise<unknown>;
2881+
};
2882+
};
2883+
},
2884+
]
2885+
>
2886+
)[0]?.[0];
2887+
await expect(
2888+
compactInput?.runtimeContext?.llm?.complete?.({
2889+
messages: [{ role: "user", content: "summarize" }],
28382890
agentId: "other-agent",
28392891
}),
28402892
).rejects.toThrow("cannot override the active session agent");

‎src/agents/embedded-agent-runner/compact.queued.ts‎

Lines changed: 29 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/**
22
* Queues embedded-agent session compaction onto the correct command lane.
33
*/
4+
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
45
import { OPENCLAW_EMBEDDED_CONTEXT_ENGINE_HOST } from "../../context-engine/host-compat.js";
56
import { ensureContextEnginesInitialized } from "../../context-engine/init.js";
67
import {
@@ -158,6 +159,7 @@ async function disposeContextEngine(contextEngine: ContextEngine): Promise<void>
158159

159160
async function deferOwningContextEngineBudgetCompaction(params: {
160161
compactParams: CompactEmbeddedAgentSessionParams;
162+
contextEngineSessionKey?: string;
161163
contextEngine: ContextEngine;
162164
contextEngineRuntimeContext: ContextEngineRuntimeContext;
163165
contextEngineRuntimeSettings: ContextEngineRuntimeSettings;
@@ -168,13 +170,14 @@ async function deferOwningContextEngineBudgetCompaction(params: {
168170
await runContextEngineMaintenance({
169171
contextEngine: params.contextEngine,
170172
sessionId: params.compactParams.sessionId,
171-
sessionKey: params.compactParams.sessionKey,
173+
sessionKey: params.contextEngineSessionKey ?? params.compactParams.sessionKey,
172174
sessionTarget: buildContextEngineCompactionSessionTarget(params.compactParams),
173175
sessionFile: params.compactParams.sessionFile,
174176
reason: "turn",
175177
runtimeContext: params.contextEngineRuntimeContext,
176178
runtimeSettings: params.contextEngineRuntimeSettings,
177179
config: params.compactParams.config,
180+
contextEngineAgentId: params.compactParams.contextEngineAgentId,
178181
disposeDeferredContextEngineAfterMaintenance: true,
179182
onDeferredMaintenance: () => {
180183
deferredScheduled = true;
@@ -243,6 +246,11 @@ function mergeSecondaryNativeHarnessCompactionDetails(params: {
243246
export async function compactEmbeddedAgentSession(
244247
params: CompactEmbeddedAgentSessionParams,
245248
): Promise<EmbeddedAgentCompactResult> {
249+
const contextEngineAgentId =
250+
normalizeOptionalString(params.contextEngineAgentId) ?? normalizeOptionalString(params.agentId);
251+
const contextEngineSessionKey =
252+
normalizeOptionalString(params.sessionKey) ??
253+
normalizeOptionalString(params.sessionTarget?.sessionKey);
246254
const runtimeTarget = await resolveAgentRunSessionTarget({
247255
...params,
248256
missingSessionKey: "resolve-existing",
@@ -254,9 +262,10 @@ export async function compactEmbeddedAgentSession(
254262
sessionKey: runtimeTarget.sessionKey,
255263
sessionTarget: runtimeTarget,
256264
sessionFile: runtimeTarget.sessionKey,
265+
contextEngineAgentId,
257266
};
258267
if (resolvedParams.trigger !== "manual") {
259-
return await compactEmbeddedAgentSessionImpl(resolvedParams);
268+
return await compactEmbeddedAgentSessionImpl(resolvedParams, contextEngineSessionKey);
260269
}
261270
// Reply operations and embedded handles are separate lifecycle owners. A
262271
// /compact reply may coexist with this handle, but another embedded writer may not.
@@ -289,10 +298,13 @@ export async function compactEmbeddedAgentSession(
289298
resolvedParams.sessionFile,
290299
);
291300
try {
292-
return await compactEmbeddedAgentSessionImpl({
293-
...resolvedParams,
294-
abortSignal,
295-
});
301+
return await compactEmbeddedAgentSessionImpl(
302+
{
303+
...resolvedParams,
304+
abortSignal,
305+
},
306+
contextEngineSessionKey,
307+
);
296308
} finally {
297309
clearActiveEmbeddedRun(
298310
resolvedParams.sessionId,
@@ -305,6 +317,7 @@ export async function compactEmbeddedAgentSession(
305317

306318
async function compactEmbeddedAgentSessionImpl(
307319
inputParams: CompactEmbeddedAgentSessionParams,
320+
contextEngineSessionKey?: string,
308321
): Promise<EmbeddedAgentCompactResult> {
309322
if (inputParams.abortSignal?.aborted) {
310323
return createCompactionAbortedResult();
@@ -399,6 +412,7 @@ async function compactEmbeddedAgentSessionImpl(
399412
agentDir,
400413
resolvedWorkspaceDir,
401414
lease.snapshot,
415+
contextEngineSessionKey,
402416
() => {
403417
disposeContextEngineOnExit = false;
404418
},
@@ -422,6 +436,7 @@ async function compactResolvedContextEngine(
422436
agentDir: string,
423437
resolvedWorkspaceDir: string,
424438
preparedModelRuntime: PreparedModelRuntimeSnapshot,
439+
contextEngineSessionKey: string | undefined,
425440
releaseContextEngineOwnership: () => void,
426441
): Promise<EmbeddedAgentCompactResult> {
427442
const runtimeTarget = await resolveAgentRunSessionTarget({
@@ -576,6 +591,7 @@ async function compactResolvedContextEngine(
576591
params: preparedParams,
577592
agentDir,
578593
harnessRuntime: preparedHarnessRuntime,
594+
contextEngineSessionKey,
579595
contextTokenBudget,
580596
contextEnginePluginId: resolveContextEngineOwnerPluginId(contextEngine),
581597
});
@@ -620,6 +636,7 @@ async function compactResolvedContextEngine(
620636
) {
621637
const deferredResult = await deferOwningContextEngineBudgetCompaction({
622638
compactParams: preparedParams,
639+
contextEngineSessionKey,
623640
contextEngine,
624641
contextEngineRuntimeContext,
625642
contextEngineRuntimeSettings,
@@ -768,7 +785,7 @@ async function compactResolvedContextEngine(
768785
await runContextEngineMaintenance({
769786
contextEngine,
770787
sessionId: postCompactionSessionId,
771-
sessionKey: params.sessionKey,
788+
sessionKey: contextEngineSessionKey ?? params.sessionKey,
772789
sessionTarget: buildContextEngineCompactionSessionTarget({
773790
...params,
774791
sessionFile: postCompactionSessionFile,
@@ -780,6 +797,7 @@ async function compactResolvedContextEngine(
780797
runtimeContext,
781798
runtimeSettings: contextEngineRuntimeSettings,
782799
config: params.config,
800+
contextEngineAgentId: params.contextEngineAgentId,
783801
});
784802
}
785803
if (engineOwnsCompaction && result.ok && result.compacted) {
@@ -922,16 +940,12 @@ function shouldAttemptNativeHarnessCompaction(params: {
922940
function buildCompactionContextEngineRuntimeContext(params: {
923941
params: CompactEmbeddedAgentSessionParams;
924942
agentDir: string;
943+
contextEngineSessionKey?: string;
925944
harnessRuntime?: string;
926945
contextEnginePluginId?: string;
927946
contextTokenBudget?: number;
928947
}): ContextEngineRuntimeContext {
929-
const { sessionAgentId } = resolveSessionAgentIds({
930-
sessionKey: params.params.sessionKey,
931-
config: params.params.config,
932-
agentId: params.params.agentId,
933-
});
934-
const { sessionFile: _sessionFile, ...runtimeParams } = params.params;
948+
const { sessionFile: _sessionFile, contextEngineAgentId, ...runtimeParams } = params.params;
935949
return {
936950
...runtimeParams,
937951
sessionTarget: buildContextEngineCompactionSessionTarget(params.params),
@@ -943,8 +957,8 @@ function buildCompactionContextEngineRuntimeContext(params: {
943957
}),
944958
...resolveContextEngineCapabilities({
945959
config: params.params.config,
946-
sessionKey: params.params.sessionKey,
947-
agentId: sessionAgentId,
960+
sessionKey: params.contextEngineSessionKey ?? params.params.sessionKey,
961+
explicitAgentId: contextEngineAgentId,
948962
authProfileId: params.params.authProfileId,
949963
contextEnginePluginId: params.contextEnginePluginId,
950964
purpose: "context-engine.compaction",

‎src/agents/embedded-agent-runner/compact.types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ import type { ScheduledToolPolicyContext } from "../scheduled-tool-policy.js";
2121
import type { TrustedSubagentCompletionHandoff } from "../subagents/announce/subagent-announce-handoff.js";
2222

2323
export type CompactEmbeddedAgentSessionParams = {
24+
/** Explicit session owner captured before fallback agent resolution. */
25+
contextEngineAgentId?: string;
2426
sessionId: string;
2527
runId?: string;
2628
sessionKey?: string;

‎src/agents/embedded-agent-runner/context-engine-capabilities.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import { resolveBoundAgentIdForSession } from "../session-agent-binding.js";
99
type ResolveContextEngineCapabilitiesParams = {
1010
config?: OpenClawConfig;
1111
sessionKey?: string;
12-
agentId?: string;
12+
explicitAgentId?: string;
1313
authProfileId?: string;
1414
contextEnginePluginId?: string;
1515
purpose: string;
@@ -25,7 +25,7 @@ export function resolveContextEngineCapabilities(
2525
const agentId = resolveBoundAgentIdForSession({
2626
config: params.config,
2727
sessionKey,
28-
agentId: params.agentId,
28+
agentId: params.explicitAgentId,
2929
});
3030
const contextEnginePluginId = normalizeOptionalString(params.contextEnginePluginId);
3131
return {

‎src/agents/embedded-agent-runner/context-engine-maintenance.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ type ContextEngineMaintenanceParams = {
5959
runtimeContext?: ContextEngineRuntimeContext;
6060
runtimeSettings?: ContextEngineRuntimeSettings;
6161
agentId?: string;
62+
contextEngineAgentId?: string;
6263
executionMode?: "foreground" | "background";
6364
onDeferredMaintenance?: (promise: Promise<void>) => void;
6465
onDeferredMaintenanceFailure?: (error: unknown) => void;
@@ -236,7 +237,7 @@ function buildContextEngineMaintenanceRuntimeContext(
236237
...resolveContextEngineCapabilities({
237238
config: params.config,
238239
sessionKey: params.sessionKey,
239-
agentId: params.agentId,
240+
explicitAgentId: params.contextEngineAgentId,
240241
authProfileId: normalizeOptionalString(params.runtimeContext?.authProfileId),
241242
contextEnginePluginId: params.contextEnginePluginId,
242243
purpose: params.purpose ?? "context-engine.maintenance",

‎src/agents/embedded-agent-runner/run-orchestrator.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,9 @@ export function runEmbeddedAgent(
102102
async function runEmbeddedAgentInternal(
103103
paramsInput: RunEmbeddedAgentInternalParams,
104104
): Promise<EmbeddedAgentRunResult> {
105+
const contextEngineAgentId =
106+
normalizeOptionalString(paramsInput.sessionTarget?.agentId) ??
107+
normalizeOptionalString(paramsInput.agentId);
105108
const paramsBase = applyAgentRunSessionTargetIdentity(paramsInput);
106109
const skillWorkshopProposalMutationBudget = paramsBase.skillWorkshopProposalOnly
107110
? (paramsBase.skillWorkshopProposalMutationBudget ?? { remaining: 1 })
@@ -412,6 +415,7 @@ async function runEmbeddedAgentInternal(
412415

413416
return await executePreparedEmbeddedRun({
414417
runParams: params,
418+
contextEngineAgentId,
415419
provider,
416420
modelId,
417421
agentDir,

0 commit comments

Comments
 (0)