Skip to content

Commit 8885be4

Browse files
authored
fix(codex): refresh session meters after /codex compact (#123640)
* fix(codex): route compact through session pipeline Route /codex compact through host-owned manual compaction so native completion and token snapshots update session meters, and report the terminal outcome to the user. * test(codex): cover unavailable compact outcome * fix(plugins): fence command compaction capability Bind compactCurrent to one command invocation and captured session generation so retained or stale callbacks fail closed without running compaction. * fix(plugins): lazy-load command session revalidation Keep compaction session freshness checks at the auto-reply owner without pulling the session accessor into generic plugin command module initialization. * fix(plugins): keep session revalidation lazy Avoid loading the session accessor through generic plugin command initialization while preserving pre-compaction session-generation checks. * fix(compaction): fence session lifecycle admission Revalidate the exact session id and lifecycle revision immediately before native compaction and again before accounting so resets and rebinds fail closed across awaited work. * fix(commands): fence plugin compaction authority * fix(compaction): require accounting commit * test(compaction): keep regression under lint cap * fix(codex): preserve compact admission * fix(codex): preserve compaction target identity * fix(compaction): bind admitted target * fix(compaction): fence accounting commit
1 parent 3ac267f commit 8885be4

17 files changed

Lines changed: 1035 additions & 126 deletions

‎docs/plugins/codex-harness.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -505,6 +505,7 @@ Keep provider refs and runtime policy separate:
505505
| Resume a stored Codex CLI session as a paired-node turn | `/codex sessions --host <node> [filter]`, then `/codex resume <session-id> --host <node> --bind here` |
506506
| View non-archived Codex sessions across computers | Enable Codex supervision and open **Codex Sessions** |
507507
| Change the bound thread's model, fast-mode, or permissions | `/codex model <model>`, `/codex fast [on\|off\|status]`, `/codex permissions [default\|yolo\|status]` |
508+
| Compact the current Codex session | `/codex compact` |
508509
| Stop or steer the active turn | `/codex stop`, `/codex steer <text>` |
509510
| Detach the current binding | `/codex detach` (alias `/codex unbind`) |
510511
| Send Codex feedback only | `/codex diagnostics [note]` |
@@ -728,7 +729,9 @@ Common forms:
728729
- `/codex stop` stops the active turn; `/codex steer <text>` steers it.
729730
- `/codex model <model>`, `/codex fast [on|off|status]`, and
730731
`/codex permissions [default|yolo|status]` change per-conversation state.
731-
- `/codex compact` asks Codex app-server to compact the attached thread.
732+
- `/codex compact` runs the same completion and session-accounting pipeline as
733+
`/compact`, then reports whether Codex compacted the session and the resulting
734+
token count. If compaction is skipped or fails, the reply includes the reason.
732735
- `/codex review` starts Codex native review for the attached thread.
733736
- `/codex diagnostics [note]` asks before sending Codex feedback for the
734737
attached thread.

‎docs/plugins/sdk-runtime.md‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,36 @@ return {
121121
Use `openclaw/plugin-sdk/pair-loop-guard-runtime` directly only for custom
122122
two-party event loops that do not go through the shared inbound reply runner.
123123

124+
## Plugin command runtime helpers
125+
126+
Plugin command handlers receive request-bound capabilities through
127+
`ctx.runtimeContext`. When the command is bound to a current session,
128+
`ctx.runtimeContext.compactCurrent()` runs the same manual compaction
129+
pipeline as `/compact`, including native agent-harness completion and session
130+
token accounting:
131+
132+
```typescript
133+
const compactCurrent = ctx.runtimeContext?.compactCurrent;
134+
if (!compactCurrent) {
135+
return { text: "This command needs a bound session." };
136+
}
137+
138+
const result = await compactCurrent();
139+
return {
140+
text: result.compacted
141+
? `Compacted to ${result.tokensAfter ?? "an unknown number of"} tokens.`
142+
: `Compaction did not complete: ${result.reason ?? "unknown reason"}.`,
143+
};
144+
```
145+
146+
This general capability is available to every plugin command, not only Codex.
147+
The host gates it to the current invocation and exact bound session generation.
148+
The capability is absent when no current session is bound; a retained callback
149+
fails closed after the handler settles. Do not retain it or reconstruct
150+
compaction with session-store patches and harness calls. The result contains
151+
`compacted`, optional `reason`, and optional `tokensBefore` and `tokensAfter`
152+
snapshots; OpenClaw owns all persistence and lifecycle coordination.
153+
124154
## Runtime namespaces
125155

126156
<AccordionGroup>

‎extensions/codex/src/app-server/capabilities.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ export const CODEX_CONTROL_METHODS = {
99
installedApps: "app/installed",
1010
listApps: "app/list",
1111
readApps: "app/read",
12-
compact: "thread/compact/start",
1312
feedback: "feedback/upload",
1413
forkThread: "thread/fork",
1514
listHooks: "hooks/list",

‎extensions/codex/src/command-handler-actions.ts‎

Lines changed: 58 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
import { MODEL_SELECTION_LOCKED_MESSAGE } from "openclaw/plugin-sdk/model-session-runtime";
1+
import {
2+
MODEL_SELECTION_LOCKED_MESSAGE,
3+
resolvePersistedSessionRuntimeId,
4+
} from "openclaw/plugin-sdk/model-session-runtime";
25
import type { PluginCommandContext } from "openclaw/plugin-sdk/plugin-entry";
36
import { getSessionEntry, resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime";
47
import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
@@ -9,6 +12,8 @@ import {
912
resolveCodexNativeExecutionBlock,
1013
resolveCodexNativeSandboxBlock,
1114
} from "./app-server/sandbox-guard.js";
15+
import { sessionBindingIdentity } from "./app-server/session-binding.js";
16+
import { isSameCodexAppServerThreadOwner } from "./app-server/thread-ownership.js";
1217
import { canMutateCodexHost } from "./command-authorization.js";
1318
import { formatCodexDisplayText, formatComputerUseStatus } from "./command-formatters.js";
1419
import {
@@ -422,35 +427,79 @@ export async function startThreadAction(
422427
kind: "compact" | "review",
423428
args: string[],
424429
): Promise<string> {
425-
const label = kind === "compact" ? "compaction" : "review";
426430
if (args.length > 0) {
427-
return `Usage: /codex ${label === "compaction" ? "compact" : label}`;
431+
return `Usage: /codex ${kind}`;
428432
}
429433
const target = await resolveControlTarget(ctx);
430434
if (!target) {
431-
return `Cannot start Codex ${label} because this command did not include a stable binding identity.`;
435+
return `Cannot start Codex ${kind === "compact" ? "compaction" : "review"} because this command did not include a stable binding identity.`;
432436
}
433437
const binding = await deps.bindingStore.read(target.identity);
434438
if (!binding?.threadId) {
435439
return `No Codex thread is attached to this OpenClaw session yet.`;
436440
}
441+
if (kind === "compact") {
442+
const sessionTarget = ctx.sessionTarget;
443+
if (
444+
!ctx.sessionId ||
445+
!ctx.sessionKey ||
446+
!sessionTarget ||
447+
sessionTarget.sessionId !== ctx.sessionId ||
448+
sessionTarget.sessionKey !== ctx.sessionKey
449+
) {
450+
return "Codex compaction is unavailable because this command is not bound to a complete session identity.";
451+
}
452+
const currentSession = getSessionEntry({
453+
storePath: sessionTarget.storePath,
454+
sessionKey: ctx.sessionKey,
455+
hydrateSkillPromptRefs: false,
456+
readConsistency: "latest",
457+
});
458+
if (
459+
currentSession?.sessionId !== ctx.sessionId ||
460+
resolvePersistedSessionRuntimeId(currentSession) !== "codex"
461+
) {
462+
return "Codex compaction is unavailable because the current OpenClaw session is not using the Codex runtime.";
463+
}
464+
if (target.identity.kind === "conversation") {
465+
const sessionBinding = ctx.sessionId
466+
? await deps.bindingStore.read(
467+
sessionBindingIdentity({
468+
sessionId: ctx.sessionId,
469+
sessionKey: ctx.sessionKey,
470+
agentId: sessionTarget.agentId,
471+
config: ctx.config,
472+
}),
473+
)
474+
: undefined;
475+
if (!isSameCodexAppServerThreadOwner(binding, sessionBinding)) {
476+
return "Codex compaction is unavailable because the conversation-bound thread differs from the current session binding. Resume that thread into the session first.";
477+
}
478+
}
479+
const compactCurrent = ctx.runtimeContext?.compactCurrent;
480+
if (!compactCurrent) {
481+
return "Codex compaction is unavailable because this command is not bound to a session.";
482+
}
483+
const result = await compactCurrent();
484+
return result.compacted
485+
? `Compacted Codex session (${result.tokensAfter ?? "unknown"} tokens after).`
486+
: `Codex compaction did not complete: ${formatCodexDisplayText(result.reason ?? "no reason returned")}.`;
487+
}
437488
const connection = resolveCodexBindingAppServerConnection({
438489
binding,
439490
authProfileId: binding.authProfileId,
440491
pluginConfig,
441492
});
442493
await deps.codexControlRequest(
443494
pluginConfig,
444-
kind === "compact" ? CODEX_CONTROL_METHODS.compact : CODEX_CONTROL_METHODS.review,
445-
kind === "review"
446-
? { threadId: binding.threadId, target: { type: "uncommittedChanges" } }
447-
: { threadId: binding.threadId },
495+
CODEX_CONTROL_METHODS.review,
496+
{ threadId: binding.threadId, target: { type: "uncommittedChanges" } },
448497
{
449498
agentDir: target.agentDir,
450499
authProfileId: connection.clientAuthProfileId,
451500
config: ctx.config,
452501
...(connection.usesSupervisionConnection ? { startOptions: connection.appServer.start } : {}),
453502
},
454503
);
455-
return `Started Codex ${label} for thread ${formatCodexDisplayText(binding.threadId)}.`;
504+
return `Started Codex review for thread ${formatCodexDisplayText(binding.threadId)}.`;
456505
}

‎extensions/codex/src/command-rpc.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,8 +73,8 @@ describe("Codex command RPC helpers", () => {
7373

7474
await codexControlRequest(
7575
{},
76-
"thread/compact/start",
77-
{ threadId: "thread-1" },
76+
"thread/list",
77+
{ archived: false },
7878
{
7979
authProfileId: null,
8080
},

0 commit comments

Comments
 (0)