Skip to content

Commit 8ebf199

Browse files
fix(codex): bound restored plan context
1 parent 80284b4 commit 8ebf199

2 files changed

Lines changed: 97 additions & 12 deletions

File tree

‎extensions/codex/src/app-server/plan-compaction-state.ts‎

Lines changed: 53 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { Buffer } from "node:buffer";
12
import type { EmbeddedRunAttemptParams } from "openclaw/plugin-sdk/agent-harness-runtime";
23
import type { AgentPlanStep } from "openclaw/plugin-sdk/channel-outbound";
34
import type { CodexAppServerClient } from "./client.js";
@@ -9,6 +10,11 @@ const RESTORED_PLAN_PREAMBLE =
910
"OpenClaw restored the active task list after context compaction. " +
1011
"This is application state, not a new user request. Continue the current task and call " +
1112
"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 = "…";
1218

1319
/** Retains the latest projected plan so Codex compaction cannot discard it. */
1420
export class CodexCompactionPlanState {
@@ -18,16 +24,11 @@ export class CodexCompactionPlanState {
1824
if (event.stream !== "plan") {
1925
return;
2026
}
21-
const steps = readPlanSteps(event.data.steps);
22-
if (steps.length === 0) {
27+
const plan = readBoundedPlan(event.data.explanation, event.data.steps);
28+
if (!plan) {
2329
return;
2430
}
25-
this.latestPlan = {
26-
...(typeof event.data.explanation === "string"
27-
? { explanation: event.data.explanation }
28-
: {}),
29-
steps,
30-
};
31+
this.latestPlan = plan;
3132
}
3233

3334
async restore(params: {
@@ -50,10 +51,7 @@ export class CodexCompactionPlanState {
5051
content: [
5152
{
5253
type: "input_text",
53-
text: `${RESTORED_PLAN_PREAMBLE}\n${JSON.stringify({
54-
explanation: this.latestPlan.explanation,
55-
plan: this.latestPlan.steps,
56-
})}`,
54+
text: `${RESTORED_PLAN_PREAMBLE}\n${serializePlan(this.latestPlan)}`,
5755
},
5856
],
5957
},
@@ -64,6 +62,49 @@ export class CodexCompactionPlanState {
6462
}
6563
}
6664

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+
67108
function readPlanSteps(value: unknown): AgentPlanStep[] {
68109
if (!Array.isArray(value)) {
69110
return [];

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

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2450,6 +2450,50 @@ describe("runCodexAppServerAttempt", () => {
24502450
await run;
24512451
});
24522452

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+
24532497
it("continues the turn when restoring plan state after compaction fails", async () => {
24542498
const params = createRunParams();
24552499
const harness = createStartedThreadHarness(async (method) => {

0 commit comments

Comments
 (0)