@openclaw/codex 2026.7.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 (48) hide show
  1. package/README.md +27 -3
  2. package/dist/app-server-policy-Scc-Wevo.js +49 -0
  3. package/dist/{attempt-notifications-BGsEIIDI.js → attempt-notifications-BFmNhqFl.js} +3 -6
  4. package/dist/auth-binding-C1czuHPA.js +62 -0
  5. package/dist/cli-metadata.js +20 -0
  6. package/dist/{app-server-policy-C968Kgin.js → command-formatters-Dq9InZUK.js} +39 -51
  7. package/dist/{command-handlers-Dv-pzAmg.js → command-handlers-IgqmL_kv.js} +161 -61
  8. package/dist/{compact-4mVBriKT.js → compact-DCTmg3id.js} +39 -10
  9. package/dist/computer-use-CPcU8TjG.js +685 -0
  10. package/dist/conversation-control-CGkBlfc5.js +286 -0
  11. package/dist/doctor-contract-api.js +120 -81
  12. package/dist/{provider-capabilities-CDnHbmUZ.js → dynamic-tools-C_1tEs34.js} +6109 -5725
  13. package/dist/harness.js +59 -15
  14. package/dist/index.js +1460 -269
  15. package/dist/{media-understanding-provider-BHOu9-Gg.js → media-understanding-provider-D31dOJwb.js} +32 -15
  16. package/dist/media-understanding-provider.js +1 -1
  17. package/dist/{models-DDmO1zwd.js → models-uh26C8QU.js} +5 -9
  18. package/dist/notification-correlation-KmfV4EkP.js +67 -0
  19. package/dist/plugin-app-cache-key-Ceb-lm2c.js +315 -0
  20. package/dist/{provider-zjPfx5Fs.js → rate-limits-DyXaYAxU.js} +10 -266
  21. package/dist/request-B_oQsCXy.js +157 -0
  22. package/dist/{run-attempt-FUyOjGCV.js → run-attempt-MLzoMe_m.js} +7395 -6430
  23. package/dist/runtime-artifact-C2ITXdhM.js +488 -0
  24. package/dist/{sandbox-guard-DA2TQfZW.js → sandbox-guard-D1Wky__S.js} +10 -1
  25. package/dist/{config-CYEDnLJ2.js → session-binding-h1mmCGnl.js} +985 -31
  26. package/dist/session-catalog-CEvoXWHA.js +2412 -0
  27. package/dist/session-cli-XsEuWb_C.js +175 -0
  28. package/dist/{shared-client-4ICy3U6d.js → shared-client-JiAnW6pc.js} +2193 -1319
  29. package/dist/{side-question-N4OaDer2.js → side-question-DqDvIwSU.js} +140 -70
  30. package/dist/{thread-lifecycle-qWE88Dn2.js → thread-lifecycle-CN_pPtPh.js} +1826 -1188
  31. package/dist/{protocol-validators-dZQ-UTOa.js → transcript-mirror-D9rTxx2P.js} +485 -2
  32. package/dist/transport-stdio-DXgGZ7Ib.js +88 -0
  33. package/dist/usage-D5Rohxoc.js +25 -0
  34. package/dist/{web-search-provider.runtime-BSlriav6.js → web-search-provider.runtime-CKVBn3fP.js} +3 -3
  35. package/npm-shrinkwrap.json +56 -30
  36. package/openclaw.plugin.json +177 -14
  37. package/package.json +8 -6
  38. package/dist/command-rpc-eLM_mtC7.js +0 -784
  39. package/dist/computer-use-Bmaz333N.js +0 -377
  40. package/dist/notification-correlation-Bo7KB3ks.js +0 -35
  41. package/dist/plugin-app-cache-key-BrhVdeEf.js +0 -98
  42. package/dist/prompt-overlay.js +0 -15
  43. package/dist/protocol-2POPqAY4.js +0 -13
  44. package/dist/provider-catalog.js +0 -79
  45. package/dist/provider-discovery.js +0 -34
  46. package/dist/provider.js +0 -2
  47. package/dist/request-BcJyl8KL.js +0 -36
  48. package/dist/session-binding-C1ZXdP-x.js +0 -627
@@ -1,5 +1,9 @@
1
- import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
1
+ import { createHash } from "node:crypto";
2
+ import { isRecord, normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
2
3
  import { Compile } from "typebox/compile";
4
+ import { embeddedAgentLog, formatErrorMessage, runAgentHarnessBeforeMessageWriteHook } from "openclaw/plugin-sdk/agent-harness-runtime";
5
+ import { Buffer } from "node:buffer";
6
+ import { publishSessionTranscriptUpdateByIdentity, withSessionTranscriptWriteLock } from "openclaw/plugin-sdk/session-transcript-runtime";
3
7
  //#region extensions/codex/src/app-server/protocol-generated/json/DynamicToolCallParams.json
4
8
  var DynamicToolCallParams_default = {
5
9
  $schema: "http://json-schema.org/draft-07/schema#",
@@ -6111,4 +6115,483 @@ function formatValidationErrors(validate, value) {
6111
6115
  }).join("; ");
6112
6116
  }
6113
6117
  //#endregion
6114
- export { readCodexDynamicToolCallParams as a, readCodexTurn as c, assertCodexTurnStartResponse as i, readCodexTurnCompletedNotification as l, assertCodexThreadResumeResponse as n, readCodexErrorNotification as o, assertCodexThreadStartResponse as r, readCodexModelListResponse as s, assertCodexThreadForkResponse as t };
6118
+ //#region extensions/codex/src/app-server/upstream-prompt-provenance.ts
6119
+ const UPSTREAM_USER_TEXT_META_KEY = "upstreamUserText";
6120
+ const MIRROR_IDENTITY_META_KEY = "mirrorIdentity";
6121
+ function attachCodexMirrorIdentity(message, identity) {
6122
+ const record = message;
6123
+ const existing = record["__openclaw"];
6124
+ const baseMeta = existing && typeof existing === "object" && !Array.isArray(existing) ? existing : {};
6125
+ return {
6126
+ ...record,
6127
+ __openclaw: {
6128
+ ...baseMeta,
6129
+ [MIRROR_IDENTITY_META_KEY]: identity
6130
+ }
6131
+ };
6132
+ }
6133
+ function readMirrorIdentity(message) {
6134
+ const meta = message["__openclaw"];
6135
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)) return;
6136
+ const id = meta[MIRROR_IDENTITY_META_KEY];
6137
+ return typeof id === "string" && id ? id : void 0;
6138
+ }
6139
+ function attachUpstreamUserText(message, text) {
6140
+ const record = message;
6141
+ const existing = record["__openclaw"];
6142
+ const baseMeta = existing && typeof existing === "object" && !Array.isArray(existing) ? existing : {};
6143
+ return {
6144
+ ...record,
6145
+ __openclaw: {
6146
+ ...baseMeta,
6147
+ [UPSTREAM_USER_TEXT_META_KEY]: text
6148
+ }
6149
+ };
6150
+ }
6151
+ function readUpstreamUserText(message) {
6152
+ const meta = message?.["__openclaw"];
6153
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)) return;
6154
+ const text = meta[UPSTREAM_USER_TEXT_META_KEY];
6155
+ return typeof text === "string" && text ? text : void 0;
6156
+ }
6157
+ //#endregion
6158
+ //#region extensions/codex/src/app-server/user-prompt-message.ts
6159
+ function buildSenderLabel(params) {
6160
+ const label = params.senderName ?? params.senderUsername ?? params.senderE164 ?? params.senderId;
6161
+ if (!label) return;
6162
+ return !params.senderId || label.includes(params.senderId) ? label : `${label} (${params.senderId})`;
6163
+ }
6164
+ function buildFromPrepared(params, preparedUserMessage) {
6165
+ const senderId = normalizeOptionalString(params.senderId);
6166
+ const senderName = normalizeOptionalString(params.senderName);
6167
+ const senderUsername = normalizeOptionalString(params.senderUsername);
6168
+ const senderE164 = normalizeOptionalString(params.senderE164);
6169
+ const senderLabel = buildSenderLabel({
6170
+ senderId,
6171
+ senderName,
6172
+ senderUsername,
6173
+ senderE164
6174
+ });
6175
+ const sourceChannel = normalizeOptionalString(params.inputProvenance?.sourceChannel ?? params.messageChannel ?? params.messageProvider);
6176
+ return {
6177
+ role: "user",
6178
+ timestamp: Date.now(),
6179
+ ...params.inputProvenance ? { provenance: params.inputProvenance } : {},
6180
+ ...sourceChannel ? { sourceChannel } : {},
6181
+ ...senderId ? { senderId } : {},
6182
+ ...senderName ? { senderName } : {},
6183
+ ...senderUsername ? { senderUsername } : {},
6184
+ ...senderE164 ? { senderE164 } : {},
6185
+ ...senderLabel ? { senderLabel } : {},
6186
+ ...preparedUserMessage ? preparedUserMessage : { content: params.prompt }
6187
+ };
6188
+ }
6189
+ function buildCodexUserPromptMessage(params) {
6190
+ return buildFromPrepared(params, params.userTurnTranscriptRecorder?.message);
6191
+ }
6192
+ function buildCodexUpstreamPromptMessage(params, identity, upstreamUserText) {
6193
+ const message = attachCodexMirrorIdentity(buildCodexUserPromptMessage(params), identity);
6194
+ return upstreamUserText ? attachUpstreamUserText(message, upstreamUserText) : message;
6195
+ }
6196
+ function promptSnapshot(params, turnId, upstreamUserText) {
6197
+ return params.suppressNextUserMessagePersistence ? [] : [buildCodexUpstreamPromptMessage(params, `${turnId}:prompt`, upstreamUserText)];
6198
+ }
6199
+ async function buildResolvedCodexUserPromptMessage(params) {
6200
+ return buildFromPrepared(params, await params.userTurnTranscriptRecorder?.resolveMessage() ?? params.userTurnTranscriptRecorder?.message);
6201
+ }
6202
+ //#endregion
6203
+ //#region extensions/codex/src/app-server/transcript-mirror.ts
6204
+ const MIRROR_ORIGIN_META_KEY = "mirrorOrigin";
6205
+ const CODEX_APP_SERVER_MIRROR_ORIGIN = "codex-app-server";
6206
+ const CODEX_HISTORY_IMPORT_MAX_MESSAGES = 200;
6207
+ const CODEX_HISTORY_IMPORT_MAX_BYTES = 512 * 1024;
6208
+ const CODEX_HISTORY_IMPORT_MAX_MESSAGE_BYTES = 64 * 1024;
6209
+ const CODEX_HISTORY_TRUNCATION_SUFFIX = "\n\n[Message truncated during Codex history import.]";
6210
+ const CODEX_HISTORY_ASSISTANT_API = "openai-chatgpt-responses";
6211
+ const CODEX_HISTORY_ASSISTANT_PROVIDER = "openai";
6212
+ const CODEX_HISTORY_ASSISTANT_MODEL = "native-history";
6213
+ const CODEX_HISTORY_ZERO_USAGE = {
6214
+ input: 0,
6215
+ output: 0,
6216
+ cacheRead: 0,
6217
+ cacheWrite: 0,
6218
+ totalTokens: 0,
6219
+ cost: {
6220
+ input: 0,
6221
+ output: 0,
6222
+ cacheRead: 0,
6223
+ cacheWrite: 0,
6224
+ total: 0
6225
+ }
6226
+ };
6227
+ function isUtf8ContinuationByte(byte) {
6228
+ return byte !== void 0 && (byte & 192) === 128;
6229
+ }
6230
+ function truncateUtf8Prefix(value, maxBytes) {
6231
+ const bytes = Buffer.from(value);
6232
+ if (bytes.byteLength <= maxBytes) return value;
6233
+ let end = Math.max(0, maxBytes);
6234
+ while (end > 0 && isUtf8ContinuationByte(bytes[end])) end -= 1;
6235
+ return bytes.subarray(0, end).toString("utf8");
6236
+ }
6237
+ function normalizeImportedHistoryText(value) {
6238
+ if (typeof value !== "string") return;
6239
+ const text = value.trim();
6240
+ if (!text) return;
6241
+ if (Buffer.byteLength(text, "utf8") <= CODEX_HISTORY_IMPORT_MAX_MESSAGE_BYTES) return text;
6242
+ const suffixBytes = Buffer.byteLength(CODEX_HISTORY_TRUNCATION_SUFFIX, "utf8");
6243
+ return `${truncateUtf8Prefix(text, Math.max(0, CODEX_HISTORY_IMPORT_MAX_MESSAGE_BYTES - suffixBytes))}${CODEX_HISTORY_TRUNCATION_SUFFIX}`;
6244
+ }
6245
+ function projectCodexUserItemText(item) {
6246
+ if (!Array.isArray(item.content)) return;
6247
+ const parts = [];
6248
+ for (const value of item.content) {
6249
+ if (!value || typeof value !== "object" || Array.isArray(value)) continue;
6250
+ const input = value;
6251
+ if (input.type === "text") {
6252
+ const text = normalizeImportedHistoryText(input.text);
6253
+ if (text) parts.push(text);
6254
+ continue;
6255
+ }
6256
+ if (input.type === "image" || input.type === "localImage") {
6257
+ parts.push("[Image attachment]");
6258
+ continue;
6259
+ }
6260
+ if (input.type === "skill" || input.type === "mention") {
6261
+ const name = normalizeOptionalString(input.name);
6262
+ if (name) parts.push(`${input.type === "skill" ? "$" : "@"}${name}`);
6263
+ }
6264
+ }
6265
+ return normalizeImportedHistoryText(parts.join("\n"));
6266
+ }
6267
+ function selectTurnsThroughBoundary(thread, throughTurnId) {
6268
+ if (throughTurnId === null) return [];
6269
+ const turns = thread.turns ?? [];
6270
+ const boundaryIndex = turns.findIndex((turn) => turn.id === throughTurnId);
6271
+ if (boundaryIndex < 0) throw new Error(`Codex history boundary turn not found: ${throughTurnId}`);
6272
+ const boundary = turns[boundaryIndex];
6273
+ if (boundary?.status !== "completed" && boundary?.status !== "interrupted" && boundary?.status !== "failed") throw new Error(`Codex history boundary turn is not terminal: ${throughTurnId}`);
6274
+ return turns.slice(0, boundaryIndex + 1);
6275
+ }
6276
+ function projectCodexThreadHistory(params) {
6277
+ const projected = [];
6278
+ const threadTimestamp = typeof params.thread.createdAt === "number" && Number.isFinite(params.thread.createdAt) ? params.thread.createdAt * 1e3 : params.importedAt;
6279
+ let itemOffset = 0;
6280
+ for (const turn of selectTurnsThroughBoundary(params.thread, params.throughTurnId)) for (const value of turn.items) {
6281
+ const item = value;
6282
+ const itemId = normalizeOptionalString(item.id);
6283
+ const identity = `${turn.id}:${itemId ?? itemOffset}`;
6284
+ const timestampSeconds = item.type === "agentMessage" ? turn.completedAt ?? turn.startedAt : turn.startedAt ?? turn.completedAt;
6285
+ const timestamp = typeof timestampSeconds === "number" && Number.isFinite(timestampSeconds) ? timestampSeconds * 1e3 + itemOffset : threadTimestamp + itemOffset;
6286
+ const text = item.type === "userMessage" ? projectCodexUserItemText(item) : item.type === "agentMessage" ? normalizeImportedHistoryText(item.text) : void 0;
6287
+ const role = item.type === "userMessage" ? "user" : item.type === "agentMessage" ? "assistant" : void 0;
6288
+ itemOffset += 1;
6289
+ if (!text || !role) continue;
6290
+ const message = role === "assistant" ? attachCodexMirrorIdentity({
6291
+ role,
6292
+ content: [{
6293
+ type: "text",
6294
+ text
6295
+ }],
6296
+ api: CODEX_HISTORY_ASSISTANT_API,
6297
+ provider: normalizeOptionalString(params.modelProvider) ?? normalizeOptionalString(params.thread.modelProvider) ?? CODEX_HISTORY_ASSISTANT_PROVIDER,
6298
+ model: CODEX_HISTORY_ASSISTANT_MODEL,
6299
+ usage: CODEX_HISTORY_ZERO_USAGE,
6300
+ stopReason: "stop",
6301
+ timestamp
6302
+ }, identity) : attachCodexMirrorIdentity({
6303
+ role,
6304
+ content: text,
6305
+ timestamp
6306
+ }, identity);
6307
+ const phase = item.phase === "commentary" || item.phase === "final_answer" ? item.phase : void 0;
6308
+ projected.push({
6309
+ message,
6310
+ responseItem: {
6311
+ type: "message",
6312
+ role,
6313
+ content: [{
6314
+ type: role === "assistant" ? "output_text" : "input_text",
6315
+ text
6316
+ }],
6317
+ ...role === "assistant" && phase ? { phase } : {}
6318
+ },
6319
+ textBytes: Buffer.byteLength(text, "utf8")
6320
+ });
6321
+ }
6322
+ return projected;
6323
+ }
6324
+ function selectBoundedCodexHistoryTail(projected) {
6325
+ const selected = [];
6326
+ let selectedBytes = 0;
6327
+ for (let index = projected.length - 1; index >= 0; index -= 1) {
6328
+ const candidate = projected[index];
6329
+ if (!candidate) continue;
6330
+ if (selected.length >= CODEX_HISTORY_IMPORT_MAX_MESSAGES || selectedBytes + candidate.textBytes > CODEX_HISTORY_IMPORT_MAX_BYTES) break;
6331
+ selected.push(candidate);
6332
+ selectedBytes += candidate.textBytes;
6333
+ }
6334
+ return selected.toReversed();
6335
+ }
6336
+ /** Projects one terminal Codex history prefix into transcript and Responses API items. */
6337
+ function projectBoundedCodexThreadHistory(params) {
6338
+ const projected = projectCodexThreadHistory({
6339
+ thread: params.thread,
6340
+ throughTurnId: params.throughTurnId,
6341
+ importedAt: params.importedAt,
6342
+ ...params.modelProvider ? { modelProvider: params.modelProvider } : {}
6343
+ });
6344
+ const selected = selectBoundedCodexHistoryTail(projected);
6345
+ return {
6346
+ importedMessages: selected.length,
6347
+ omittedMessages: projected.length - selected.length,
6348
+ responseItems: selected.map(({ responseItem }) => responseItem),
6349
+ transcriptMessages: selected.map(({ message }) => message)
6350
+ };
6351
+ }
6352
+ /** Imports a bounded, user-visible Codex history tail into a new OpenClaw transcript. */
6353
+ async function importCodexThreadHistoryToTranscript(params) {
6354
+ const projection = projectBoundedCodexThreadHistory({
6355
+ thread: params.thread,
6356
+ throughTurnId: params.throughTurnId,
6357
+ importedAt: Date.now(),
6358
+ ...params.modelProvider ? { modelProvider: params.modelProvider } : {}
6359
+ });
6360
+ if (projection.transcriptMessages.length > 0) await mirror({
6361
+ storePath: params.storePath,
6362
+ sessionId: params.sessionId,
6363
+ sessionKey: params.sessionKey,
6364
+ ...params.agentId ? { agentId: params.agentId } : {},
6365
+ ...params.cwd ? { cwd: params.cwd } : {},
6366
+ ...params.config ? { config: params.config } : {},
6367
+ messages: projection.transcriptMessages,
6368
+ idempotencyScope: `codex-app-server:${params.thread.id}:history`
6369
+ });
6370
+ return {
6371
+ importedMessages: projection.importedMessages,
6372
+ omittedMessages: projection.omittedMessages
6373
+ };
6374
+ }
6375
+ function attachCodexMirrorOrigin(message) {
6376
+ const record = message;
6377
+ const existing = record["__openclaw"];
6378
+ const baseMeta = existing && typeof existing === "object" && !Array.isArray(existing) ? existing : {};
6379
+ return {
6380
+ ...record,
6381
+ __openclaw: {
6382
+ ...baseMeta,
6383
+ [MIRROR_ORIGIN_META_KEY]: CODEX_APP_SERVER_MIRROR_ORIGIN
6384
+ }
6385
+ };
6386
+ }
6387
+ async function mirrorBestEffort(params) {
6388
+ try {
6389
+ const messages = await resolveFinalCodexMirrorMessages({
6390
+ params: params.params,
6391
+ messagesSnapshot: params.result.messagesSnapshot,
6392
+ turnId: params.turnId
6393
+ });
6394
+ const mirrorResult = await mirror({
6395
+ agentId: params.agentId,
6396
+ sessionKey: params.sessionKey,
6397
+ sessionId: params.params.sessionId,
6398
+ storePath: params.params.sessionTarget?.storePath,
6399
+ cwd: params.cwd,
6400
+ messages,
6401
+ idempotencyScope: `codex-app-server:${params.threadId}`,
6402
+ config: params.params.config
6403
+ });
6404
+ for (const message of mirrorResult.userMessagesPresent) try {
6405
+ params.notifyUserMessagePersisted(message);
6406
+ } catch (error) {
6407
+ embeddedAgentLog.warn("failed to notify codex app-server user-message persistence", { error: formatErrorMessage(error) });
6408
+ }
6409
+ return mirrorResult.assistantMirrorIdentitiesOwned.includes(`${params.turnId}:assistant`);
6410
+ } catch (error) {
6411
+ embeddedAgentLog.warn("failed to mirror codex app-server transcript", { error });
6412
+ return false;
6413
+ }
6414
+ }
6415
+ async function resolveFinalCodexMirrorMessages(params) {
6416
+ if (params.params.suppressNextUserMessagePersistence || !params.params.userTurnTranscriptRecorder) return params.messagesSnapshot;
6417
+ const promptSnapshot = params.messagesSnapshot.find((message) => message.role === "user");
6418
+ const resolvedBase = attachCodexMirrorIdentity(await buildResolvedCodexUserPromptMessage(params.params), `${params.turnId}:prompt`);
6419
+ const upstreamUserText = readUpstreamUserText(promptSnapshot);
6420
+ const resolvedPrompt = upstreamUserText ? attachUpstreamUserText(resolvedBase, upstreamUserText) : resolvedBase;
6421
+ const firstUserIndex = params.messagesSnapshot.findIndex((message) => message.role === "user");
6422
+ if (firstUserIndex === -1) return [resolvedPrompt, ...params.messagesSnapshot];
6423
+ const messages = params.messagesSnapshot.slice();
6424
+ messages[firstUserIndex] = resolvedPrompt;
6425
+ return messages;
6426
+ }
6427
+ function createCodexAppServerUserMessagePersistenceNotifier(runParams) {
6428
+ let notified = false;
6429
+ return (message) => {
6430
+ if (notified) return;
6431
+ notified = true;
6432
+ runParams.userTurnTranscriptRecorder?.markRuntimePersisted(message);
6433
+ try {
6434
+ runParams.onUserMessagePersisted?.(message);
6435
+ } catch (error) {
6436
+ embeddedAgentLog.warn("codex app-server user persistence notification failed", { error: formatErrorMessage(error) });
6437
+ }
6438
+ };
6439
+ }
6440
+ async function mirrorPromptAtTurnStartBestEffort(params) {
6441
+ if (params.params.suppressNextUserMessagePersistence) return;
6442
+ try {
6443
+ const mirrorPromise = (async () => {
6444
+ const userPromptMessage = attachUpstreamUserText(attachCodexMirrorIdentity(await buildResolvedCodexUserPromptMessage(params.params), `${params.turnId}:prompt`), params.upstreamUserText);
6445
+ const mirrorResult = await mirror({
6446
+ agentId: params.agentId,
6447
+ sessionKey: params.sessionKey,
6448
+ sessionId: params.params.sessionId,
6449
+ storePath: params.params.sessionTarget?.storePath,
6450
+ cwd: params.cwd,
6451
+ messages: [userPromptMessage],
6452
+ idempotencyScope: `codex-app-server:${params.threadId}`,
6453
+ config: params.params.config
6454
+ });
6455
+ for (const message of mirrorResult.userMessagesPresent) params.notifyUserMessagePersisted(message);
6456
+ })();
6457
+ params.params.userTurnTranscriptRecorder?.markRuntimePersistencePending(mirrorPromise);
6458
+ await mirrorPromise;
6459
+ } catch (error) {
6460
+ embeddedAgentLog.warn("failed to mirror codex app-server prompt at turn start", { error });
6461
+ }
6462
+ }
6463
+ function fingerprintMirrorMessageContent(message) {
6464
+ const payload = JSON.stringify({
6465
+ role: message.role,
6466
+ content: message.content
6467
+ });
6468
+ return createHash("sha256").update(payload).digest("hex").slice(0, 16);
6469
+ }
6470
+ function buildMirrorDedupeIdentity(message) {
6471
+ const explicit = readMirrorIdentity(message);
6472
+ if (explicit) return explicit;
6473
+ return `${message.role}:${fingerprintMirrorMessageContent(message)}`;
6474
+ }
6475
+ async function mirror(params) {
6476
+ const messages = params.messages.filter((message) => message.role === "user" || message.role === "assistant" || message.role === "toolResult");
6477
+ if (messages.length === 0) return {
6478
+ assistantMirrorIdentitiesOwned: [],
6479
+ userMessagesPresent: []
6480
+ };
6481
+ const transcriptTarget = resolveCodexMirrorTranscriptTarget(params);
6482
+ const { appendedUpdates, assistantMirrorIdentitiesOwned, userMessagesPresent } = await withSessionTranscriptWriteLock({
6483
+ ...transcriptTarget,
6484
+ config: params.config
6485
+ }, async (transcript) => {
6486
+ const nextAppendedUpdates = [];
6487
+ const nextAssistantMirrorIdentitiesOwned = /* @__PURE__ */ new Set();
6488
+ const nextUserMessagesPresent = [];
6489
+ const mirrorState = readTranscriptMirrorState(await transcript.readEvents());
6490
+ let nextMessageSeq = mirrorState.messageCount;
6491
+ for (const message of messages) {
6492
+ const dedupeIdentity = buildMirrorDedupeIdentity(message);
6493
+ const idempotencyKey = (message.role === "user" ? normalizeOptionalString(message.idempotencyKey) : void 0) ?? (params.idempotencyScope ? `${params.idempotencyScope}:${dedupeIdentity}` : void 0);
6494
+ const transcriptMessage = {
6495
+ ...attachCodexMirrorOrigin(message),
6496
+ ...idempotencyKey ? { idempotencyKey } : {}
6497
+ };
6498
+ if (idempotencyKey && mirrorState.idempotencyKeys.has(idempotencyKey)) {
6499
+ const persistedUserMessage = mirrorState.userMessagesByIdempotencyKey.get(idempotencyKey);
6500
+ if (persistedUserMessage) nextUserMessagesPresent.push(persistedUserMessage);
6501
+ if (message.role === "assistant") nextAssistantMirrorIdentitiesOwned.add(dedupeIdentity);
6502
+ continue;
6503
+ }
6504
+ const nextMessage = runAgentHarnessBeforeMessageWriteHook({
6505
+ message: transcriptMessage,
6506
+ agentId: params.agentId,
6507
+ sessionKey: params.sessionKey
6508
+ });
6509
+ if (!nextMessage) {
6510
+ if (message.role === "assistant") nextAssistantMirrorIdentitiesOwned.add(dedupeIdentity);
6511
+ continue;
6512
+ }
6513
+ const messageToAppend = idempotencyKey ? {
6514
+ ...attachCodexMirrorOrigin(nextMessage),
6515
+ idempotencyKey
6516
+ } : attachCodexMirrorOrigin(nextMessage);
6517
+ const appended = await transcript.appendMessage({
6518
+ message: messageToAppend,
6519
+ idempotencyLookup: idempotencyKey ? "caller-checked" : "scan",
6520
+ cwd: params.cwd
6521
+ });
6522
+ if (!appended) continue;
6523
+ const { messageId, message: appendedMessage } = appended;
6524
+ if (message.role === "assistant") nextAssistantMirrorIdentitiesOwned.add(dedupeIdentity);
6525
+ if (appendedMessage.role === "user") {
6526
+ nextUserMessagesPresent.push(appendedMessage);
6527
+ if (idempotencyKey) mirrorState.userMessagesByIdempotencyKey.set(idempotencyKey, appendedMessage);
6528
+ }
6529
+ nextMessageSeq += 1;
6530
+ nextAppendedUpdates.push({
6531
+ messageId,
6532
+ message: appendedMessage,
6533
+ messageSeq: nextMessageSeq
6534
+ });
6535
+ if (idempotencyKey) mirrorState.idempotencyKeys.add(idempotencyKey);
6536
+ }
6537
+ return {
6538
+ appendedUpdates: nextAppendedUpdates,
6539
+ assistantMirrorIdentitiesOwned: [...nextAssistantMirrorIdentitiesOwned],
6540
+ userMessagesPresent: nextUserMessagesPresent
6541
+ };
6542
+ });
6543
+ for (const update of appendedUpdates) try {
6544
+ await publishSessionTranscriptUpdateByIdentity({
6545
+ ...transcriptTarget,
6546
+ update: {
6547
+ ...params.agentId ? { agentId: params.agentId } : {},
6548
+ message: update.message,
6549
+ messageId: update.messageId,
6550
+ messageSeq: update.messageSeq,
6551
+ sessionKey: transcriptTarget.sessionKey
6552
+ }
6553
+ });
6554
+ } catch (error) {
6555
+ embeddedAgentLog.warn("failed to publish codex app-server transcript update", { error: formatErrorMessage(error) });
6556
+ }
6557
+ return {
6558
+ assistantMirrorIdentitiesOwned,
6559
+ userMessagesPresent
6560
+ };
6561
+ }
6562
+ const codexTranscriptMirrorRuntime = {
6563
+ mirror,
6564
+ mirrorBestEffort
6565
+ };
6566
+ function resolveCodexMirrorTranscriptTarget(params) {
6567
+ const sessionKey = params.sessionKey?.trim();
6568
+ const storePath = params.storePath?.trim();
6569
+ if (!sessionKey || !storePath) throw new Error("Codex transcript mirror requires a runtime session identity");
6570
+ return {
6571
+ ...params.agentId ? { agentId: params.agentId } : {},
6572
+ sessionId: params.sessionId,
6573
+ sessionKey,
6574
+ storePath
6575
+ };
6576
+ }
6577
+ function readTranscriptMirrorState(events) {
6578
+ const idempotencyKeys = /* @__PURE__ */ new Set();
6579
+ const userMessagesByIdempotencyKey = /* @__PURE__ */ new Map();
6580
+ let messageCount = 0;
6581
+ for (const event of events) {
6582
+ if (!event || typeof event !== "object" || Array.isArray(event)) continue;
6583
+ const parsed = event;
6584
+ if (parsed.type === "message") messageCount += 1;
6585
+ if (typeof parsed.message?.idempotencyKey === "string") {
6586
+ idempotencyKeys.add(parsed.message.idempotencyKey);
6587
+ if (parsed.message.role === "user") userMessagesByIdempotencyKey.set(parsed.message.idempotencyKey, parsed.message);
6588
+ }
6589
+ }
6590
+ return {
6591
+ idempotencyKeys,
6592
+ messageCount,
6593
+ userMessagesByIdempotencyKey
6594
+ };
6595
+ }
6596
+ //#endregion
6597
+ export { readCodexTurnCompletedNotification as _, projectBoundedCodexThreadHistory as a, attachCodexMirrorIdentity as c, assertCodexThreadStartResponse as d, assertCodexTurnStartResponse as f, readCodexTurn as g, readCodexModelListResponse as h, mirrorPromptAtTurnStartBestEffort as i, assertCodexThreadForkResponse as l, readCodexErrorNotification as m, createCodexAppServerUserMessagePersistenceNotifier as n, buildCodexUserPromptMessage as o, readCodexDynamicToolCallParams as p, importCodexThreadHistoryToTranscript as r, promptSnapshot as s, codexTranscriptMirrorRuntime as t, assertCodexThreadResumeResponse as u };
@@ -0,0 +1,88 @@
1
+ import { materializeWindowsSpawnProgram, resolveWindowsSpawnProgram } from "openclaw/plugin-sdk/windows-spawn";
2
+ import { spawn } from "node:child_process";
3
+ //#region extensions/codex/src/app-server/transport-stdio.ts
4
+ /**
5
+ * Creates and configures stdio-backed Codex app-server transports, including
6
+ * Windows spawn normalization and environment filtering.
7
+ */
8
+ const UNSAFE_ENVIRONMENT_KEYS = /* @__PURE__ */ new Set([
9
+ "__proto__",
10
+ "constructor",
11
+ "prototype"
12
+ ]);
13
+ const QA_PARENT_PID_ENV = "OPENCLAW_QA_PARENT_PID";
14
+ const DEFAULT_SPAWN_RUNTIME = {
15
+ platform: process.platform,
16
+ env: process.env,
17
+ execPath: process.execPath
18
+ };
19
+ /** Resolves the concrete command/argv/shell settings used to spawn Codex app-server. */
20
+ function resolveCodexAppServerSpawnInvocation(options, runtime = DEFAULT_SPAWN_RUNTIME) {
21
+ if (options.commandSource === "managed") throw new Error("Managed Codex app-server start options must be resolved before spawn.");
22
+ const resolved = materializeWindowsSpawnProgram(resolveWindowsSpawnProgram({
23
+ command: options.command,
24
+ platform: runtime.platform,
25
+ env: runtime.env,
26
+ execPath: runtime.execPath,
27
+ packageName: "@openai/codex"
28
+ }), options.args);
29
+ return {
30
+ command: resolved.command,
31
+ args: resolved.argv,
32
+ shell: resolved.shell,
33
+ windowsHide: resolved.windowsHide
34
+ };
35
+ }
36
+ /** Merges app-server environment overrides while honoring clearEnv and unsafe key filtering. */
37
+ function resolveCodexAppServerSpawnEnv(options, baseEnv = process.env, platform = process.platform) {
38
+ const env = Object.create(null);
39
+ copySafeEnvironmentEntries(env, baseEnv);
40
+ copySafeEnvironmentEntries(env, options.env ?? {});
41
+ const keysToClear = normalizedEnvironmentKeys(options.clearEnv ?? []);
42
+ if (platform === "win32") {
43
+ const lowerCaseKeysToClear = new Set(keysToClear.map((key) => key.toLowerCase()));
44
+ for (const candidate of Object.keys(env)) if (lowerCaseKeysToClear.has(candidate.toLowerCase())) delete env[candidate];
45
+ } else for (const key of keysToClear) delete env[key];
46
+ return env;
47
+ }
48
+ /** Keeps QA-owned app-server processes inside the gateway process-group cleanup boundary. */
49
+ function resolveCodexAppServerDetachedMode(env, platform = process.platform) {
50
+ return platform !== "win32" && !env[QA_PARENT_PID_ENV]?.trim();
51
+ }
52
+ function normalizedEnvironmentKeys(rawKeys) {
53
+ const keys = [];
54
+ for (const rawKey of rawKeys) {
55
+ const key = rawKey.trim();
56
+ if (key.length > 0) keys.push(key);
57
+ }
58
+ return keys;
59
+ }
60
+ function copySafeEnvironmentEntries(target, source) {
61
+ for (const [key, value] of Object.entries(source)) {
62
+ if (UNSAFE_ENVIRONMENT_KEYS.has(key)) continue;
63
+ target[key] = value;
64
+ }
65
+ }
66
+ /** Spawns the Codex app-server process and returns the shared transport interface. */
67
+ function createStdioTransport(options) {
68
+ const env = resolveCodexAppServerSpawnEnv(options);
69
+ const invocation = resolveCodexAppServerSpawnInvocation(options, {
70
+ platform: process.platform,
71
+ env,
72
+ execPath: process.execPath
73
+ });
74
+ return spawn(invocation.command, invocation.args, {
75
+ ...options.cwd !== void 0 ? { cwd: options.cwd } : {},
76
+ env,
77
+ detached: resolveCodexAppServerDetachedMode(env),
78
+ shell: invocation.shell,
79
+ stdio: [
80
+ "pipe",
81
+ "pipe",
82
+ "pipe"
83
+ ],
84
+ windowsHide: invocation.windowsHide
85
+ });
86
+ }
87
+ //#endregion
88
+ export { resolveCodexAppServerSpawnEnv as n, createStdioTransport as t };
@@ -0,0 +1,25 @@
1
+ import { b as resolveCodexAppServerRuntimeOptions } from "./session-binding-h1mmCGnl.js";
2
+ import { t as buildCodexAppServerUsageSnapshot } from "./rate-limits-DyXaYAxU.js";
3
+ import { t as readCodexAppServerUsage } from "./request-B_oQsCXy.js";
4
+ import { CODEX_APP_SERVER_AUTH_MARKER } from "openclaw/plugin-sdk/agent-runtime";
5
+ //#region extensions/codex/src/app-server/usage.ts
6
+ /** Handles the synthetic usage credential for a Codex-backed OpenAI route. */
7
+ async function fetchCodexAppServerUsageSnapshot(ctx, options = {}) {
8
+ if (ctx.token !== CODEX_APP_SERVER_AUTH_MARKER) return null;
9
+ const appServer = resolveCodexAppServerRuntimeOptions({ pluginConfig: options.pluginConfig });
10
+ const usage = await (options.readUsage ?? readCodexAppServerUsage)({
11
+ timeoutMs: ctx.timeoutMs,
12
+ agentDir: ctx.agentDir,
13
+ ...ctx.authProfileId ? { authProfileId: ctx.authProfileId } : {},
14
+ config: ctx.config,
15
+ startOptions: appServer.start
16
+ });
17
+ const snapshot = buildCodexAppServerUsageSnapshot(usage.rateLimits);
18
+ const accountEmail = ctx.email ?? usage.accountEmail;
19
+ return accountEmail && !snapshot.error ? {
20
+ ...snapshot,
21
+ accountEmail
22
+ } : snapshot;
23
+ }
24
+ //#endregion
25
+ export { fetchCodexAppServerUsageSnapshot };
@@ -1,6 +1,6 @@
1
- import { r as isJsonObject } from "./protocol-2POPqAY4.js";
2
- import { _ as buildCodexNativeWebSearchThreadConfig } from "./thread-lifecycle-qWE88Dn2.js";
3
- import { n as runBoundedCodexAppServerTurn } from "./media-understanding-provider-BHOu9-Gg.js";
1
+ import { Z as isJsonObject } from "./shared-client-JiAnW6pc.js";
2
+ import { u as buildCodexNativeWebSearchThreadConfig } from "./thread-lifecycle-CN_pPtPh.js";
3
+ import { n as runBoundedCodexAppServerTurn } from "./media-understanding-provider-D31dOJwb.js";
4
4
  import { readStringParam, resolveSearchTimeoutSeconds, wrapWebContent } from "openclaw/plugin-sdk/provider-web-search";
5
5
  //#region extensions/codex/src/web-search-provider.runtime.ts
6
6
  async function executeCodexWebSearchProviderTool(ctx, args, executionContext, options) {