@openclaw/codex 2026.7.2-beta.1 → 2026.7.2-beta.2

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 (41) hide show
  1. package/README.md +1 -1
  2. package/dist/{app-server-policy-DVcxdse_.js → app-server-policy-Scc-Wevo.js} +1 -1
  3. package/dist/{attempt-notifications-DEv9h7iC.js → attempt-notifications-BFmNhqFl.js} +3 -6
  4. package/dist/cli-metadata.js +1 -1
  5. package/dist/{command-formatters-D6ZlGNmb.js → command-formatters-Dq9InZUK.js} +34 -3
  6. package/dist/{command-handlers-Cpl9fUWv.js → command-handlers-IgqmL_kv.js} +10 -13
  7. package/dist/{compact-FnJmiPNA.js → compact-DCTmg3id.js} +4 -5
  8. package/dist/{computer-use-DVzr8OP1.js → computer-use-CPcU8TjG.js} +4 -4
  9. package/dist/{conversation-control-DtQ-E7mr.js → conversation-control-CGkBlfc5.js} +5 -7
  10. package/dist/doctor-contract-api.js +1 -1
  11. package/dist/{dynamic-tools-BMLoaTeG.js → dynamic-tools-C_1tEs34.js} +608 -330
  12. package/dist/harness.js +9 -5
  13. package/dist/index.js +52 -31
  14. package/dist/{media-understanding-provider-D580L0P8.js → media-understanding-provider-D31dOJwb.js} +11 -12
  15. package/dist/media-understanding-provider.js +1 -1
  16. package/dist/{models-DuKzZA6G.js → models-uh26C8QU.js} +5 -9
  17. package/dist/{notification-correlation-DfaCm0mx.js → notification-correlation-KmfV4EkP.js} +3 -3
  18. package/dist/{plugin-app-cache-key-BKNjHMEs.js → plugin-app-cache-key-Ceb-lm2c.js} +2 -2
  19. package/dist/{rate-limits-Dhp04Rqo.js → rate-limits-DyXaYAxU.js} +7 -6
  20. package/dist/{request-DborTWgw.js → request-B_oQsCXy.js} +54 -8
  21. package/dist/{run-attempt-VPVJoYDP.js → run-attempt-MLzoMe_m.js} +499 -295
  22. package/dist/{config-c48K5HP9.js → session-binding-h1mmCGnl.js} +786 -3
  23. package/dist/{session-catalog-7H112Tr_.js → session-catalog-CEvoXWHA.js} +45 -29
  24. package/dist/{session-cli-B28RhCyp.js → session-cli-XsEuWb_C.js} +1 -1
  25. package/dist/{shared-client-D4mFI9al.js → shared-client-JiAnW6pc.js} +255 -81
  26. package/dist/{side-question-CgJBz52s.js → side-question-DqDvIwSU.js} +15 -13
  27. package/dist/{thread-lifecycle-BgLXzjvV.js → thread-lifecycle-CN_pPtPh.js} +1787 -1579
  28. package/dist/{protocol-validators-dZQ-UTOa.js → transcript-mirror-D9rTxx2P.js} +485 -2
  29. package/dist/usage-D5Rohxoc.js +25 -0
  30. package/dist/{web-search-provider.runtime-Bs-eTn5U.js → web-search-provider.runtime-CKVBn3fP.js} +3 -3
  31. package/npm-shrinkwrap.json +30 -30
  32. package/openclaw.plugin.json +10 -5
  33. package/package.json +6 -6
  34. package/dist/capabilities-42Dfn2TV.js +0 -33
  35. package/dist/prompt-overlay.js +0 -15
  36. package/dist/protocol-BMifTfdW.js +0 -15
  37. package/dist/provider-catalog.js +0 -118
  38. package/dist/provider-discovery.js +0 -34
  39. package/dist/provider.js +0 -307
  40. package/dist/session-binding-BMfX1OX-.js +0 -786
  41. package/dist/transcript-mirror-DhLwFIL4.js +0 -485
@@ -1,485 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
3
- import { embeddedAgentLog, formatErrorMessage, runAgentHarnessBeforeMessageWriteHook } from "openclaw/plugin-sdk/agent-harness-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/user-prompt-message.ts
47
- function buildSenderLabel(params) {
48
- const label = params.senderName ?? params.senderUsername ?? params.senderE164 ?? params.senderId;
49
- if (!label) return;
50
- return !params.senderId || label.includes(params.senderId) ? label : `${label} (${params.senderId})`;
51
- }
52
- function buildFromPrepared(params, preparedUserMessage) {
53
- const senderId = normalizeOptionalString(params.senderId);
54
- const senderName = normalizeOptionalString(params.senderName);
55
- const senderUsername = normalizeOptionalString(params.senderUsername);
56
- const senderE164 = normalizeOptionalString(params.senderE164);
57
- const senderLabel = buildSenderLabel({
58
- senderId,
59
- senderName,
60
- senderUsername,
61
- senderE164
62
- });
63
- const sourceChannel = normalizeOptionalString(params.inputProvenance?.sourceChannel ?? params.messageChannel ?? params.messageProvider);
64
- return {
65
- role: "user",
66
- timestamp: Date.now(),
67
- ...params.inputProvenance ? { provenance: params.inputProvenance } : {},
68
- ...sourceChannel ? { sourceChannel } : {},
69
- ...senderId ? { senderId } : {},
70
- ...senderName ? { senderName } : {},
71
- ...senderUsername ? { senderUsername } : {},
72
- ...senderE164 ? { senderE164 } : {},
73
- ...senderLabel ? { senderLabel } : {},
74
- ...preparedUserMessage ? preparedUserMessage : { content: params.prompt }
75
- };
76
- }
77
- function buildCodexUserPromptMessage(params) {
78
- return buildFromPrepared(params, params.userTurnTranscriptRecorder?.message);
79
- }
80
- function buildCodexUpstreamPromptMessage(params, identity, upstreamUserText) {
81
- const message = attachCodexMirrorIdentity(buildCodexUserPromptMessage(params), identity);
82
- return upstreamUserText ? attachUpstreamUserText(message, upstreamUserText) : message;
83
- }
84
- function promptSnapshot(params, turnId, upstreamUserText) {
85
- return params.suppressNextUserMessagePersistence ? [] : [buildCodexUpstreamPromptMessage(params, `${turnId}:prompt`, upstreamUserText)];
86
- }
87
- async function buildResolvedCodexUserPromptMessage(params) {
88
- return buildFromPrepared(params, await params.userTurnTranscriptRecorder?.resolveMessage() ?? params.userTurnTranscriptRecorder?.message);
89
- }
90
- //#endregion
91
- //#region extensions/codex/src/app-server/transcript-mirror.ts
92
- const MIRROR_ORIGIN_META_KEY = "mirrorOrigin";
93
- const CODEX_APP_SERVER_MIRROR_ORIGIN = "codex-app-server";
94
- const CODEX_HISTORY_IMPORT_MAX_MESSAGES = 200;
95
- const CODEX_HISTORY_IMPORT_MAX_BYTES = 512 * 1024;
96
- const CODEX_HISTORY_IMPORT_MAX_MESSAGE_BYTES = 64 * 1024;
97
- const CODEX_HISTORY_TRUNCATION_SUFFIX = "\n\n[Message truncated during Codex history import.]";
98
- const CODEX_HISTORY_ASSISTANT_API = "openai-chatgpt-responses";
99
- const CODEX_HISTORY_ASSISTANT_PROVIDER = "openai";
100
- const CODEX_HISTORY_ASSISTANT_MODEL = "native-history";
101
- const CODEX_HISTORY_ZERO_USAGE = {
102
- input: 0,
103
- output: 0,
104
- cacheRead: 0,
105
- cacheWrite: 0,
106
- totalTokens: 0,
107
- cost: {
108
- input: 0,
109
- output: 0,
110
- cacheRead: 0,
111
- cacheWrite: 0,
112
- total: 0
113
- }
114
- };
115
- function isUtf8ContinuationByte(byte) {
116
- return byte !== void 0 && (byte & 192) === 128;
117
- }
118
- function truncateUtf8Prefix(value, maxBytes) {
119
- const bytes = Buffer.from(value);
120
- if (bytes.byteLength <= maxBytes) return value;
121
- let end = Math.max(0, maxBytes);
122
- while (end > 0 && isUtf8ContinuationByte(bytes[end])) end -= 1;
123
- return bytes.subarray(0, end).toString("utf8");
124
- }
125
- function normalizeImportedHistoryText(value) {
126
- if (typeof value !== "string") return;
127
- const text = value.trim();
128
- if (!text) return;
129
- if (Buffer.byteLength(text, "utf8") <= CODEX_HISTORY_IMPORT_MAX_MESSAGE_BYTES) return text;
130
- const suffixBytes = Buffer.byteLength(CODEX_HISTORY_TRUNCATION_SUFFIX, "utf8");
131
- return `${truncateUtf8Prefix(text, Math.max(0, CODEX_HISTORY_IMPORT_MAX_MESSAGE_BYTES - suffixBytes))}${CODEX_HISTORY_TRUNCATION_SUFFIX}`;
132
- }
133
- function projectCodexUserItemText(item) {
134
- if (!Array.isArray(item.content)) return;
135
- const parts = [];
136
- for (const value of item.content) {
137
- if (!value || typeof value !== "object" || Array.isArray(value)) continue;
138
- const input = value;
139
- if (input.type === "text") {
140
- const text = normalizeImportedHistoryText(input.text);
141
- if (text) parts.push(text);
142
- continue;
143
- }
144
- if (input.type === "image" || input.type === "localImage") {
145
- parts.push("[Image attachment]");
146
- continue;
147
- }
148
- if (input.type === "skill" || input.type === "mention") {
149
- const name = normalizeOptionalString(input.name);
150
- if (name) parts.push(`${input.type === "skill" ? "$" : "@"}${name}`);
151
- }
152
- }
153
- return normalizeImportedHistoryText(parts.join("\n"));
154
- }
155
- function selectTurnsThroughBoundary(thread, throughTurnId) {
156
- if (throughTurnId === null) return [];
157
- const turns = thread.turns ?? [];
158
- const boundaryIndex = turns.findIndex((turn) => turn.id === throughTurnId);
159
- if (boundaryIndex < 0) throw new Error(`Codex history boundary turn not found: ${throughTurnId}`);
160
- const boundary = turns[boundaryIndex];
161
- if (boundary?.status !== "completed" && boundary?.status !== "interrupted" && boundary?.status !== "failed") throw new Error(`Codex history boundary turn is not terminal: ${throughTurnId}`);
162
- return turns.slice(0, boundaryIndex + 1);
163
- }
164
- function projectCodexThreadHistory(params) {
165
- const projected = [];
166
- const threadTimestamp = typeof params.thread.createdAt === "number" && Number.isFinite(params.thread.createdAt) ? params.thread.createdAt * 1e3 : params.importedAt;
167
- let itemOffset = 0;
168
- for (const turn of selectTurnsThroughBoundary(params.thread, params.throughTurnId)) for (const value of turn.items) {
169
- const item = value;
170
- const itemId = normalizeOptionalString(item.id);
171
- const identity = `${turn.id}:${itemId ?? itemOffset}`;
172
- const timestampSeconds = item.type === "agentMessage" ? turn.completedAt ?? turn.startedAt : turn.startedAt ?? turn.completedAt;
173
- const timestamp = typeof timestampSeconds === "number" && Number.isFinite(timestampSeconds) ? timestampSeconds * 1e3 + itemOffset : threadTimestamp + itemOffset;
174
- const text = item.type === "userMessage" ? projectCodexUserItemText(item) : item.type === "agentMessage" ? normalizeImportedHistoryText(item.text) : void 0;
175
- const role = item.type === "userMessage" ? "user" : item.type === "agentMessage" ? "assistant" : void 0;
176
- itemOffset += 1;
177
- if (!text || !role) continue;
178
- const message = role === "assistant" ? attachCodexMirrorIdentity({
179
- role,
180
- content: [{
181
- type: "text",
182
- text
183
- }],
184
- api: CODEX_HISTORY_ASSISTANT_API,
185
- provider: normalizeOptionalString(params.modelProvider) ?? normalizeOptionalString(params.thread.modelProvider) ?? CODEX_HISTORY_ASSISTANT_PROVIDER,
186
- model: CODEX_HISTORY_ASSISTANT_MODEL,
187
- usage: CODEX_HISTORY_ZERO_USAGE,
188
- stopReason: "stop",
189
- timestamp
190
- }, identity) : attachCodexMirrorIdentity({
191
- role,
192
- content: text,
193
- timestamp
194
- }, identity);
195
- const phase = item.phase === "commentary" || item.phase === "final_answer" ? item.phase : void 0;
196
- projected.push({
197
- message,
198
- responseItem: {
199
- type: "message",
200
- role,
201
- content: [{
202
- type: role === "assistant" ? "output_text" : "input_text",
203
- text
204
- }],
205
- ...role === "assistant" && phase ? { phase } : {}
206
- },
207
- textBytes: Buffer.byteLength(text, "utf8")
208
- });
209
- }
210
- return projected;
211
- }
212
- function selectBoundedCodexHistoryTail(projected) {
213
- const selected = [];
214
- let selectedBytes = 0;
215
- for (let index = projected.length - 1; index >= 0; index -= 1) {
216
- const candidate = projected[index];
217
- if (!candidate) continue;
218
- if (selected.length >= CODEX_HISTORY_IMPORT_MAX_MESSAGES || selectedBytes + candidate.textBytes > CODEX_HISTORY_IMPORT_MAX_BYTES) break;
219
- selected.push(candidate);
220
- selectedBytes += candidate.textBytes;
221
- }
222
- return selected.toReversed();
223
- }
224
- /** Projects one terminal Codex history prefix into transcript and Responses API items. */
225
- function projectBoundedCodexThreadHistory(params) {
226
- const projected = projectCodexThreadHistory({
227
- thread: params.thread,
228
- throughTurnId: params.throughTurnId,
229
- importedAt: params.importedAt,
230
- ...params.modelProvider ? { modelProvider: params.modelProvider } : {}
231
- });
232
- const selected = selectBoundedCodexHistoryTail(projected);
233
- return {
234
- importedMessages: selected.length,
235
- omittedMessages: projected.length - selected.length,
236
- responseItems: selected.map(({ responseItem }) => responseItem),
237
- transcriptMessages: selected.map(({ message }) => message)
238
- };
239
- }
240
- /** Imports a bounded, user-visible Codex history tail into a new OpenClaw transcript. */
241
- async function importCodexThreadHistoryToTranscript(params) {
242
- const projection = projectBoundedCodexThreadHistory({
243
- thread: params.thread,
244
- throughTurnId: params.throughTurnId,
245
- importedAt: Date.now(),
246
- ...params.modelProvider ? { modelProvider: params.modelProvider } : {}
247
- });
248
- if (projection.transcriptMessages.length > 0) await mirror({
249
- storePath: params.storePath,
250
- sessionId: params.sessionId,
251
- sessionKey: params.sessionKey,
252
- ...params.agentId ? { agentId: params.agentId } : {},
253
- ...params.cwd ? { cwd: params.cwd } : {},
254
- ...params.config ? { config: params.config } : {},
255
- messages: projection.transcriptMessages,
256
- idempotencyScope: `codex-app-server:${params.thread.id}:history`
257
- });
258
- return {
259
- importedMessages: projection.importedMessages,
260
- omittedMessages: projection.omittedMessages
261
- };
262
- }
263
- function attachCodexMirrorOrigin(message) {
264
- const record = message;
265
- const existing = record["__openclaw"];
266
- const baseMeta = existing && typeof existing === "object" && !Array.isArray(existing) ? existing : {};
267
- return {
268
- ...record,
269
- __openclaw: {
270
- ...baseMeta,
271
- [MIRROR_ORIGIN_META_KEY]: CODEX_APP_SERVER_MIRROR_ORIGIN
272
- }
273
- };
274
- }
275
- async function mirrorBestEffort(params) {
276
- try {
277
- const messages = await resolveFinalCodexMirrorMessages({
278
- params: params.params,
279
- messagesSnapshot: params.result.messagesSnapshot,
280
- turnId: params.turnId
281
- });
282
- const mirrorResult = await mirror({
283
- agentId: params.agentId,
284
- sessionKey: params.sessionKey,
285
- sessionId: params.params.sessionId,
286
- storePath: params.params.sessionTarget?.storePath,
287
- cwd: params.cwd,
288
- messages,
289
- idempotencyScope: `codex-app-server:${params.threadId}`,
290
- config: params.params.config
291
- });
292
- for (const message of mirrorResult.userMessagesPresent) try {
293
- params.notifyUserMessagePersisted(message);
294
- } catch (error) {
295
- embeddedAgentLog.warn("failed to notify codex app-server user-message persistence", { error: formatErrorMessage(error) });
296
- }
297
- return mirrorResult.assistantMirrorIdentitiesOwned.includes(`${params.turnId}:assistant`);
298
- } catch (error) {
299
- embeddedAgentLog.warn("failed to mirror codex app-server transcript", { error });
300
- return false;
301
- }
302
- }
303
- async function resolveFinalCodexMirrorMessages(params) {
304
- if (params.params.suppressNextUserMessagePersistence || !params.params.userTurnTranscriptRecorder) return params.messagesSnapshot;
305
- const promptSnapshot = params.messagesSnapshot.find((message) => message.role === "user");
306
- const resolvedBase = attachCodexMirrorIdentity(await buildResolvedCodexUserPromptMessage(params.params), `${params.turnId}:prompt`);
307
- const upstreamUserText = readUpstreamUserText(promptSnapshot);
308
- const resolvedPrompt = upstreamUserText ? attachUpstreamUserText(resolvedBase, upstreamUserText) : resolvedBase;
309
- const firstUserIndex = params.messagesSnapshot.findIndex((message) => message.role === "user");
310
- if (firstUserIndex === -1) return [resolvedPrompt, ...params.messagesSnapshot];
311
- const messages = params.messagesSnapshot.slice();
312
- messages[firstUserIndex] = resolvedPrompt;
313
- return messages;
314
- }
315
- function createCodexAppServerUserMessagePersistenceNotifier(runParams) {
316
- let notified = false;
317
- return (message) => {
318
- if (notified) return;
319
- notified = true;
320
- runParams.userTurnTranscriptRecorder?.markRuntimePersisted(message);
321
- try {
322
- runParams.onUserMessagePersisted?.(message);
323
- } catch (error) {
324
- embeddedAgentLog.warn("codex app-server user persistence notification failed", { error: formatErrorMessage(error) });
325
- }
326
- };
327
- }
328
- async function mirrorPromptAtTurnStartBestEffort(params) {
329
- if (params.params.suppressNextUserMessagePersistence) return;
330
- try {
331
- const mirrorPromise = (async () => {
332
- const userPromptMessage = attachUpstreamUserText(attachCodexMirrorIdentity(await buildResolvedCodexUserPromptMessage(params.params), `${params.turnId}:prompt`), params.upstreamUserText);
333
- const mirrorResult = await mirror({
334
- agentId: params.agentId,
335
- sessionKey: params.sessionKey,
336
- sessionId: params.params.sessionId,
337
- storePath: params.params.sessionTarget?.storePath,
338
- cwd: params.cwd,
339
- messages: [userPromptMessage],
340
- idempotencyScope: `codex-app-server:${params.threadId}`,
341
- config: params.params.config
342
- });
343
- for (const message of mirrorResult.userMessagesPresent) params.notifyUserMessagePersisted(message);
344
- })();
345
- params.params.userTurnTranscriptRecorder?.markRuntimePersistencePending(mirrorPromise);
346
- await mirrorPromise;
347
- } catch (error) {
348
- embeddedAgentLog.warn("failed to mirror codex app-server prompt at turn start", { error });
349
- }
350
- }
351
- function fingerprintMirrorMessageContent(message) {
352
- const payload = JSON.stringify({
353
- role: message.role,
354
- content: message.content
355
- });
356
- return createHash("sha256").update(payload).digest("hex").slice(0, 16);
357
- }
358
- function buildMirrorDedupeIdentity(message) {
359
- const explicit = readMirrorIdentity(message);
360
- if (explicit) return explicit;
361
- return `${message.role}:${fingerprintMirrorMessageContent(message)}`;
362
- }
363
- async function mirror(params) {
364
- const messages = params.messages.filter((message) => message.role === "user" || message.role === "assistant" || message.role === "toolResult");
365
- if (messages.length === 0) return {
366
- assistantMirrorIdentitiesOwned: [],
367
- userMessagesPresent: []
368
- };
369
- const transcriptTarget = resolveCodexMirrorTranscriptTarget(params);
370
- const { appendedUpdates, assistantMirrorIdentitiesOwned, userMessagesPresent } = await withSessionTranscriptWriteLock({
371
- ...transcriptTarget,
372
- config: params.config
373
- }, async (transcript) => {
374
- const nextAppendedUpdates = [];
375
- const nextAssistantMirrorIdentitiesOwned = /* @__PURE__ */ new Set();
376
- const nextUserMessagesPresent = [];
377
- const mirrorState = readTranscriptMirrorState(await transcript.readEvents());
378
- let nextMessageSeq = mirrorState.messageCount;
379
- for (const message of messages) {
380
- const dedupeIdentity = buildMirrorDedupeIdentity(message);
381
- const idempotencyKey = (message.role === "user" ? normalizeOptionalString(message.idempotencyKey) : void 0) ?? (params.idempotencyScope ? `${params.idempotencyScope}:${dedupeIdentity}` : void 0);
382
- const transcriptMessage = {
383
- ...attachCodexMirrorOrigin(message),
384
- ...idempotencyKey ? { idempotencyKey } : {}
385
- };
386
- if (idempotencyKey && mirrorState.idempotencyKeys.has(idempotencyKey)) {
387
- const persistedUserMessage = mirrorState.userMessagesByIdempotencyKey.get(idempotencyKey);
388
- if (persistedUserMessage) nextUserMessagesPresent.push(persistedUserMessage);
389
- if (message.role === "assistant") nextAssistantMirrorIdentitiesOwned.add(dedupeIdentity);
390
- continue;
391
- }
392
- const nextMessage = runAgentHarnessBeforeMessageWriteHook({
393
- message: transcriptMessage,
394
- agentId: params.agentId,
395
- sessionKey: params.sessionKey
396
- });
397
- if (!nextMessage) {
398
- if (message.role === "assistant") nextAssistantMirrorIdentitiesOwned.add(dedupeIdentity);
399
- continue;
400
- }
401
- const messageToAppend = idempotencyKey ? {
402
- ...attachCodexMirrorOrigin(nextMessage),
403
- idempotencyKey
404
- } : attachCodexMirrorOrigin(nextMessage);
405
- const appended = await transcript.appendMessage({
406
- message: messageToAppend,
407
- idempotencyLookup: idempotencyKey ? "caller-checked" : "scan",
408
- cwd: params.cwd
409
- });
410
- if (!appended) continue;
411
- const { messageId, message: appendedMessage } = appended;
412
- if (message.role === "assistant") nextAssistantMirrorIdentitiesOwned.add(dedupeIdentity);
413
- if (appendedMessage.role === "user") {
414
- nextUserMessagesPresent.push(appendedMessage);
415
- if (idempotencyKey) mirrorState.userMessagesByIdempotencyKey.set(idempotencyKey, appendedMessage);
416
- }
417
- nextMessageSeq += 1;
418
- nextAppendedUpdates.push({
419
- messageId,
420
- message: appendedMessage,
421
- messageSeq: nextMessageSeq
422
- });
423
- if (idempotencyKey) mirrorState.idempotencyKeys.add(idempotencyKey);
424
- }
425
- return {
426
- appendedUpdates: nextAppendedUpdates,
427
- assistantMirrorIdentitiesOwned: [...nextAssistantMirrorIdentitiesOwned],
428
- userMessagesPresent: nextUserMessagesPresent
429
- };
430
- });
431
- for (const update of appendedUpdates) try {
432
- await publishSessionTranscriptUpdateByIdentity({
433
- ...transcriptTarget,
434
- update: {
435
- ...params.agentId ? { agentId: params.agentId } : {},
436
- message: update.message,
437
- messageId: update.messageId,
438
- messageSeq: update.messageSeq,
439
- sessionKey: transcriptTarget.sessionKey
440
- }
441
- });
442
- } catch (error) {
443
- embeddedAgentLog.warn("failed to publish codex app-server transcript update", { error: formatErrorMessage(error) });
444
- }
445
- return {
446
- assistantMirrorIdentitiesOwned,
447
- userMessagesPresent
448
- };
449
- }
450
- const codexTranscriptMirrorRuntime = {
451
- mirror,
452
- mirrorBestEffort
453
- };
454
- function resolveCodexMirrorTranscriptTarget(params) {
455
- const sessionKey = params.sessionKey?.trim();
456
- const storePath = params.storePath?.trim();
457
- if (!sessionKey || !storePath) throw new Error("Codex transcript mirror requires a runtime session identity");
458
- return {
459
- ...params.agentId ? { agentId: params.agentId } : {},
460
- sessionId: params.sessionId,
461
- sessionKey,
462
- storePath
463
- };
464
- }
465
- function readTranscriptMirrorState(events) {
466
- const idempotencyKeys = /* @__PURE__ */ new Set();
467
- const userMessagesByIdempotencyKey = /* @__PURE__ */ new Map();
468
- let messageCount = 0;
469
- for (const event of events) {
470
- if (!event || typeof event !== "object" || Array.isArray(event)) continue;
471
- const parsed = event;
472
- if (parsed.type === "message") messageCount += 1;
473
- if (typeof parsed.message?.idempotencyKey === "string") {
474
- idempotencyKeys.add(parsed.message.idempotencyKey);
475
- if (parsed.message.role === "user") userMessagesByIdempotencyKey.set(parsed.message.idempotencyKey, parsed.message);
476
- }
477
- }
478
- return {
479
- idempotencyKeys,
480
- messageCount,
481
- userMessagesByIdempotencyKey
482
- };
483
- }
484
- //#endregion
485
- export { projectBoundedCodexThreadHistory as a, attachCodexMirrorIdentity as c, mirrorPromptAtTurnStartBestEffort as i, createCodexAppServerUserMessagePersistenceNotifier as n, buildCodexUserPromptMessage as o, importCodexThreadHistoryToTranscript as r, promptSnapshot as s, codexTranscriptMirrorRuntime as t };