@openclaw/codex 2026.7.2-beta.3 → 2026.7.2-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/{app-server-policy-DUMF2Xyr.js → app-server-policy-BmDgseo_.js} +1 -1
  2. package/dist/attempt-client-cleanup-Ia52yRWc.js +127 -0
  3. package/dist/{attempt-notifications-Ecjyzufe.js → attempt-notifications-CMR2_fmR.js} +1 -1
  4. package/dist/{media-understanding-provider-IPNNQre6.js → bounded-turn-FEbUXoYT.js} +71 -188
  5. package/dist/capabilities-BHRSI6Cn.js +36 -0
  6. package/dist/cli-metadata.js +1 -1
  7. package/dist/{command-formatters-NCTL7A2q.js → command-formatters-ico4ZFnk.js} +3 -37
  8. package/dist/{command-handlers-DtFbZiba.js → command-handlers-CRmnwI2N.js} +1233 -1221
  9. package/dist/{compact-Kgy26gIM.js → compact-dEN49UH6.js} +8 -7
  10. package/dist/{computer-use-C7x4ZaqR.js → computer-use-BjGylO-E.js} +16 -6
  11. package/dist/{conversation-control-B0s3aIjT.js → conversation-control-DE7d9DOj.js} +6 -5
  12. package/dist/doctor-contract-api.js +24 -86
  13. package/dist/{dynamic-tools-D_vSVmv9.js → dynamic-tools-LIt9ojep.js} +135 -2696
  14. package/dist/event-projector-assistant-message-DTgnPPVF.js +101 -0
  15. package/dist/event-projector-usage-tvgb1NCX.js +69 -0
  16. package/dist/harness.js +31 -11
  17. package/dist/incognito-session-ET_ufDH-.js +2 -0
  18. package/dist/index.js +250 -275
  19. package/dist/media-understanding-provider.js +173 -1
  20. package/dist/{models-DD5zBdX5.js → models-BA01NEez.js} +2 -2
  21. package/dist/{notification-correlation-C8DVQ_Bq.js → notification-correlation-Bj_Ak_jI.js} +3 -3
  22. package/dist/{plugin-app-cache-key-DJbhLYSK.js → plugin-app-cache-key-DSXX-rXO.js} +5 -5
  23. package/dist/{transcript-mirror-D9rTxx2P.js → protocol-validators-Dm4eXZmt.js} +335 -595
  24. package/dist/{rate-limits-CqhWQ2R9.js → rate-limits-S_PXs0ul.js} +1 -1
  25. package/dist/realtime-voice-api-BPcA1uN9.js +494 -0
  26. package/dist/realtime-voice-api.js +2 -0
  27. package/dist/{request-9yf9pZjf.js → request-CXpPennK.js} +1 -1
  28. package/dist/{run-attempt-BIoO8ISr.js → run-attempt-C5GTPJOE.js} +3111 -387
  29. package/dist/{session-binding-Bmt20HfB.js → session-binding-DlVQ-Pxs.js} +957 -890
  30. package/dist/{session-catalog-CA7R-hX2.js → session-catalog-CP2oCcEb.js} +98 -87
  31. package/dist/{session-cli-Bxk3-Wqz.js → session-cli-CqZ0Fp2a.js} +2 -2
  32. package/dist/session-upstream-marker-QE-m5QFG.js +82 -0
  33. package/dist/settled-turn-finalizer-CA_2QXIE.js +303 -0
  34. package/dist/{shared-client-CSXLtCLE.js → shared-client-BVKE40c-.js} +1870 -1694
  35. package/dist/{side-question-DtzquMOb.js → side-question-CO12sHxo.js} +24 -16
  36. package/dist/{thread-lifecycle-CQ_9mAa1.js → thread-lifecycle-DRg_FdzC.js} +127 -153
  37. package/dist/transcript-mirror-uKA-A4tB.js +550 -0
  38. package/dist/upstream-session-fork-_Vrz4WJr.js +320 -0
  39. package/dist/{usage-CuPpFgTc.js → usage-UpVbdX5G.js} +3 -3
  40. package/dist/{web-search-provider.runtime-_x5XTeqh.js → web-search-provider.runtime-CaQMYDbp.js} +3 -3
  41. package/package.json +7 -8
  42. package/npm-shrinkwrap.json +0 -202
  43. package/dist/{auth-binding-C1czuHPA.js → auth-binding-B4FfbcCg.js} +1 -1
@@ -0,0 +1,550 @@
1
+ import { embeddedAgentLog, formatErrorMessage, projectAgentHarnessTranscriptMessageForDisplay, runAgentHarnessBeforeMessageWriteHook } from "openclaw/plugin-sdk/agent-harness-runtime";
2
+ import { createHash } from "node:crypto";
3
+ import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
4
+ import { Buffer } from "node:buffer";
5
+ import { publishSessionTranscriptUpdateByIdentity, withSessionTranscriptWriteLock } from "openclaw/plugin-sdk/session-transcript-runtime";
6
+ //#region extensions/codex/src/app-server/upstream-prompt-provenance.ts
7
+ const UPSTREAM_USER_TEXT_META_KEY = "upstreamUserText";
8
+ const MIRROR_IDENTITY_META_KEY = "mirrorIdentity";
9
+ function attachCodexMirrorIdentity(message, identity) {
10
+ const record = message;
11
+ const existing = record["__openclaw"];
12
+ const baseMeta = existing && typeof existing === "object" && !Array.isArray(existing) ? existing : {};
13
+ return {
14
+ ...record,
15
+ __openclaw: {
16
+ ...baseMeta,
17
+ [MIRROR_IDENTITY_META_KEY]: identity
18
+ }
19
+ };
20
+ }
21
+ function readMirrorIdentity(message) {
22
+ const meta = message["__openclaw"];
23
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)) return;
24
+ const id = meta[MIRROR_IDENTITY_META_KEY];
25
+ return typeof id === "string" && id ? id : void 0;
26
+ }
27
+ function attachUpstreamUserText(message, text) {
28
+ const record = message;
29
+ const existing = record["__openclaw"];
30
+ const baseMeta = existing && typeof existing === "object" && !Array.isArray(existing) ? existing : {};
31
+ return {
32
+ ...record,
33
+ __openclaw: {
34
+ ...baseMeta,
35
+ [UPSTREAM_USER_TEXT_META_KEY]: text
36
+ }
37
+ };
38
+ }
39
+ function readUpstreamUserText(message) {
40
+ const meta = message?.["__openclaw"];
41
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)) return;
42
+ const text = meta[UPSTREAM_USER_TEXT_META_KEY];
43
+ return typeof text === "string" && text ? text : void 0;
44
+ }
45
+ //#endregion
46
+ //#region extensions/codex/src/app-server/transcript-mirror-attestation.ts
47
+ const MIRROR_ORIGIN_META_KEY = "mirrorOrigin";
48
+ const MIRROR_SOURCE_FINGERPRINT_META_KEY = "mirrorSourceFingerprint";
49
+ const CODEX_APP_SERVER_MIRROR_ORIGIN = "codex-app-server";
50
+ function attachCodexMirrorAttestation(message, sourceFingerprint) {
51
+ const record = message;
52
+ const existing = record["__openclaw"];
53
+ const baseMeta = existing && typeof existing === "object" && !Array.isArray(existing) ? existing : {};
54
+ return {
55
+ ...record,
56
+ __openclaw: {
57
+ ...baseMeta,
58
+ [MIRROR_ORIGIN_META_KEY]: CODEX_APP_SERVER_MIRROR_ORIGIN,
59
+ ...sourceFingerprint ? { [MIRROR_SOURCE_FINGERPRINT_META_KEY]: sourceFingerprint } : {}
60
+ }
61
+ };
62
+ }
63
+ function readCodexMirrorSourceFingerprint(message) {
64
+ const meta = message["__openclaw"];
65
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)) return;
66
+ const value = meta[MIRROR_SOURCE_FINGERPRINT_META_KEY];
67
+ return typeof value === "string" && value ? value : void 0;
68
+ }
69
+ function serializeCodexMirrorSourceEvidence(message) {
70
+ const record = message;
71
+ return JSON.stringify({
72
+ role: message.role,
73
+ content: record.content,
74
+ ...message.role === "user" ? { upstreamUserText: readUpstreamUserText(message) } : {},
75
+ ...message.role === "toolResult" ? {
76
+ toolCallId: record.toolCallId,
77
+ toolName: record.toolName,
78
+ isError: record.isError === true
79
+ } : {}
80
+ });
81
+ }
82
+ function fingerprintCodexMirrorSourceMessage(message) {
83
+ return createHash("sha256").update(serializeCodexMirrorSourceEvidence(message)).digest("hex").slice(0, 32);
84
+ }
85
+ //#endregion
86
+ //#region extensions/codex/src/app-server/user-prompt-message.ts
87
+ function buildSenderLabel(params) {
88
+ const label = params.senderName ?? params.senderUsername ?? params.senderE164 ?? params.senderId;
89
+ if (!label) return;
90
+ return !params.senderId || label.includes(params.senderId) ? label : `${label} (${params.senderId})`;
91
+ }
92
+ function buildFromPrepared(params, preparedUserMessage) {
93
+ const senderId = normalizeOptionalString(params.senderId);
94
+ const senderName = normalizeOptionalString(params.senderName);
95
+ const senderUsername = normalizeOptionalString(params.senderUsername);
96
+ const senderE164 = normalizeOptionalString(params.senderE164);
97
+ const senderLabel = buildSenderLabel({
98
+ senderId,
99
+ senderName,
100
+ senderUsername,
101
+ senderE164
102
+ });
103
+ const sourceChannel = normalizeOptionalString(params.inputProvenance?.sourceChannel ?? params.messageChannel ?? params.messageProvider);
104
+ return {
105
+ role: "user",
106
+ timestamp: Date.now(),
107
+ ...params.inputProvenance ? { provenance: params.inputProvenance } : {},
108
+ ...sourceChannel ? { sourceChannel } : {},
109
+ ...senderId ? { senderId } : {},
110
+ ...senderName ? { senderName } : {},
111
+ ...senderUsername ? { senderUsername } : {},
112
+ ...senderE164 ? { senderE164 } : {},
113
+ ...senderLabel ? { senderLabel } : {},
114
+ ...preparedUserMessage ? preparedUserMessage : { content: params.prompt }
115
+ };
116
+ }
117
+ function buildCodexUserPromptMessage(params) {
118
+ return buildFromPrepared(params, params.userTurnTranscriptRecorder?.message);
119
+ }
120
+ function buildCodexUpstreamPromptMessage(params, identity, upstreamUserText) {
121
+ const message = attachCodexMirrorIdentity(buildCodexUserPromptMessage(params), identity);
122
+ return upstreamUserText ? attachUpstreamUserText(message, upstreamUserText) : message;
123
+ }
124
+ function promptSnapshot(params, turnId, upstreamUserText) {
125
+ return params.suppressNextUserMessagePersistence ? [] : [buildCodexUpstreamPromptMessage(params, `${turnId}:prompt`, upstreamUserText)];
126
+ }
127
+ async function buildResolvedCodexUserPromptMessage(params) {
128
+ return buildFromPrepared(params, await params.userTurnTranscriptRecorder?.resolveMessage() ?? params.userTurnTranscriptRecorder?.message);
129
+ }
130
+ //#endregion
131
+ //#region extensions/codex/src/app-server/transcript-mirror.ts
132
+ function isMirroredAgentMessage(message) {
133
+ return message.role === "user" || message.role === "assistant" || message.role === "toolResult";
134
+ }
135
+ const CODEX_HISTORY_IMPORT_MAX_MESSAGES = 200;
136
+ const CODEX_HISTORY_IMPORT_MAX_BYTES = 512 * 1024;
137
+ const CODEX_HISTORY_IMPORT_MAX_MESSAGE_BYTES = 64 * 1024;
138
+ const CODEX_HISTORY_TRUNCATION_SUFFIX = "\n\n[Message truncated during Codex history import.]";
139
+ const CODEX_HISTORY_ASSISTANT_API = "openai-chatgpt-responses";
140
+ const CODEX_HISTORY_ASSISTANT_PROVIDER = "openai";
141
+ const CODEX_HISTORY_ASSISTANT_MODEL = "native-history";
142
+ const CODEX_HISTORY_ZERO_USAGE = {
143
+ input: 0,
144
+ output: 0,
145
+ cacheRead: 0,
146
+ cacheWrite: 0,
147
+ totalTokens: 0,
148
+ cost: {
149
+ input: 0,
150
+ output: 0,
151
+ cacheRead: 0,
152
+ cacheWrite: 0,
153
+ total: 0
154
+ }
155
+ };
156
+ function isUtf8ContinuationByte(byte) {
157
+ return byte !== void 0 && (byte & 192) === 128;
158
+ }
159
+ function truncateUtf8Prefix(value, maxBytes) {
160
+ const bytes = Buffer.from(value);
161
+ if (bytes.byteLength <= maxBytes) return value;
162
+ let end = Math.max(0, maxBytes);
163
+ while (end > 0 && isUtf8ContinuationByte(bytes[end])) end -= 1;
164
+ return bytes.subarray(0, end).toString("utf8");
165
+ }
166
+ function normalizeImportedHistoryText(value) {
167
+ if (typeof value !== "string") return;
168
+ const text = value.trim();
169
+ if (!text) return;
170
+ if (Buffer.byteLength(text, "utf8") <= CODEX_HISTORY_IMPORT_MAX_MESSAGE_BYTES) return text;
171
+ const suffixBytes = Buffer.byteLength(CODEX_HISTORY_TRUNCATION_SUFFIX, "utf8");
172
+ return `${truncateUtf8Prefix(text, Math.max(0, CODEX_HISTORY_IMPORT_MAX_MESSAGE_BYTES - suffixBytes))}${CODEX_HISTORY_TRUNCATION_SUFFIX}`;
173
+ }
174
+ function projectCodexUserItemText(item) {
175
+ if (!Array.isArray(item.content)) return;
176
+ const parts = [];
177
+ for (const value of item.content) {
178
+ if (!value || typeof value !== "object" || Array.isArray(value)) continue;
179
+ const input = value;
180
+ if (input.type === "text") {
181
+ const text = normalizeImportedHistoryText(input.text);
182
+ if (text) parts.push(text);
183
+ continue;
184
+ }
185
+ if (input.type === "image" || input.type === "localImage") {
186
+ parts.push("[Image attachment]");
187
+ continue;
188
+ }
189
+ if (input.type === "skill" || input.type === "mention") {
190
+ const name = normalizeOptionalString(input.name);
191
+ if (name) parts.push(`${input.type === "skill" ? "$" : "@"}${name}`);
192
+ }
193
+ }
194
+ return normalizeImportedHistoryText(parts.join("\n"));
195
+ }
196
+ function selectTurnsThroughBoundary(thread, throughTurnId) {
197
+ if (throughTurnId === null) return [];
198
+ const turns = thread.turns ?? [];
199
+ const boundaryIndex = turns.findIndex((turn) => turn.id === throughTurnId);
200
+ if (boundaryIndex < 0) throw new Error(`Codex history boundary turn not found: ${throughTurnId}`);
201
+ const boundary = turns[boundaryIndex];
202
+ if (boundary?.status !== "completed" && boundary?.status !== "interrupted" && boundary?.status !== "failed") throw new Error(`Codex history boundary turn is not terminal: ${throughTurnId}`);
203
+ return turns.slice(0, boundaryIndex + 1);
204
+ }
205
+ function projectCodexThreadHistory(params) {
206
+ const projected = [];
207
+ const threadTimestamp = typeof params.thread.createdAt === "number" && Number.isFinite(params.thread.createdAt) ? params.thread.createdAt * 1e3 : params.importedAt;
208
+ let itemOffset = 0;
209
+ for (const turn of selectTurnsThroughBoundary(params.thread, params.throughTurnId)) for (const value of turn.items) {
210
+ const item = value;
211
+ const itemId = normalizeOptionalString(item.id);
212
+ const identity = `${turn.id}:${itemId ?? itemOffset}`;
213
+ const timestampSeconds = item.type === "agentMessage" ? turn.completedAt ?? turn.startedAt : turn.startedAt ?? turn.completedAt;
214
+ const timestamp = typeof timestampSeconds === "number" && Number.isFinite(timestampSeconds) ? timestampSeconds * 1e3 + itemOffset : threadTimestamp + itemOffset;
215
+ const text = item.type === "userMessage" ? projectCodexUserItemText(item) : item.type === "agentMessage" ? normalizeImportedHistoryText(item.text) : void 0;
216
+ const role = item.type === "userMessage" ? "user" : item.type === "agentMessage" ? "assistant" : void 0;
217
+ itemOffset += 1;
218
+ if (!text || !role) continue;
219
+ const message = role === "assistant" ? attachCodexMirrorIdentity({
220
+ role,
221
+ content: [{
222
+ type: "text",
223
+ text
224
+ }],
225
+ api: CODEX_HISTORY_ASSISTANT_API,
226
+ provider: normalizeOptionalString(params.modelProvider) ?? normalizeOptionalString(params.thread.modelProvider) ?? CODEX_HISTORY_ASSISTANT_PROVIDER,
227
+ model: CODEX_HISTORY_ASSISTANT_MODEL,
228
+ usage: CODEX_HISTORY_ZERO_USAGE,
229
+ stopReason: "stop",
230
+ timestamp
231
+ }, identity) : attachCodexMirrorIdentity({
232
+ role,
233
+ content: text,
234
+ timestamp
235
+ }, identity);
236
+ const phase = item.phase === "commentary" || item.phase === "final_answer" ? item.phase : void 0;
237
+ projected.push({
238
+ message,
239
+ responseItem: {
240
+ type: "message",
241
+ role,
242
+ content: [{
243
+ type: role === "assistant" ? "output_text" : "input_text",
244
+ text
245
+ }],
246
+ ...role === "assistant" && phase ? { phase } : {}
247
+ },
248
+ textBytes: Buffer.byteLength(text, "utf8")
249
+ });
250
+ }
251
+ return projected;
252
+ }
253
+ function selectBoundedCodexHistoryTail(projected) {
254
+ const selected = [];
255
+ let selectedBytes = 0;
256
+ for (let index = projected.length - 1; index >= 0; index -= 1) {
257
+ const candidate = projected[index];
258
+ if (!candidate) continue;
259
+ if (selected.length >= CODEX_HISTORY_IMPORT_MAX_MESSAGES || selectedBytes + candidate.textBytes > CODEX_HISTORY_IMPORT_MAX_BYTES) break;
260
+ selected.push(candidate);
261
+ selectedBytes += candidate.textBytes;
262
+ }
263
+ return selected.toReversed();
264
+ }
265
+ /** Projects one terminal Codex history prefix into transcript and Responses API items. */
266
+ function projectBoundedCodexThreadHistory(params) {
267
+ const projected = projectCodexThreadHistory({
268
+ thread: params.thread,
269
+ throughTurnId: params.throughTurnId,
270
+ importedAt: params.importedAt,
271
+ ...params.modelProvider ? { modelProvider: params.modelProvider } : {}
272
+ });
273
+ const selected = selectBoundedCodexHistoryTail(projected);
274
+ return {
275
+ importedMessages: selected.length,
276
+ omittedMessages: projected.length - selected.length,
277
+ responseItems: selected.map(({ responseItem }) => responseItem),
278
+ transcriptMessages: selected.map(({ message }) => message)
279
+ };
280
+ }
281
+ /** Imports a bounded, user-visible Codex history tail into a new OpenClaw transcript. */
282
+ async function importCodexThreadHistoryToTranscript(params) {
283
+ const projection = projectBoundedCodexThreadHistory({
284
+ thread: params.thread,
285
+ throughTurnId: params.throughTurnId,
286
+ importedAt: Date.now(),
287
+ ...params.modelProvider ? { modelProvider: params.modelProvider } : {}
288
+ });
289
+ if (projection.transcriptMessages.length > 0) await mirror({
290
+ storePath: params.storePath,
291
+ sessionId: params.sessionId,
292
+ sessionKey: params.sessionKey,
293
+ ...params.agentId ? { agentId: params.agentId } : {},
294
+ ...params.cwd ? { cwd: params.cwd } : {},
295
+ ...params.config ? { config: params.config } : {},
296
+ messages: projection.transcriptMessages,
297
+ idempotencyScope: `codex-app-server:${params.thread.id}:history`
298
+ });
299
+ return {
300
+ importedMessages: projection.importedMessages,
301
+ omittedMessages: projection.omittedMessages
302
+ };
303
+ }
304
+ async function mirrorBestEffort(params) {
305
+ try {
306
+ const messages = await resolveFinalCodexMirrorMessages({
307
+ params: params.params,
308
+ messagesSnapshot: params.result.messagesSnapshot,
309
+ turnId: params.turnId
310
+ });
311
+ const mirrorResult = await mirror({
312
+ agentId: params.agentId,
313
+ sessionKey: params.sessionKey,
314
+ sessionId: params.params.sessionId,
315
+ storePath: params.params.sessionTarget?.storePath,
316
+ cwd: params.cwd,
317
+ messages,
318
+ idempotencyScope: `codex-app-server:${params.threadId}`,
319
+ config: params.params.config
320
+ });
321
+ for (const message of mirrorResult.userMessagesPresent) try {
322
+ params.notifyUserMessagePersisted(message);
323
+ } catch (error) {
324
+ embeddedAgentLog.warn("failed to notify codex app-server user-message persistence", { error: formatErrorMessage(error) });
325
+ }
326
+ const expectedFingerprints = new Map(messages.flatMap((message) => {
327
+ if (!isMirroredAgentMessage(message)) return [];
328
+ const identity = readMirrorIdentity(message);
329
+ return identity ? [[identity, fingerprintCodexMirrorSourceMessage(message)]] : [];
330
+ }));
331
+ const mirroredMessages = mirrorResult.messagesPresent.filter((message) => {
332
+ const identity = readMirrorIdentity(message);
333
+ return identity !== void 0 && readCodexMirrorSourceFingerprint(message) === expectedFingerprints.get(identity);
334
+ });
335
+ const assistantMirrorIdentity = `${params.turnId}:assistant`;
336
+ const assistantTranscriptOwned = mirrorResult.assistantMirrorIdentitiesOwned.includes(assistantMirrorIdentity);
337
+ const assistantTranscriptIdempotencyKey = normalizeOptionalString((assistantTranscriptOwned ? mirroredMessages.find((message) => readMirrorIdentity(message) === assistantMirrorIdentity) : void 0)?.idempotencyKey);
338
+ return {
339
+ assistantTranscriptOwned,
340
+ ...assistantTranscriptIdempotencyKey ? { assistantTranscriptIdempotencyKey } : {},
341
+ mirroredMessages
342
+ };
343
+ } catch (error) {
344
+ embeddedAgentLog.warn("failed to mirror codex app-server transcript", { error });
345
+ return {
346
+ assistantTranscriptOwned: false,
347
+ mirroredMessages: []
348
+ };
349
+ }
350
+ }
351
+ async function resolveFinalCodexMirrorMessages(params) {
352
+ if (params.params.suppressNextUserMessagePersistence || !params.params.userTurnTranscriptRecorder) return params.messagesSnapshot;
353
+ const promptSnapshot = params.messagesSnapshot.find((message) => message.role === "user");
354
+ const resolvedBase = attachCodexMirrorIdentity(await buildResolvedCodexUserPromptMessage(params.params), `${params.turnId}:prompt`);
355
+ const upstreamUserText = readUpstreamUserText(promptSnapshot);
356
+ const resolvedPrompt = upstreamUserText ? attachUpstreamUserText(resolvedBase, upstreamUserText) : resolvedBase;
357
+ const firstUserIndex = params.messagesSnapshot.findIndex((message) => message.role === "user");
358
+ if (firstUserIndex === -1) return [resolvedPrompt, ...params.messagesSnapshot];
359
+ const messages = params.messagesSnapshot.slice();
360
+ messages[firstUserIndex] = resolvedPrompt;
361
+ return messages;
362
+ }
363
+ function createCodexAppServerUserMessagePersistenceNotifier(runParams) {
364
+ let notified = false;
365
+ return (message) => {
366
+ if (notified) return;
367
+ notified = true;
368
+ runParams.userTurnTranscriptRecorder?.markRuntimePersisted(message);
369
+ try {
370
+ runParams.onUserMessagePersisted?.(message);
371
+ } catch (error) {
372
+ embeddedAgentLog.warn("codex app-server user persistence notification failed", { error: formatErrorMessage(error) });
373
+ }
374
+ };
375
+ }
376
+ async function mirrorPromptAtTurnStartBestEffort(params) {
377
+ if (params.params.suppressNextUserMessagePersistence) return;
378
+ try {
379
+ const mirrorPromise = (async () => {
380
+ const userPromptMessage = projectAgentHarnessTranscriptMessageForDisplay({
381
+ hidden: params.params.trigger === "memory",
382
+ message: attachUpstreamUserText(attachCodexMirrorIdentity(await buildResolvedCodexUserPromptMessage(params.params), `${params.turnId}:prompt`), params.upstreamUserText)
383
+ });
384
+ const mirrorResult = await mirror({
385
+ agentId: params.agentId,
386
+ sessionKey: params.sessionKey,
387
+ sessionId: params.params.sessionId,
388
+ storePath: params.params.sessionTarget?.storePath,
389
+ cwd: params.cwd,
390
+ messages: [userPromptMessage],
391
+ idempotencyScope: `codex-app-server:${params.threadId}`,
392
+ config: params.params.config
393
+ });
394
+ for (const message of mirrorResult.userMessagesPresent) params.notifyUserMessagePersisted(message);
395
+ })();
396
+ params.params.userTurnTranscriptRecorder?.markRuntimePersistencePending(mirrorPromise);
397
+ await mirrorPromise;
398
+ } catch (error) {
399
+ embeddedAgentLog.warn("failed to mirror codex app-server prompt at turn start", { error });
400
+ }
401
+ }
402
+ function fingerprintMirrorMessageContent(message) {
403
+ const payload = JSON.stringify({
404
+ role: message.role,
405
+ content: message.content
406
+ });
407
+ return createHash("sha256").update(payload).digest("hex").slice(0, 16);
408
+ }
409
+ function buildMirrorDedupeIdentity(message) {
410
+ const explicit = readMirrorIdentity(message);
411
+ if (explicit) return explicit;
412
+ return `${message.role}:${fingerprintMirrorMessageContent(message)}`;
413
+ }
414
+ async function mirror(params) {
415
+ const messages = params.messages.filter(isMirroredAgentMessage);
416
+ if (messages.length === 0) return {
417
+ assistantMirrorIdentitiesOwned: [],
418
+ messagesPresent: [],
419
+ userMessagesPresent: []
420
+ };
421
+ const transcriptTarget = resolveCodexMirrorTranscriptTarget(params);
422
+ const { appendedUpdates, assistantMirrorIdentitiesOwned, messagesPresent, userMessagesPresent } = await withSessionTranscriptWriteLock({
423
+ ...transcriptTarget,
424
+ config: params.config
425
+ }, async (transcript) => {
426
+ const nextAppendedUpdates = [];
427
+ const nextAssistantMirrorIdentitiesOwned = /* @__PURE__ */ new Set();
428
+ const nextMessagesPresent = [];
429
+ const nextUserMessagesPresent = [];
430
+ const mirrorState = readTranscriptMirrorState(await transcript.readEvents());
431
+ let nextMessageSeq = mirrorState.messageCount;
432
+ for (const message of messages) {
433
+ const dedupeIdentity = buildMirrorDedupeIdentity(message);
434
+ const sourceFingerprint = fingerprintCodexMirrorSourceMessage(message);
435
+ const idempotencyKey = (message.role === "user" ? normalizeOptionalString(message.idempotencyKey) : void 0) ?? (params.idempotencyScope ? `${params.idempotencyScope}:${dedupeIdentity}` : void 0);
436
+ const transcriptMessage = {
437
+ ...attachCodexMirrorAttestation(message, sourceFingerprint),
438
+ ...idempotencyKey ? { idempotencyKey } : {}
439
+ };
440
+ if (idempotencyKey && mirrorState.idempotencyKeys.has(idempotencyKey)) {
441
+ const persistedMessage = mirrorState.messagesByIdempotencyKey.get(idempotencyKey);
442
+ if (persistedMessage) nextMessagesPresent.push(persistedMessage);
443
+ const persistedUserMessage = persistedMessage?.role === "user" ? persistedMessage : void 0;
444
+ if (persistedUserMessage) nextUserMessagesPresent.push(persistedUserMessage);
445
+ if (message.role === "assistant") nextAssistantMirrorIdentitiesOwned.add(dedupeIdentity);
446
+ continue;
447
+ }
448
+ const nextMessage = params.skipBeforeMessageWriteHooks ? transcriptMessage : runAgentHarnessBeforeMessageWriteHook({
449
+ message: transcriptMessage,
450
+ agentId: params.agentId,
451
+ sessionKey: params.sessionKey
452
+ });
453
+ if (!nextMessage) {
454
+ if (message.role === "assistant") nextAssistantMirrorIdentitiesOwned.add(dedupeIdentity);
455
+ continue;
456
+ }
457
+ let messageToAppend = idempotencyKey ? {
458
+ ...attachCodexMirrorAttestation(nextMessage, sourceFingerprint),
459
+ idempotencyKey
460
+ } : attachCodexMirrorAttestation(nextMessage, sourceFingerprint);
461
+ const mirrorIdentity = readMirrorIdentity(message);
462
+ if (mirrorIdentity) messageToAppend = attachCodexMirrorIdentity(messageToAppend, mirrorIdentity);
463
+ messageToAppend = projectAgentHarnessTranscriptMessageForDisplay({
464
+ hidden: message.display === false,
465
+ message: messageToAppend
466
+ });
467
+ const appended = await transcript.appendMessage({
468
+ message: messageToAppend,
469
+ idempotencyLookup: idempotencyKey ? "caller-checked" : "scan",
470
+ cwd: params.cwd
471
+ });
472
+ if (!appended) continue;
473
+ const { messageId, message: appendedMessage } = appended;
474
+ if (isMirroredAgentMessage(appendedMessage)) {
475
+ nextMessagesPresent.push(appendedMessage);
476
+ if (idempotencyKey) mirrorState.messagesByIdempotencyKey.set(idempotencyKey, appendedMessage);
477
+ }
478
+ if (message.role === "assistant") nextAssistantMirrorIdentitiesOwned.add(dedupeIdentity);
479
+ if (appendedMessage.role === "user") nextUserMessagesPresent.push(appendedMessage);
480
+ nextMessageSeq += 1;
481
+ nextAppendedUpdates.push({
482
+ messageId,
483
+ message: appendedMessage,
484
+ messageSeq: nextMessageSeq
485
+ });
486
+ if (idempotencyKey) mirrorState.idempotencyKeys.add(idempotencyKey);
487
+ }
488
+ return {
489
+ appendedUpdates: nextAppendedUpdates,
490
+ assistantMirrorIdentitiesOwned: [...nextAssistantMirrorIdentitiesOwned],
491
+ messagesPresent: nextMessagesPresent,
492
+ userMessagesPresent: nextUserMessagesPresent
493
+ };
494
+ });
495
+ for (const update of appendedUpdates) try {
496
+ await publishSessionTranscriptUpdateByIdentity({
497
+ ...transcriptTarget,
498
+ update: {
499
+ ...params.agentId ? { agentId: params.agentId } : {},
500
+ message: update.message,
501
+ messageId: update.messageId,
502
+ messageSeq: update.messageSeq,
503
+ sessionKey: transcriptTarget.sessionKey
504
+ }
505
+ });
506
+ } catch (error) {
507
+ embeddedAgentLog.warn("failed to publish codex app-server transcript update", { error: formatErrorMessage(error) });
508
+ }
509
+ return {
510
+ assistantMirrorIdentitiesOwned,
511
+ messagesPresent,
512
+ userMessagesPresent
513
+ };
514
+ }
515
+ const codexTranscriptMirrorRuntime = {
516
+ mirror,
517
+ mirrorBestEffort
518
+ };
519
+ function resolveCodexMirrorTranscriptTarget(params) {
520
+ const sessionKey = params.sessionKey?.trim();
521
+ const storePath = params.storePath?.trim();
522
+ if (!sessionKey || !storePath) throw new Error("Codex transcript mirror requires a runtime session identity");
523
+ return {
524
+ ...params.agentId ? { agentId: params.agentId } : {},
525
+ sessionId: params.sessionId,
526
+ sessionKey,
527
+ storePath
528
+ };
529
+ }
530
+ function readTranscriptMirrorState(events) {
531
+ const idempotencyKeys = /* @__PURE__ */ new Set();
532
+ const messagesByIdempotencyKey = /* @__PURE__ */ new Map();
533
+ let messageCount = 0;
534
+ for (const event of events) {
535
+ if (!event || typeof event !== "object" || Array.isArray(event)) continue;
536
+ const parsed = event;
537
+ if (parsed.type === "message") messageCount += 1;
538
+ if (typeof parsed.message?.idempotencyKey === "string") {
539
+ idempotencyKeys.add(parsed.message.idempotencyKey);
540
+ if (isMirroredAgentMessage(parsed.message)) messagesByIdempotencyKey.set(parsed.message.idempotencyKey, parsed.message);
541
+ }
542
+ }
543
+ return {
544
+ idempotencyKeys,
545
+ messagesByIdempotencyKey,
546
+ messageCount
547
+ };
548
+ }
549
+ //#endregion
550
+ export { projectBoundedCodexThreadHistory as a, fingerprintCodexMirrorSourceMessage as c, attachCodexMirrorIdentity as d, readMirrorIdentity as f, mirrorPromptAtTurnStartBestEffort as i, readCodexMirrorSourceFingerprint as l, createCodexAppServerUserMessagePersistenceNotifier as n, buildCodexUserPromptMessage as o, readUpstreamUserText as p, importCodexThreadHistoryToTranscript as r, promptSnapshot as s, codexTranscriptMirrorRuntime as t, serializeCodexMirrorSourceEvidence as u };