|
| 1 | +import { |
| 2 | + embeddedAgentLog, |
| 3 | + formatErrorMessage, |
| 4 | + type EmbeddedRunAttemptParamsV2 as EmbeddedRunAttemptParams, |
| 5 | +} from "openclaw/plugin-sdk/agent-harness-runtime"; |
| 6 | +import { |
| 7 | + appendSessionTranscriptMessageByIdentity, |
| 8 | + publishSessionTranscriptUpdateByIdentity, |
| 9 | +} from "openclaw/plugin-sdk/session-transcript-runtime"; |
| 10 | + |
| 11 | +const CONTEXT_COMPACTION_CUSTOM_TYPE = "openclaw.context-compaction"; |
| 12 | + |
| 13 | +export async function persistCodexContextCompactionActivity(params: { |
| 14 | + run: EmbeddedRunAttemptParams; |
| 15 | + threadId: string; |
| 16 | + turnId: string; |
| 17 | + itemId: string; |
| 18 | + timestamp: number; |
| 19 | +}): Promise<void> { |
| 20 | + const target = params.run.sessionTarget; |
| 21 | + if (!target?.sessionId || !target.sessionKey || !target.storePath) { |
| 22 | + return; |
| 23 | + } |
| 24 | + const activityId = `codex-context-compaction:${params.threadId}:${params.turnId}:${params.itemId}`; |
| 25 | + const message = { |
| 26 | + role: "custom" as const, |
| 27 | + customType: CONTEXT_COMPACTION_CUSTOM_TYPE, |
| 28 | + content: "Context compacted", |
| 29 | + display: true, |
| 30 | + excludeFromContext: true, |
| 31 | + details: { |
| 32 | + kind: "context_compaction", |
| 33 | + backend: "codex-app-server", |
| 34 | + threadId: params.threadId, |
| 35 | + turnId: params.turnId, |
| 36 | + itemId: params.itemId, |
| 37 | + runId: params.run.runId, |
| 38 | + }, |
| 39 | + timestamp: params.timestamp, |
| 40 | + idempotencyKey: activityId, |
| 41 | + }; |
| 42 | + try { |
| 43 | + const appended = await appendSessionTranscriptMessageByIdentity({ |
| 44 | + agentId: target.agentId, |
| 45 | + sessionId: target.sessionId, |
| 46 | + sessionKey: target.sessionKey, |
| 47 | + storePath: target.storePath, |
| 48 | + config: params.run.config, |
| 49 | + cwd: params.run.workspaceDir, |
| 50 | + eventId: activityId, |
| 51 | + message, |
| 52 | + }); |
| 53 | + if (!appended?.appended) { |
| 54 | + return; |
| 55 | + } |
| 56 | + await publishSessionTranscriptUpdateByIdentity({ |
| 57 | + agentId: target.agentId, |
| 58 | + sessionId: target.sessionId, |
| 59 | + sessionKey: target.sessionKey, |
| 60 | + storePath: target.storePath, |
| 61 | + update: { |
| 62 | + message: appended.message, |
| 63 | + messageId: appended.messageId, |
| 64 | + runId: params.run.runId, |
| 65 | + }, |
| 66 | + }); |
| 67 | + } catch (error) { |
| 68 | + embeddedAgentLog.warn("failed to persist codex context compaction activity", { |
| 69 | + error: formatErrorMessage(error), |
| 70 | + itemId: params.itemId, |
| 71 | + }); |
| 72 | + } |
| 73 | +} |
0 commit comments