Skip to content

Commit e382fa7

Browse files
fix(codex): keep task lists active across compaction (#123921)
* fix(codex): restore plan state after compaction * fix(codex): bound restored plan context
1 parent d612949 commit e382fa7

6 files changed

Lines changed: 277 additions & 14 deletions

File tree

‎extensions/codex/src/app-server/event-projector-options.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ export type CodexAppServerEventProjectorOptions = {
1313
readRemoteWorkspaceFile?: CodexRemoteWorkspaceFileReader;
1414
remoteWorkspaceRequestTimeoutMs?: number;
1515
trajectoryRecorder?: CodexTrajectoryRecorder | null;
16-
onContextCompacted?: () => void;
16+
onContextCompacted?: () => void | Promise<void>;
1717
resolveDynamicToolResultContentSource?: (toolName: string) => "network" | undefined;
1818
upstreamUserText?: string;
1919
};

‎extensions/codex/src/app-server/event-projector.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -450,7 +450,7 @@ export class CodexAppServerEventProjector {
450450
if (item?.type === "contextCompaction" && itemId) {
451451
this.activeCompactionItemIds.delete(itemId);
452452
this.completedCompactionCount += 1;
453-
this.options.onContextCompacted?.();
453+
await this.options.onContextCompacted?.();
454454
await runAgentHarnessAfterCompactionHook({
455455
sessionFile: this.params.sessionFile,
456456
messages: await this.toolTranscriptProjection.readMirroredSessionMessages(),
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
import { Buffer } from "node:buffer";
2+
import type { EmbeddedRunAttemptParams } from "openclaw/plugin-sdk/agent-harness-runtime";
3+
import type { AgentPlanStep } from "openclaw/plugin-sdk/channel-outbound";
4+
import type { CodexAppServerClient } from "./client.js";
5+
6+
type AgentEvent = Parameters<NonNullable<EmbeddedRunAttemptParams["onAgentEvent"]>>[0];
7+
type StoredPlan = { explanation?: string; steps: AgentPlanStep[] };
8+
9+
const RESTORED_PLAN_PREAMBLE =
10+
"OpenClaw restored the active task list after context compaction. " +
11+
"This is application state, not a new user request. Continue the current task and call " +
12+
"update_plan whenever a status changes.";
13+
const RESTORED_PLAN_MAX_STEPS = 50;
14+
const RESTORED_PLAN_MAX_STEP_BYTES = 512;
15+
const RESTORED_PLAN_MAX_EXPLANATION_BYTES = 2 * 1024;
16+
const RESTORED_PLAN_MAX_PAYLOAD_BYTES = 32 * 1024;
17+
const RESTORED_PLAN_TRUNCATION_SUFFIX = "…";
18+
19+
/** Retains the latest projected plan so Codex compaction cannot discard it. */
20+
export class CodexCompactionPlanState {
21+
private latestPlan: StoredPlan | undefined;
22+
23+
record(event: AgentEvent): void {
24+
if (event.stream !== "plan") {
25+
return;
26+
}
27+
const plan = readBoundedPlan(event.data.explanation, event.data.steps);
28+
if (!plan) {
29+
return;
30+
}
31+
this.latestPlan = plan;
32+
}
33+
34+
async restore(params: {
35+
client: CodexAppServerClient;
36+
threadId: string;
37+
timeoutMs: number;
38+
signal?: AbortSignal;
39+
}): Promise<void> {
40+
if (!this.latestPlan) {
41+
return;
42+
}
43+
await params.client.request(
44+
"thread/inject_items",
45+
{
46+
threadId: params.threadId,
47+
items: [
48+
{
49+
type: "message",
50+
role: "user",
51+
content: [
52+
{
53+
type: "input_text",
54+
text: `${RESTORED_PLAN_PREAMBLE}\n${serializePlan(this.latestPlan)}`,
55+
},
56+
],
57+
},
58+
],
59+
},
60+
{ timeoutMs: params.timeoutMs, signal: params.signal },
61+
);
62+
}
63+
}
64+
65+
function readBoundedPlan(explanationValue: unknown, stepsValue: unknown): StoredPlan | undefined {
66+
const explanation =
67+
typeof explanationValue === "string"
68+
? truncateUtf8(explanationValue, RESTORED_PLAN_MAX_EXPLANATION_BYTES)
69+
: undefined;
70+
const steps: AgentPlanStep[] = [];
71+
for (const step of readPlanSteps(stepsValue)) {
72+
if (steps.length >= RESTORED_PLAN_MAX_STEPS) {
73+
break;
74+
}
75+
const boundedStep = {
76+
...step,
77+
step: truncateUtf8(step.step, RESTORED_PLAN_MAX_STEP_BYTES),
78+
};
79+
const candidate = {
80+
...(explanation ? { explanation } : {}),
81+
steps: [...steps, boundedStep],
82+
};
83+
if (Buffer.byteLength(serializePlan(candidate), "utf8") > RESTORED_PLAN_MAX_PAYLOAD_BYTES) {
84+
break;
85+
}
86+
steps.push(boundedStep);
87+
}
88+
return steps.length > 0 ? { ...(explanation ? { explanation } : {}), steps } : undefined;
89+
}
90+
91+
function serializePlan(plan: StoredPlan): string {
92+
return JSON.stringify({ explanation: plan.explanation, plan: plan.steps });
93+
}
94+
95+
function truncateUtf8(value: string, maxBytes: number): string {
96+
const bytes = Buffer.from(value);
97+
if (bytes.byteLength <= maxBytes) {
98+
return value;
99+
}
100+
const suffixBytes = Buffer.byteLength(RESTORED_PLAN_TRUNCATION_SUFFIX, "utf8");
101+
let end = Math.max(0, maxBytes - suffixBytes);
102+
while (end > 0 && (bytes[end] ?? 0) >> 6 === 0b10) {
103+
end -= 1;
104+
}
105+
return `${bytes.subarray(0, end).toString("utf8")}${RESTORED_PLAN_TRUNCATION_SUFFIX}`;
106+
}
107+
108+
function readPlanSteps(value: unknown): AgentPlanStep[] {
109+
if (!Array.isArray(value)) {
110+
return [];
111+
}
112+
return value.flatMap((entry) => {
113+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
114+
return [];
115+
}
116+
const { step, status } = entry as { step?: unknown; status?: unknown };
117+
if (typeof step !== "string" || !isPlanStatus(status)) {
118+
return [];
119+
}
120+
return [{ step, status }];
121+
});
122+
}
123+
124+
function isPlanStatus(value: unknown): value is AgentPlanStep["status"] {
125+
return value === "pending" || value === "in_progress" || value === "completed";
126+
}

‎extensions/codex/src/app-server/run-attempt-active-turn.ts‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ export async function activateCodexAttemptTurn(
5656
sandboxSessionKey,
5757
effectiveCwd,
5858
} = connection;
59-
const { dynamicToolParams, computerContextEpoch, toolBridge } = attemptTools;
59+
const { dynamicToolParams, compactionPlanState, computerContextEpoch, toolBridge } = attemptTools;
6060
const { state, userInputBridgeRef, steeringQueueRef, turnWatches, completeTurn, interruptTurn } =
6161
turnRuntime;
6262
const { emitExecutionPhaseOnce, emitLifecycleStart, maybeAnnounceFastModeAutoOff } = lifecycle;
@@ -116,10 +116,24 @@ export async function activateCodexAttemptTurn(
116116
onNativeToolResultRecorded: maybeAnnounceFastModeAutoOff,
117117
...(prepareNativeMcpAppResultDetails ? { prepareNativeMcpAppResultDetails } : {}),
118118
upstreamUserText: turnState.codexTurnPromptText,
119-
onContextCompacted: () => {
119+
onContextCompacted: async () => {
120120
computerContextEpoch.value += 1;
121121
delete computerContextEpoch.frameToolCallId;
122122
delete computerContextEpoch.frameImageIdentity;
123+
try {
124+
await compactionPlanState.restore({
125+
client: resourceState.client,
126+
threadId: resourceState.thread.threadId,
127+
timeoutMs: connection.appServer.requestTimeoutMs,
128+
signal: runAbortController.signal,
129+
});
130+
} catch (error) {
131+
embeddedAgentLog.warn("failed to restore Codex plan state after compaction", {
132+
runId: params.runId,
133+
threadId: resourceState.thread.threadId,
134+
error: formatErrorMessage(error),
135+
});
136+
}
123137
},
124138
},
125139
);

‎extensions/codex/src/app-server/run-attempt-tool-setup.ts‎

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
createCodexDynamicToolBridge,
2525
projectCodexExecutableDynamicTools,
2626
} from "./dynamic-tools.js";
27+
import { CodexCompactionPlanState } from "./plan-compaction-state.js";
2728
import { emitCodexAppServerEvent } from "./run-attempt-lifecycle.js";
2829
import type { CodexAttemptRuntime } from "./run-attempt-runtime.js";
2930
import { resolveCodexDynamicToolDirectNames } from "./run-attempt-tools.js";
@@ -115,16 +116,18 @@ export async function prepareCodexAttemptTools(runtime: CodexAttemptRuntime) {
115116
return ordinal;
116117
}
117118
: undefined;
118-
const dynamicToolParams =
119-
allocateCodexToolOutcomeOrdinal || onCodexToolOutcome
120-
? {
121-
...runtimeParams,
122-
...(allocateCodexToolOutcomeOrdinal
123-
? { allocateToolOutcomeOrdinal: allocateCodexToolOutcomeOrdinal }
124-
: {}),
125-
...(onCodexToolOutcome ? { onToolOutcome: onCodexToolOutcome } : {}),
126-
}
127-
: runtimeParams;
119+
const compactionPlanState = new CodexCompactionPlanState();
120+
const dynamicToolParams = {
121+
...runtimeParams,
122+
onAgentEvent: (event: Parameters<NonNullable<EmbeddedRunAttemptParams["onAgentEvent"]>>[0]) => {
123+
compactionPlanState.record(event);
124+
return runtimeParams.onAgentEvent?.(event);
125+
},
126+
...(allocateCodexToolOutcomeOrdinal
127+
? { allocateToolOutcomeOrdinal: allocateCodexToolOutcomeOrdinal }
128+
: {}),
129+
...(onCodexToolOutcome ? { onToolOutcome: onCodexToolOutcome } : {}),
130+
};
128131
const computerContextEpoch: {
129132
value: number;
130133
frameToolCallId?: string;
@@ -539,6 +542,7 @@ export async function prepareCodexAttemptTools(runtime: CodexAttemptRuntime) {
539542
cronCreatorToolAllowlistCaptureRef,
540543
scheduledAppAuthoritySourceRef,
541544
dynamicToolParams,
545+
compactionPlanState,
542546
computerContextEpoch,
543547
toolBridge,
544548
toolState,

‎extensions/codex/src/app-server/run-attempt.test.ts‎

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2403,10 +2403,129 @@ describe("runCodexAppServerAttempt", () => {
24032403
},
24042404
});
24052405

2406+
await harness.notify(
2407+
itemNotification("item/started", { type: "contextCompaction", id: "compact-1" }),
2408+
);
2409+
await harness.notify(
2410+
itemNotification("item/completed", { type: "contextCompaction", id: "compact-1" }),
2411+
);
2412+
const planRestoreRequest = harness.requests.find(
2413+
(request) => request.method === "thread/inject_items",
2414+
);
2415+
expect(planRestoreRequest?.params).toMatchObject({
2416+
threadId: "thread-1",
2417+
items: [
2418+
{
2419+
type: "message",
2420+
role: "user",
2421+
content: [
2422+
{
2423+
type: "input_text",
2424+
text: expect.stringContaining('"step":"Restore progress","status":"in_progress"'),
2425+
},
2426+
],
2427+
},
2428+
],
2429+
});
2430+
24062431
await harness.completeTurn({ threadId: "thread-1", turnId: "turn-1" });
24072432
await run;
24082433
});
24092434

2435+
it("does not inject plan state after compaction when the turn has no plan", async () => {
2436+
const params = createRunParams();
2437+
const harness = createStartedThreadHarness();
2438+
const run = runCodexAppServerAttempt(params);
2439+
await harness.waitForMethod("turn/start");
2440+
2441+
await harness.notify(
2442+
itemNotification("item/started", { type: "contextCompaction", id: "compact-1" }),
2443+
);
2444+
await harness.notify(
2445+
itemNotification("item/completed", { type: "contextCompaction", id: "compact-1" }),
2446+
);
2447+
expect(harness.requests.map((request) => request.method)).not.toContain("thread/inject_items");
2448+
2449+
await harness.completeTurn({ threadId: "thread-1", turnId: "turn-1" });
2450+
await run;
2451+
});
2452+
2453+
it("bounds restored plan state after compaction", async () => {
2454+
const params = createRunParams();
2455+
const harness = createStartedThreadHarness();
2456+
const run = runCodexAppServerAttempt(params);
2457+
await harness.waitForMethod("turn/start");
2458+
await harness.notify({
2459+
method: "turn/plan/updated",
2460+
params: {
2461+
threadId: "thread-1",
2462+
turnId: "turn-1",
2463+
explanation: "e".repeat(10_000),
2464+
plan: Array.from({ length: 100 }, (_, index) => ({
2465+
step: `${index}: ${"x".repeat(2_000)}`,
2466+
status: index === 0 ? "inProgress" : "pending",
2467+
})),
2468+
},
2469+
});
2470+
await harness.notify(
2471+
itemNotification("item/started", { type: "contextCompaction", id: "compact-1" }),
2472+
);
2473+
await harness.notify(
2474+
itemNotification("item/completed", { type: "contextCompaction", id: "compact-1" }),
2475+
);
2476+
2477+
const request = harness.requests.find((entry) => entry.method === "thread/inject_items");
2478+
const text = (
2479+
request?.params as { items?: Array<{ content?: Array<{ text?: string }> }> } | undefined
2480+
)?.items?.[0]?.content?.[0]?.text;
2481+
expect(text).toBeDefined();
2482+
const payloadText = text?.slice((text?.indexOf("\n") ?? -1) + 1) ?? "";
2483+
const payload = JSON.parse(payloadText) as {
2484+
explanation?: string;
2485+
plan: Array<{ step: string; status: string }>;
2486+
};
2487+
expect(Buffer.byteLength(payloadText, "utf8")).toBeLessThanOrEqual(32 * 1024);
2488+
expect(Buffer.byteLength(payload.explanation ?? "", "utf8")).toBeLessThanOrEqual(2 * 1024);
2489+
expect(payload.plan.length).toBeLessThanOrEqual(50);
2490+
expect(payload.plan.every((step) => Buffer.byteLength(step.step, "utf8") <= 512)).toBe(true);
2491+
expect(payload.plan[0]?.status).toBe("in_progress");
2492+
2493+
await harness.completeTurn({ threadId: "thread-1", turnId: "turn-1" });
2494+
await run;
2495+
});
2496+
2497+
it("continues the turn when restoring plan state after compaction fails", async () => {
2498+
const params = createRunParams();
2499+
const harness = createStartedThreadHarness(async (method) => {
2500+
if (method === "thread/inject_items") {
2501+
throw new Error("injected test failure");
2502+
}
2503+
return undefined;
2504+
});
2505+
const run = runCodexAppServerAttempt(params);
2506+
await harness.waitForMethod("turn/start");
2507+
await harness.notify({
2508+
method: "turn/plan/updated",
2509+
params: {
2510+
threadId: "thread-1",
2511+
turnId: "turn-1",
2512+
explanation: "Keep working",
2513+
plan: [{ step: "Finish safely", status: "inProgress" }],
2514+
},
2515+
});
2516+
await harness.notify(
2517+
itemNotification("item/started", { type: "contextCompaction", id: "compact-1" }),
2518+
);
2519+
await harness.notify(
2520+
itemNotification("item/completed", { type: "contextCompaction", id: "compact-1" }),
2521+
);
2522+
expect(harness.requests.map((request) => request.method)).toContain("thread/inject_items");
2523+
2524+
await harness.completeTurn({ threadId: "thread-1", turnId: "turn-1" });
2525+
const result = await run;
2526+
expect(readAttemptTerminal(result).promptError).toBeNull();
2527+
});
2528+
24102529
it("fails closed for Codex app defaults when restricted native tools have no plugin config", async () => {
24112530
testing.setOpenClawCodingToolsFactoryForTests(() => [createRuntimeDynamicTool("message")]);
24122531
const params = createRunParams();

0 commit comments

Comments
 (0)