Skip to content

Commit 927fc84

Browse files
committed
fix: preserve active turns during session compaction
1 parent 3659c85 commit 927fc84

7 files changed

Lines changed: 286 additions & 135 deletions

‎src/agents/sessions/agent-session-compaction.ts‎

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,13 @@ import {
77
estimateContextTokens,
88
prepareCompaction,
99
shouldCompact,
10+
type CompactionPreparation,
1011
type CompactionResult,
1112
} from "../runtime/index.js";
1213
import { AgentSessionInspection } from "./agent-session-inspection.js";
1314
import { unwrapCoreResult } from "./agent-session-utils.js";
1415
import { formatNoModelSelectedMessage } from "./auth-guidance.js";
16+
import { preflightManualSessionCompaction } from "./manual-compaction-preflight.js";
1517
import { getLatestCompactionEntry, type CompactionEntry } from "./session-manager.js";
1618
import type { SettingsManager } from "./settings-manager.js";
1719

@@ -141,23 +143,17 @@ export abstract class AgentSessionCompaction extends AgentSessionInspection {
141143
}
142144

143145
const pathEntries = this.sessionManager.getBranch();
144-
let preparation = unwrapCoreResult(prepareCompaction(pathEntries, options.settings));
145-
if (!preparation && isManual) {
146-
// An explicit request should compact the smallest valid history instead of
147-
// relying on the old empty-summary behavior when the whole session fits the keep budget.
148-
preparation = unwrapCoreResult(
149-
prepareCompaction(pathEntries, { ...options.settings, keepRecentTokens: 0 }),
150-
);
146+
let preparation: CompactionPreparation | undefined;
147+
if (isManual) {
148+
const manualPreflight = preflightManualSessionCompaction(pathEntries, options.settings);
149+
if (!manualPreflight.compactable) {
150+
throw new Error(manualPreflight.reason);
151+
}
152+
preparation = manualPreflight.preparation;
153+
} else {
154+
preparation = unwrapCoreResult(prepareCompaction(pathEntries, options.settings));
151155
}
152156
if (!preparation) {
153-
if (isManual) {
154-
const lastEntry = pathEntries[pathEntries.length - 1];
155-
throw new Error(
156-
lastEntry?.type === "compaction"
157-
? "Already compacted"
158-
: "Nothing to compact (session too small)",
159-
);
160-
}
161157
return { status: "skipped" };
162158
}
163159

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import {
2+
prepareCompaction,
3+
type CompactionPreparation,
4+
type CompactionSettings,
5+
} from "../../../packages/agent-core/src/harness/compaction/compaction.js";
6+
import type { SessionEntry } from "./session-manager.js";
7+
8+
type ManualCompactionPreflight =
9+
| { compactable: true; preparation: CompactionPreparation }
10+
| { compactable: false; reason: "Already compacted" | "Nothing to compact (session too small)" };
11+
12+
/** Plans manual compaction without aborting or otherwise mutating the active session. */
13+
export function preflightManualSessionCompaction(
14+
pathEntries: SessionEntry[],
15+
settings: CompactionSettings,
16+
): ManualCompactionPreflight {
17+
const initial = prepareCompaction(pathEntries, settings);
18+
if (!initial.ok) {
19+
throw initial.error;
20+
}
21+
let preparation = initial.value;
22+
if (!preparation) {
23+
// Explicit manual compaction uses the smallest valid history rather than
24+
// treating a session that fits the configured keep budget as a no-op.
25+
const smallest = prepareCompaction(pathEntries, { ...settings, keepRecentTokens: 0 });
26+
if (!smallest.ok) {
27+
throw smallest.error;
28+
}
29+
preparation = smallest.value;
30+
}
31+
if (preparation) {
32+
return { compactable: true, preparation };
33+
}
34+
return {
35+
compactable: false,
36+
reason:
37+
pathEntries.at(-1)?.type === "compaction"
38+
? "Already compacted"
39+
: "Nothing to compact (session too small)",
40+
};
41+
}

‎src/gateway/server-methods/sessions-compact.ts‎

Lines changed: 65 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
errorShape,
66
validateSessionsCompactParams,
77
} from "../../../packages/gateway-protocol/src/index.js";
8+
import { resolveDefaultAgentId } from "../../agents/agent-scope.js";
89
import { clearSessionQueues } from "../../auto-reply/reply/queue/cleanup.js";
910
import {
1011
resolveSessionWorkStartError,
@@ -18,16 +19,18 @@ import {
1819
} from "../../config/sessions/session-accessor.js";
1920
import { formatErrorMessage } from "../../infra/errors.js";
2021
import {
21-
interruptSessionWorkAdmissions,
22+
isCompetingSessionWorkAdmissionActive,
2223
runExclusiveSessionLifecycleMutation,
23-
SESSION_WORK_ADMISSION_DRAIN_TIMEOUT_MS,
2424
} from "../../sessions/session-lifecycle-admission.js";
2525
import { recordSessionCompacted } from "../../sessions/session-state-events.js";
2626
import { resolveRequestedSessionAgentId as resolveRequestedGlobalAgentId } from "../session-create-service.js";
2727
import { migrateAndPruneGatewaySessionStoreKey } from "../session-utils.js";
28+
import { hasVisibleActiveSessionRun } from "./session-active-runs.js";
2829
import { emitSessionsChanged } from "./session-change-event.js";
29-
import { runGatewaySessionCompaction } from "./sessions-compaction-runner.js";
30-
import { interruptSessionRunIfActive } from "./sessions-messaging.js";
30+
import {
31+
preflightGatewaySessionCompaction,
32+
runGatewaySessionCompaction,
33+
} from "./sessions-compaction-runner.js";
3134
import {
3235
emitSessionOperation,
3336
loadAccessorSessionEntryForGatewayTarget,
@@ -39,7 +42,7 @@ import type { GatewayRequestHandlers } from "./types.js";
3942
import { assertValidParams } from "./validation.js";
4043

4144
export const sessionCompactHandlers: GatewayRequestHandlers = {
42-
"sessions.compact": async ({ req, params, respond, context, client, isWebchatConnect }) => {
45+
"sessions.compact": async ({ params, respond, context, client, isWebchatConnect }) => {
4346
if (!assertValidParams(params, validateSessionsCompactParams, "sessions.compact", respond)) {
4447
return;
4548
}
@@ -168,7 +171,8 @@ export const sessionCompactHandlers: GatewayRequestHandlers = {
168171
lifecycleRevision,
169172
];
170173
let sessionStillCurrent = true;
171-
let admittedWorkReleased = true;
174+
let compactionNoopReason: string | undefined;
175+
let blockedByActiveRun = false;
172176
try {
173177
await runExclusiveSessionLifecycleMutation({
174178
scope: storePath,
@@ -180,23 +184,47 @@ export const sessionCompactHandlers: GatewayRequestHandlers = {
180184
cfg,
181185
agentId: requestedAgentId,
182186
}).entry;
183-
sessionStillCurrent = Boolean(
184-
latestEntry &&
185-
latestEntry.sessionId === sessionId &&
186-
latestEntry.lifecycleRevision === lifecycleRevision &&
187-
!resolveSessionWorkStartError(target.canonicalKey, latestEntry),
188-
);
189-
if (!sessionStillCurrent) {
187+
if (
188+
!latestEntry ||
189+
latestEntry.sessionId !== sessionId ||
190+
latestEntry.lifecycleRevision !== lifecycleRevision ||
191+
resolveSessionWorkStartError(target.canonicalKey, latestEntry)
192+
) {
193+
sessionStillCurrent = false;
194+
return;
195+
}
196+
if (maxLines === undefined) {
197+
compactionNoopReason = (
198+
await preflightGatewaySessionCompaction({
199+
cfg,
200+
entry: latestEntry,
201+
agentId: target.agentId,
202+
sessionId,
203+
sessionKey: target.canonicalKey,
204+
sessionStoreKey: compactTarget.primaryKey,
205+
storePath,
206+
})
207+
)?.reason;
208+
if (compactionNoopReason) {
209+
return;
210+
}
211+
}
212+
blockedByActiveRun =
213+
isCompetingSessionWorkAdmissionActive(storePath, lifecycleIdentities) ||
214+
hasVisibleActiveSessionRun({
215+
context,
216+
requestedKey: key,
217+
canonicalKey: target.canonicalKey,
218+
sessionId,
219+
agentId: requestedAgentId,
220+
defaultAgentId: resolveDefaultAgentId(cfg),
221+
});
222+
if (blockedByActiveRun) {
190223
return;
191224
}
192225
// Drop work queued against the pre-compaction transcript before its
193-
// active admission drains and no longer exposes queue cleanup.
226+
// lifecycle fence commits and no longer exposes queue cleanup.
194227
clearSessionQueues([key, target.canonicalKey, compactTarget.primaryKey, sessionId]);
195-
admittedWorkReleased = await interruptSessionWorkAdmissions({
196-
scope: storePath,
197-
identities: lifecycleIdentities,
198-
timeoutMs: SESSION_WORK_ADMISSION_DRAIN_TIMEOUT_MS,
199-
});
200228
},
201229
run: async () => {
202230
if (!sessionStillCurrent) {
@@ -211,11 +239,27 @@ export const sessionCompactHandlers: GatewayRequestHandlers = {
211239
);
212240
return;
213241
}
214-
if (!admittedWorkReleased) {
242+
if (compactionNoopReason) {
243+
respond(
244+
true,
245+
{
246+
ok: false,
247+
key: target.canonicalKey,
248+
compacted: false,
249+
reason: compactionNoopReason,
250+
},
251+
undefined,
252+
);
253+
return;
254+
}
255+
if (blockedByActiveRun) {
215256
respond(
216257
false,
217258
undefined,
218-
errorShape(ErrorCodes.UNAVAILABLE, `Session ${key} is still active; try again.`),
259+
errorShape(
260+
ErrorCodes.INVALID_REQUEST,
261+
`Session ${key} has an active run; retry after it finishes.`,
262+
),
219263
);
220264
return;
221265
}
@@ -243,21 +287,6 @@ export const sessionCompactHandlers: GatewayRequestHandlers = {
243287
return;
244288
}
245289

246-
const interruptResult = await interruptSessionRunIfActive({
247-
req,
248-
context,
249-
client,
250-
isWebchatConnect,
251-
requestedKey: key,
252-
canonicalKey: target.canonicalKey,
253-
agentId: requestedAgentId,
254-
sessionId,
255-
});
256-
if (interruptResult.error) {
257-
respond(false, undefined, interruptResult.error);
258-
return;
259-
}
260-
261290
const operationId = randomUUID();
262291
if (maxLines !== undefined) {
263292
const trimResult = await trimSessionTranscriptForManualCompact(

‎src/gateway/server-methods/sessions-compaction-runner.ts‎

Lines changed: 63 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,28 +3,87 @@ import { normalizeOptionalString } from "@openclaw/normalization-core/string-coe
33
import { resolveAgentWorkspaceDir } from "../../agents/agent-scope.js";
44
import { compactEmbeddedAgentSession } from "../../agents/embedded-agent.js";
55
import { resolvePersistedSessionRuntimeId } from "../../agents/session-runtime-compat.js";
6+
import { preflightManualSessionCompaction } from "../../agents/sessions/manual-compaction-preflight.js";
7+
import type { SessionEntry as AgentSessionEntry } from "../../agents/sessions/session-manager.js";
68
import { resolveIngressWorkspaceOverrideForSessionRun } from "../../agents/spawned-context.js";
79
import { normalizeReasoningLevel, normalizeThinkLevel } from "../../auto-reply/thinking.js";
810
import type { SessionEntry } from "../../config/sessions.js";
9-
import { resolveSessionTranscriptRuntimeTarget } from "../../config/sessions/session-accessor.js";
11+
import {
12+
loadTranscriptEvents,
13+
resolveSessionTranscriptRuntimeTarget,
14+
} from "../../config/sessions/session-accessor.js";
15+
import {
16+
isCanonicalSessionTranscriptEntry,
17+
scanSessionTranscriptTree,
18+
selectSessionTranscriptTreePathNodes,
19+
} from "../../config/sessions/transcript-tree.js";
1020
import type { OpenClawConfig } from "../../config/types.openclaw.js";
1121
import { resolveSessionModelRef } from "../session-utils.js";
1222

13-
export async function runGatewaySessionCompaction(params: {
23+
type GatewaySessionCompactionParams = {
1424
agentId: string;
1525
cfg: OpenClawConfig;
1626
entry: SessionEntry;
1727
sessionId: string;
1828
sessionKey: string;
1929
sessionStoreKey: string;
2030
storePath: string;
21-
}): Promise<Awaited<ReturnType<typeof compactEmbeddedAgentSession>>> {
22-
const transcriptTarget = await resolveSessionTranscriptRuntimeTarget({
31+
};
32+
33+
function usesLegacyOpenClawCompaction(params: GatewaySessionCompactionParams): boolean {
34+
const persistedRuntime = params.entry.modelSelectionLocked
35+
? resolvePersistedSessionRuntimeId(params.entry)
36+
: params.entry.agentHarnessId;
37+
const contextEngine = params.cfg.plugins?.slots?.contextEngine?.trim();
38+
return (
39+
(!persistedRuntime || persistedRuntime === "openclaw") &&
40+
(!contextEngine || contextEngine === "legacy")
41+
);
42+
}
43+
44+
async function resolveGatewayCompactionTranscriptTarget(params: GatewaySessionCompactionParams) {
45+
return await resolveSessionTranscriptRuntimeTarget({
2346
agentId: params.agentId,
2447
sessionId: params.sessionId,
2548
sessionKey: params.sessionStoreKey,
2649
storePath: params.storePath,
2750
});
51+
}
52+
53+
/** Returns only definitive legacy-runtime no-op verdicts; other runtimes decide for themselves. */
54+
export async function preflightGatewaySessionCompaction(
55+
params: GatewaySessionCompactionParams,
56+
): Promise<{ reason: "Already compacted" | "Nothing to compact (session too small)" } | undefined> {
57+
if (!usesLegacyOpenClawCompaction(params)) {
58+
return undefined;
59+
}
60+
try {
61+
const transcriptEvents = await loadTranscriptEvents({
62+
agentId: params.agentId,
63+
sessionId: params.sessionId,
64+
sessionKey: params.sessionStoreKey,
65+
storePath: params.storePath,
66+
});
67+
const tree = scanSessionTranscriptTree(transcriptEvents);
68+
const branch = selectSessionTranscriptTreePathNodes(tree, tree.leafId)
69+
.map((node) => node.entry)
70+
.filter(isCanonicalSessionTranscriptEntry) as unknown as AgentSessionEntry[];
71+
const preflight = preflightManualSessionCompaction(branch, {
72+
enabled: true,
73+
reserveTokens: 0,
74+
keepRecentTokens: 0,
75+
});
76+
return preflight.compactable ? undefined : { reason: preflight.reason };
77+
} catch {
78+
// Preserve the existing compaction error path for malformed or unavailable transcripts.
79+
return undefined;
80+
}
81+
}
82+
83+
export async function runGatewaySessionCompaction(
84+
params: GatewaySessionCompactionParams,
85+
): Promise<Awaited<ReturnType<typeof compactEmbeddedAgentSession>>> {
86+
const transcriptTarget = await resolveGatewayCompactionTranscriptTarget(params);
2887
const resolvedModel = resolveSessionModelRef(params.cfg, params.entry, params.agentId);
2988
const workspaceDir =
3089
resolveIngressWorkspaceOverrideForSessionRun({

0 commit comments

Comments
 (0)