Skip to content

Commit b8f82b5

Browse files
committed
feat(skills): enable Codex experience review
1 parent b7cc681 commit b8f82b5

9 files changed

Lines changed: 134 additions & 19 deletions

File tree

‎docs/tools/self-learning.md‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,11 @@ Experience review is deliberately delayed and bounded:
126126
- If any agent or reply run is still active, review waits another 30 seconds.
127127
- Only one experience review runs at a time.
128128
- Delayed review is process-local Gateway work. The Gateway must remain running
129-
through the idle window; one-shot local and CLI-backed runtimes do not retain
130-
enough trajectory and tool-availability context to schedule it.
129+
through the idle window. CLI-backed harnesses can schedule review only when
130+
they report the resolved model, exact model-iteration count, and actual
131+
`skill_workshop` availability. The Codex app-server harness reports those
132+
facts for its `openai/*` sessions; runtimes with missing facts still fail
133+
closed.
131134

132135
The foreground answer is never delayed for learning. A failed or ineligible
133136
turn does not start experience review, although direct user corrections can
@@ -140,6 +143,12 @@ recent user message. The rendered trajectory is capped at 60,000 characters;
140143
when necessary, OpenClaw keeps the first message and the newest evidence and
141144
marks the omitted middle.
142145

146+
For Codex app-server sessions, OpenClaw counts unique upstream response
147+
completions as model iterations and uses the harness's frozen current-turn
148+
projection. The harness also attempts to mirror that projection into the agent's
149+
SQLite transcript before delayed review is scheduled; the reviewer does not
150+
need to reread the database.
151+
143152
The reviewer reuses the resolved provider and model. It reuses the foreground
144153
auth profile when that identity is available and disables model fallbacks. The
145154
review therefore starts an additional model run on the configured provider.

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

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { normalizeUsage } from "openclaw/plugin-sdk/agent-harness-runtime";
2-
import { readNonNegativeInteger, readNumber } from "./event-projector-values.js";
2+
import { readNonNegativeInteger, readNumber, readString } from "./event-projector-values.js";
33
import { isJsonObject, type JsonObject } from "./protocol.js";
44

55
function readTokenCount(record: JsonObject, key: string): number | undefined {
@@ -110,3 +110,28 @@ export function normalizeCodexResponseTokenUsage(
110110
},
111111
};
112112
}
113+
114+
export class CodexResponseCompletionProjection {
115+
// Replayed notifications keep one upstream response equal to one model iteration.
116+
private readonly responseIds = new Set<string>();
117+
usage: ReturnType<typeof normalizeUsage>;
118+
119+
get modelIterations(): number {
120+
return this.responseIds.size;
121+
}
122+
123+
clear(): void {
124+
this.usage = undefined;
125+
}
126+
127+
record(params: JsonObject): void {
128+
const responseId = readString(params, "responseId");
129+
if (responseId) {
130+
this.responseIds.add(responseId);
131+
}
132+
const usage = isJsonObject(params.usage) ? params.usage : undefined;
133+
// Every provider completion replaces the prior response snapshot. A final
134+
// response with missing or malformed usage must leave freshness unknown.
135+
this.usage = usage ? normalizeCodexResponseTokenUsage(usage) : undefined;
136+
}
137+
}

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

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ import { buildCodexMessagesSnapshot } from "./event-projector-snapshot.js";
2929
import { CodexToolProgressProjection } from "./event-projector-tool-progress.js";
3030
import { CodexToolTranscriptProjection } from "./event-projector-tool-transcript.js";
3131
import {
32-
normalizeCodexResponseTokenUsage,
32+
CodexResponseCompletionProjection,
3333
normalizeCodexThreadTokenUsage,
3434
projectCodexThreadUsageUpdate,
3535
} from "./event-projector-usage.js";
@@ -106,7 +106,7 @@ export class CodexAppServerEventProjector {
106106
private synthesizedMissingToolResultError: string | null = null;
107107
private aborted = false;
108108
private tokenUsage: ReturnType<typeof normalizeCodexThreadTokenUsage>;
109-
private responseUsage: ReturnType<typeof normalizeCodexResponseTokenUsage>;
109+
private readonly responseCompletions = new CodexResponseCompletionProjection();
110110
private completedCompactionCount = 0;
111111
private lastTranscriptTimestamp = 0;
112112

@@ -288,13 +288,13 @@ export class CodexAppServerEventProjector {
288288
await this.handleTurnCompleted(params);
289289
break;
290290
case "rawResponse/completed":
291-
this.handleRawResponseCompleted(params);
291+
this.responseCompletions.record(params);
292292
break;
293293
case "rawResponseItem/completed":
294294
await this.handleRawResponseItemCompleted(params);
295295
break;
296296
case "error":
297-
this.responseUsage = undefined;
297+
this.responseCompletions.clear();
298298
if (params.willRetry === true) {
299299
break;
300300
}
@@ -334,7 +334,9 @@ export class CodexAppServerEventProjector {
334334
// A terminal timeout must not publish exact usage, but the timeout watcher
335335
// can still recover a completed assistant. Keep the snapshot masked until
336336
// recovery clears the abort instead of destroying it in markTimedOut().
337-
const projectedUsage = this.aborted ? this.tokenUsage : (this.responseUsage ?? this.tokenUsage);
337+
const projectedUsage = this.aborted
338+
? this.tokenUsage
339+
: (this.responseCompletions.usage ?? this.tokenUsage);
338340
const hasAssistantItemText = this.assistantProjection.hasAssistantItemTextForSynthesis();
339341
const legacyFailClosed =
340342
!this.completedTurn || this.completedTurn.status !== "completed" || hasAssistantItemText;
@@ -416,6 +418,9 @@ export class CodexAppServerEventProjector {
416418
...(agentHarnessResultClassification ? { agentHarnessResultClassification } : {}),
417419
bootstrapPromptWarningSignaturesSeen: this.params.bootstrapPromptWarningSignaturesSeen,
418420
bootstrapPromptWarningSignature: this.params.bootstrapPromptWarningSignature,
421+
...(this.responseCompletions.modelIterations > 0
422+
? { modelIterations: this.responseCompletions.modelIterations }
423+
: {}),
419424
messagesSnapshot,
420425
assistantTexts,
421426
toolMetas,
@@ -483,7 +488,7 @@ export class CodexAppServerEventProjector {
483488

484489
markAborted(): void {
485490
this.aborted = true;
486-
this.responseUsage = undefined;
491+
this.responseCompletions.clear();
487492
}
488493

489494
isCompacting(): boolean {
@@ -594,21 +599,14 @@ export class CodexAppServerEventProjector {
594599
});
595600
}
596601

597-
private handleRawResponseCompleted(params: JsonObject): void {
598-
const usage = isJsonObject(params.usage) ? params.usage : undefined;
599-
// Every provider completion replaces the prior response snapshot. A final
600-
// response with missing or malformed usage must leave freshness unknown.
601-
this.responseUsage = usage ? normalizeCodexResponseTokenUsage(usage) : undefined;
602-
}
603-
604602
private async handleTurnCompleted(params: JsonObject): Promise<void> {
605603
const turn = readCodexTurn(params.turn);
606604
if (!turn || turn.id !== this.turnId) {
607605
return;
608606
}
609607
this.completedTurn = turn;
610608
if (turn.status !== "completed") {
611-
this.responseUsage = undefined;
609+
this.responseCompletions.clear();
612610
}
613611
if (turn.status === "failed") {
614612
const usageLimitMessage = formatCodexUsageLimitErrorMessage({

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,18 @@ describe("CodexAppServerEventProjector usage projection", () => {
8383
});
8484
});
8585

86+
it("counts unique upstream responses as model iterations", async () => {
87+
const projector = await createProjector();
88+
89+
for (const responseId of ["response-1", "response-1", "response-2"]) {
90+
await projector.handleNotification(
91+
forCurrentTurn("rawResponse/completed", { responseId, usage: null }),
92+
);
93+
}
94+
95+
expect(projector.buildResult(buildEmptyToolTelemetry()).modelIterations).toBe(2);
96+
});
97+
8698
it("keeps cumulative-only thread usage unknown", async () => {
8799
const projector = await createProjector();
88100

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

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
resolveCodexAppServerReplayBlockedReason,
1818
} from "./attempt-results.js";
1919
import { attemptTerminal, type EmbeddedRunAttemptResult } from "./attempt-terminal.js";
20+
import { flattenCodexDynamicToolFunctions } from "./protocol.js";
2021
import { readCodexRateLimitsRevision, readRecentCodexRateLimits } from "./rate-limit-cache.js";
2122
import type { CodexAttemptActiveTurn } from "./run-attempt-active-turn.js";
2223
import type { CodexAttemptLifecycleController } from "./run-attempt-lifecycle-controller.js";
@@ -433,7 +434,31 @@ export async function finalizeCodexAttempt(
433434
...(finalPromptError ? { error: formatErrorMessage(finalPromptError) } : {}),
434435
durationMs: Date.now() - attemptStartedAt,
435436
},
436-
ctx: hookContext,
437+
ctx: {
438+
...hookContext,
439+
modelProviderId: resourceState.thread.modelProvider ?? effectiveRuntimeProviderId,
440+
modelId: resourceState.thread.model ?? effectiveRuntimeModelId,
441+
authProfileId: resourceState.thread.authProfileId ?? startupAuthProfileId,
442+
modelIterations: result.modelIterations ?? 0,
443+
skillWorkshopAvailable: flattenCodexDynamicToolFunctions(
444+
attemptTools.toolBridge.availableSpecs,
445+
).some((tool) => tool.name === "skill_workshop"),
446+
compacted: (result.compactionCount ?? 0) > 0,
447+
messageChannel: params.messageChannel,
448+
messageProvider: params.messageProvider,
449+
chatType: params.chatType,
450+
agentAccountId: params.agentAccountId,
451+
groupId: params.groupId,
452+
groupChannel: params.groupChannel,
453+
groupSpace: params.groupSpace,
454+
memberRoleIds: params.memberRoleIds,
455+
spawnedBy: params.spawnedBy,
456+
senderId: params.senderId ?? undefined,
457+
senderName: params.senderName,
458+
senderUsername: params.senderUsername,
459+
senderE164: params.senderE164,
460+
senderIsOwner: params.senderIsOwner,
461+
},
437462
hookRunner,
438463
});
439464
state.shouldDelayNativeHookRelayUnregister =

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,8 @@ export type EmbeddedRunAttemptResult = {
242242
bootstrapPromptWarningSignature?: string;
243243
systemPromptReport?: SessionSystemPromptReport;
244244
finalPromptText?: string;
245+
/** Exact provider-response count when the harness can observe model iterations directly. */
246+
modelIterations?: number;
245247
messagesSnapshot: AgentMessage[];
246248
/**
247249
* Complete application transcript frozen through a settled tool boundary.

‎src/agents/harness/agent-end-side-effects.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ type BaseAgentEndSideEffectsParams = Parameters<typeof runAgentHarnessAgentEndHo
1717
type AgentEndSideEffectsParams = Omit<BaseAgentEndSideEffectsParams, "ctx"> & {
1818
ctx: BaseAgentEndSideEffectsParams["ctx"] & {
1919
authProfileId?: string;
20+
modelIterations?: number;
2021
skillWorkshopAvailable?: boolean;
2122
compacted?: boolean;
2223
messageChannel?: string | null;

‎src/skills/workshop/experience-review.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ function completedRun(
1919
skillWorkshopAvailable?: boolean;
2020
compacted?: boolean;
2121
modelMetadata?: boolean;
22+
modelIterations?: number;
2223
} = {},
2324
): SkillExperienceReviewParams {
2425
const iterations = options.iterations ?? 10;
@@ -53,6 +54,9 @@ function completedRun(
5354
authProfileId: "openai:work",
5455
}),
5556
skillWorkshopAvailable: options.skillWorkshopAvailable ?? true,
57+
...(options.modelIterations === undefined
58+
? {}
59+
: { modelIterations: options.modelIterations }),
5660
compacted: options.compacted,
5761
trigger: "user",
5862
},
@@ -92,6 +96,36 @@ describe("skill experience review scheduler", () => {
9296
scheduler.clear();
9397
});
9498

99+
it("uses exact harness iterations for a Codex-style projected trajectory", async () => {
100+
vi.useFakeTimers();
101+
const runReview = vi.fn().mockResolvedValue(undefined);
102+
const scheduler = createSkillExperienceReviewScheduler({
103+
isSystemActive: () => false,
104+
runReview,
105+
});
106+
107+
scheduler.schedule(completedRun({ iterations: 1, modelIterations: 10 }));
108+
await vi.advanceTimersByTimeAsync(30_000);
109+
110+
expect(runReview).toHaveBeenCalledWith(expect.objectContaining({ modelIterations: 10 }));
111+
scheduler.clear();
112+
});
113+
114+
it("does not infer iterations when a harness explicitly reports none", async () => {
115+
vi.useFakeTimers();
116+
const runReview = vi.fn().mockResolvedValue(undefined);
117+
const scheduler = createSkillExperienceReviewScheduler({
118+
isSystemActive: () => false,
119+
runReview,
120+
});
121+
122+
scheduler.schedule(completedRun({ iterations: 10, modelIterations: 0 }));
123+
await vi.runAllTimersAsync();
124+
125+
expect(runReview).not.toHaveBeenCalled();
126+
scheduler.clear();
127+
});
128+
95129
it("rechecks current autonomy and tool policy before a delayed review", async () => {
96130
vi.useFakeTimers();
97131
const runReview = vi.fn().mockResolvedValue(undefined);

‎src/skills/workshop/experience-review.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ type ExperienceReviewAgentContext = {
4242
modelProviderId?: string;
4343
modelId?: string;
4444
authProfileId?: string;
45+
modelIterations?: number;
4546
skillWorkshopAvailable?: boolean;
4647
compacted?: boolean;
4748
trigger?: string;
@@ -300,7 +301,15 @@ export function createSkillExperienceReviewScheduler(deps: ExperienceReviewSched
300301
}
301302

302303
const turnMessages = currentTurnMessages(params.event.messages);
303-
const modelIterations = countModelIterations(turnMessages);
304+
// Native harnesses can report exact provider iterations even when their
305+
// transcript projection has a different assistant-message cardinality.
306+
const reportedModelIterations = params.ctx.modelIterations;
307+
const modelIterations =
308+
reportedModelIterations === undefined
309+
? countModelIterations(turnMessages)
310+
: Number.isSafeInteger(reportedModelIterations) && reportedModelIterations >= 0
311+
? reportedModelIterations
312+
: 0;
304313
if (params.event.success && modelIterations >= EXPERIENCE_REVIEW_MIN_MODEL_ITERATIONS) {
305314
if (!existing && pendingBySession.size >= EXPERIENCE_REVIEW_MAX_PENDING) {
306315
const oldest = pendingBySession.entries().next().value as

0 commit comments

Comments
 (0)