@openclaw/codex 2026.9.2 → 2026.9.4

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 (120) hide show
  1. package/README.md +2 -0
  2. package/dist/api.js +29 -26
  3. package/dist/apply-CvT8tW5i.js +356 -0
  4. package/dist/{attempt-client-cleanup-Bp1ZOnk2.js → attempt-client-cleanup-DKHzbwt5.js} +38 -214
  5. package/dist/{attempt-context-CSazkWns.js → attempt-context-D44yeDII.js} +9 -7
  6. package/dist/{event-projector-usage-ZqEVbAEY.js → attempt-notifications-C9XufG6l.js} +3 -106
  7. package/dist/{auth-binding-Ds_QVm-X.js → auth-binding-CWlKVccJ.js} +2 -2
  8. package/dist/auth-cache-key-7orQae_j.js +498 -0
  9. package/dist/auth-profile-CwzO4_RG.js +43 -0
  10. package/dist/auth-profile-selection-DFu9e167.js +45 -0
  11. package/dist/binding-connection-D3udKbIE.js +60 -0
  12. package/dist/{bounded-turn-DxGJRYbY.js → bounded-turn-C_Hneydj.js} +28 -125
  13. package/dist/build-state-BCmg9-5p.js +19 -0
  14. package/dist/{capabilities-B1mgvpP8.js → capabilities-8vx68WLH.js} +1 -1
  15. package/dist/cli-metadata.js +1 -1
  16. package/dist/client-B57KWPQx.js +4005 -0
  17. package/dist/command-dispatch-BpduNGVf.js +21 -0
  18. package/dist/{command-formatters-DSbGMXA0.js → command-formatters-lxlkNZgU.js} +4 -3
  19. package/dist/{command-handlers-DOJvGv6-.js → command-handlers-tiL9iWj7.js} +788 -135
  20. package/dist/command-rpc-CR5EOEZX.js +233 -0
  21. package/dist/{compact-Y_xBqrHN.js → compact-B_H3AOd7.js} +19 -14
  22. package/dist/config-oIORaQ5T.js +106 -0
  23. package/dist/{config-CyapYSji.js → config-options-CXMq1T-C.js} +205 -593
  24. package/dist/config-runtime-D0zGNIHu.js +11 -0
  25. package/dist/{config-utils-C57JiJrU.js → config-utils-DujwEnhg.js} +2 -4
  26. package/dist/conversation-binding-DsB4-O7U.js +900 -0
  27. package/dist/{plugin-marketplace-discovery-B7gHXJ3d.js → conversation-control-CtUu1b3m.js} +11 -143
  28. package/dist/doctor-contract-api.js +5 -5
  29. package/dist/{dynamic-tools-BwpvTxaX.js → dynamic-tools-CmN5RAip.js} +133 -76
  30. package/dist/{effective-mcp-catalog-CY9Jn4bA.js → effective-mcp-catalog-Bd73bqA8.js} +3 -3
  31. package/dist/{elicitation-input-DMkeki8d.js → elicitation-input-DPoK8F7w.js} +8 -22
  32. package/dist/ephemeral-turn-D78_VmzO.js +101 -0
  33. package/dist/{event-projector-assistant-message-B9kp6iGC.js → event-projector-assistant-message-BmBM4qBV.js} +12 -25
  34. package/dist/event-projector-items-5VhsECCO.js +200 -0
  35. package/dist/event-projector-usage-BfXmpOec.js +102 -0
  36. package/dist/{harness-Czh2Sdoc.js → harness-C7rRa7bm.js} +48 -24
  37. package/dist/harness.js +1 -1
  38. package/dist/history-rejection-B4nOXNXF.js +13 -0
  39. package/dist/incognito-session-uhrBF6wJ.js +15 -0
  40. package/dist/index.js +406 -2915
  41. package/dist/inference-context-Dr_mzvk4.js +94 -0
  42. package/dist/inference-proxy-HGXKUIre.js +311 -0
  43. package/dist/{isolated-completion-CRh-51AK.js → isolated-completion-DWVb5U2J.js} +7 -4
  44. package/dist/launch-args-RXQwn8zV.js +90 -0
  45. package/dist/{managed-binary-DcpnJF9x.js → managed-binary-D22rNEcR.js} +13 -103
  46. package/dist/managed-thread-store-D1t5jh3G.js +66 -0
  47. package/dist/media-understanding-provider.js +4 -1
  48. package/dist/migration-provider-api.js +2 -0
  49. package/dist/{model-catalog-DT5vo6qo.js → model-catalog-Dq2n8f_p.js} +6 -5
  50. package/dist/{models-CcrgSMQR.js → models-PCKOim-h.js} +3 -3
  51. package/dist/native-execution-policy-umd0tgh4.js +128 -0
  52. package/dist/native-subagent-history-DjtPloaU.js +140 -0
  53. package/dist/native-subagent-history-owner-Pcp7JuVF.js +34 -0
  54. package/dist/{native-subagent-monitor-B3bvQGcg.js → native-subagent-monitor-fQ7eIXEf.js} +115 -460
  55. package/dist/native-subagent-task-ids-BzTdT0Uw.js +387 -0
  56. package/dist/node-cli-sessions-DKaOmVUh.js +527 -0
  57. package/dist/{node-exec-server.runtime-nfbUOtUB.js → node-exec-server.runtime-Cl2vapEi.js} +55 -24
  58. package/dist/plan-7uG-Fp36.js +947 -0
  59. package/dist/plugin-activation-BYQculil.js +138 -0
  60. package/dist/{thread-resume-BLgqkUc1.js → plugin-app-cache-key-d0eKxy7b.js} +4 -52
  61. package/dist/{plugin-approval-roundtrip-aQVdyL5g.js → plugin-approval-roundtrip-Bz3FT8W5.js} +1 -1
  62. package/dist/plugin-inventory-oL4Na1ZG.js +328 -0
  63. package/dist/plugin-marketplace-discovery-P-Vndfqq.js +137 -0
  64. package/dist/{plugin-metadata-cache-BwCLTY_U.js → plugin-metadata-cache-ClPJpRio.js} +17 -9
  65. package/dist/protocol-5bh1G-H7.js +275 -0
  66. package/dist/provider-MQ8PVkuE.js +50 -0
  67. package/dist/{provider-capabilities-BpG9Ltc5.js → provider-capabilities-BvCUL69A.js} +2 -2
  68. package/dist/{rate-limits-Fx_l4eNa.js → rate-limits-CBMmWBr9.js} +1 -1
  69. package/dist/request-B7hEkBGq.js +212 -0
  70. package/dist/rpc-error-ttN_QjEm.js +30 -0
  71. package/dist/{run-attempt-BzthFQSM.js → run-attempt-CvsAAGa0.js} +664 -377
  72. package/dist/{runtime-artifact-Bh_gf6-t.js → runtime-artifact-BJ0rXBZ_.js} +27 -27
  73. package/dist/sandbox-guard-BxgyoM8M.js +166 -0
  74. package/dist/{session-binding-4Ki04sW-.js → session-binding-CI8UuilT.js} +30 -48
  75. package/dist/{session-binding-record-CyaXZvTe.js → session-binding-record-Bcvslnhf.js} +12 -26
  76. package/dist/session-catalog-adoption-tcZi1IfX.js +251 -0
  77. package/dist/session-catalog-archive-CwKg8Xz2.js +56 -0
  78. package/dist/session-catalog-ct-AH01I.js +1477 -0
  79. package/dist/session-catalog-home-id-CwhLdC03.js +18 -0
  80. package/dist/session-catalog-node-adoption-B1tgDW-m.js +182 -0
  81. package/dist/session-catalog-node-continue-Ci-DXyJP.js +238 -0
  82. package/dist/session-catalog-provenance-D-dIfRAH.js +96 -0
  83. package/dist/{session-cli-BjLhpmS1.js → session-cli-DNN_jhGc.js} +3 -2
  84. package/dist/{session-history-DWmMqiqW.js → session-history-Cz-tOOYj.js} +6 -3
  85. package/dist/{session-upstream-marker-DReTpGz6.js → session-history-import-DwyijFI6.js} +5 -50
  86. package/dist/{session-history-read-LHldwvyh.js → session-history-read-cxPUxyVV.js} +21 -7
  87. package/dist/session-history-worker-runtime.js +18 -6
  88. package/dist/session-history.worker-BeK1YOyT.js +378 -0
  89. package/dist/session-history.worker.js +1 -1
  90. package/dist/{session-initialization-BCFVnLL4.js → session-initialization-Ct0_Hzmg.js} +2 -2
  91. package/dist/{session-permission-policy-BaueHmSj.js → session-permission-policy-BBmXA8Eg.js} +4 -7
  92. package/dist/{session-retirement-DNdmYdFc.js → session-retirement-B2YfbAAT.js} +6 -5
  93. package/dist/session-upstream-marker-D15C9NHp.js +46 -0
  94. package/dist/{settled-turn-context-BOM3Y1pl.js → settled-turn-context-Du6gdUDd.js} +9 -9
  95. package/dist/{settled-turn-finalizer-BI-b1sry.js → settled-turn-finalizer-Dn91stmc.js} +8 -7
  96. package/dist/shared-client-CscigXXL.js +3109 -0
  97. package/dist/{side-question-B6DWAw1A.js → side-question-BGMJQf4U.js} +65 -170
  98. package/dist/source-CElXU0Oy.js +518 -0
  99. package/dist/thread-archive-guard-DfpBr-Sz.js +53 -0
  100. package/dist/thread-history-page-D0JIp48V.js +361 -0
  101. package/dist/{thread-lifecycle-DPK30jad.js → thread-lifecycle-DXl1-I6b.js} +187 -639
  102. package/dist/{thread-ownership-CbucAmmp.js → thread-ownership-BsDRTsyp.js} +13 -15
  103. package/dist/thread-policy-BuEQfE0g.js +54 -0
  104. package/dist/thread-resume-DsDOZpFg.js +52 -0
  105. package/dist/timeout-BVw8aaM1.js +33 -0
  106. package/dist/transcript-history-projection-v17wXgdK.js +238 -0
  107. package/dist/{transcript-mirror-_njEB84z.js → transcript-mirror-C5CKgNy6.js} +50 -260
  108. package/dist/{transcript-mirror-attestation-Byl34PC-.js → transcript-mirror-attestation-DibE0krH.js} +17 -4
  109. package/dist/{transport-stdio-CzTngV0j.js → transport-stdio-BGjHoYLr.js} +73 -43
  110. package/dist/{upstream-session-fork-1fwbNKzQ.js → upstream-session-fork-BZerMte_.js} +27 -19
  111. package/dist/{usage-i9fv5-4m.js → usage-tCk-mg_x.js} +4 -3
  112. package/dist/version-omm6IPI3.js +12 -0
  113. package/dist/{web-search-provider.runtime-DKQn67A7.js → web-search-provider.runtime-B7bGbGWq.js} +3 -3
  114. package/openclaw.plugin.json +23 -1
  115. package/package.json +4 -4
  116. package/dist/request-C8H22rPi.js +0 -475
  117. package/dist/session-catalog-B47uwekb.js +0 -3272
  118. package/dist/session-history.worker-zZVcx0ME.js +0 -267
  119. package/dist/shared-client-CKhX2kFt.js +0 -7505
  120. package/dist/thread-policy-CTalhWFy.js +0 -105
@@ -1,14 +1,16 @@
1
- import { Mt as retainCodexAppServerLiveThread, Ot as isCodexAppServerLiveThreadClaimed, _ as retainSharedCodexAppServerClientByInstanceId, jt as releaseCodexAppServerLiveThread } from "./shared-client-CKhX2kFt.js";
2
- import { a as closeCodexStartupClientBestEffort, d as unsubscribeCodexThreadBestEffort, r as CodexAppServerUnsafeSubscriptionError } from "./attempt-client-cleanup-Bp1ZOnk2.js";
3
- import { resolveGlobalSingleton } from "openclaw/plugin-sdk/global-singleton";
4
- import { isIncognitoSessionKey } from "openclaw/plugin-sdk/routing";
5
- import { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
1
+ import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.js";
2
+ import { n as withCodexAppServerThreadMutation } from "./incognito-session-uhrBF6wJ.js";
3
+ import { J as retainCodexAppServerLiveThread, U as isCodexAppServerLiveThreadClaimed, _ as retainSharedCodexAppServerClientByInstanceId, q as releaseCodexAppServerLiveThread } from "./shared-client-CscigXXL.js";
4
+ import { a as closeCodexStartupClientBestEffort, d as unsubscribeCodexThreadBestEffort, r as CodexAppServerUnsafeSubscriptionError } from "./attempt-client-cleanup-DKHzbwt5.js";
6
5
  //#region extensions/codex/src/app-server/thread-ownership.ts
7
- const nativeThreadOwners = resolveGlobalSingleton(Symbol.for("openclaw.codexNativeThreadOwners"), () => new KeyedAsyncQueue());
8
- /** Serialize OpenClaw-owned lifecycle changes, not native-internal thread controllers. */
9
- async function withCodexAppServerThreadMutation(threadId, run) {
10
- return await nativeThreadOwners.enqueue(`thread:${threadId}`, run);
11
- }
6
+ var thread_ownership_exports = /* @__PURE__ */ __exportAll({
7
+ isSameCodexAppServerThreadOwner: () => isSameCodexAppServerThreadOwner,
8
+ releaseCodexAppServerBindingSubscription: () => releaseCodexAppServerBindingSubscription,
9
+ retainCodexAppServerBindingSubscription: () => retainCodexAppServerBindingSubscription,
10
+ retireCodexConversationThreadBinding: () => retireCodexConversationThreadBinding,
11
+ rollbackCodexAppServerBindingSubscription: () => rollbackCodexAppServerBindingSubscription,
12
+ withExclusiveCodexAppServerThread: () => withExclusiveCodexAppServerThread
13
+ });
12
14
  /** Codex subscriptions belong to a physical connection, not the native thread ID alone. */
13
15
  function isSameCodexAppServerThreadOwner(current, expected) {
14
16
  return current !== void 0 && expected !== void 0 && current.threadId === expected.threadId && current.clientId === expected.clientId;
@@ -20,10 +22,6 @@ async function withExclusiveCodexAppServerThread(params) {
20
22
  return await params.run();
21
23
  });
22
24
  }
23
- /** Serializes bound turns and retirement so detach cannot unsubscribe an active turn. */
24
- async function withCodexConversationThreadActivity(bindingId, run) {
25
- return await nativeThreadOwners.enqueue(`conversation:${bindingId}`, run);
26
- }
27
25
  /** Publishes one owned subscription with its persistent or ephemeral retention lifetime. */
28
26
  async function retainCodexAppServerBindingSubscription(client, threadId, ownership) {
29
27
  return await retainCodexAppServerLiveThread(client, threadId, ownership?.release ?? (async (releasedThreadId, assertCurrent) => {
@@ -100,4 +98,4 @@ async function retireCodexConversationThreadBinding(params) {
100
98
  }));
101
99
  }
102
100
  //#endregion
103
- export { rollbackCodexAppServerBindingSubscription as a, withExclusiveCodexAppServerThread as c, retireCodexConversationThreadBinding as i, isIncognitoSessionKey as l, releaseCodexAppServerBindingSubscription as n, withCodexAppServerThreadMutation as o, retainCodexAppServerBindingSubscription as r, withCodexConversationThreadActivity as s, isSameCodexAppServerThreadOwner as t };
101
+ export { rollbackCodexAppServerBindingSubscription as a, retireCodexConversationThreadBinding as i, releaseCodexAppServerBindingSubscription as n, thread_ownership_exports as o, retainCodexAppServerBindingSubscription as r, withExclusiveCodexAppServerThread as s, isSameCodexAppServerThreadOwner as t };
@@ -0,0 +1,54 @@
1
+ import { l as isCodexAppServerOverloadError, u as isCodexAppServerPrewriteRequestCancellationError } from "./client-B57KWPQx.js";
2
+ import { r as requestCodexAppServerClientJson, t as CodexAppServerScopedRequestRejectedError } from "./request-B7hEkBGq.js";
3
+ import { AgentHarnessPreflightError } from "openclaw/plugin-sdk/agent-harness-runtime";
4
+ //#region extensions/codex/src/app-server/thread-policy.ts
5
+ /** A refusal, not a failed native write: the ephemeral conversation must stay alive. */
6
+ var CodexIncognitoPolicyChangeError = class extends AgentHarnessPreflightError {
7
+ constructor() {
8
+ super("Codex cannot change generic instructions in a live incognito conversation. No turn was sent and the conversation is preserved. Restore the previous instructions to continue it, or start a new incognito conversation for the changed policy.");
9
+ this.name = "CodexIncognitoPolicyChangeError";
10
+ }
11
+ };
12
+ /** Never replay a handoff: native persistence can precede an unsuccessful RPC response. */
13
+ var CodexThreadPolicyHandoffError = class extends AgentHarnessPreflightError {
14
+ constructor(outcome, cause) {
15
+ super(`Codex session policy handoff failed: ${cause instanceof Error ? cause.message : String(cause)}. The conversation is preserved; reconnect before retrying.`, { cause });
16
+ this.outcome = outcome;
17
+ this.name = "CodexThreadPolicyHandoffError";
18
+ }
19
+ };
20
+ /** The complete body remains generic configuration for compaction and native child inheritance. */
21
+ async function refreshCodexThreadPolicy(params) {
22
+ const text = "The following is the complete current OpenClaw-supplied generic instruction policy. It replaces earlier OpenClaw-supplied generic policy, including sections removed from that generic policy. Parent-local instructions supplied for the current inference request are outside this policy replacement. Independently supplied native managed, guardian, security, collaboration, and project instructions retain their authority. User requests retain their own authority.\n\n" + (params.developerInstructions === "" ? "The current OpenClaw generic policy is empty; earlier OpenClaw generic policy is withdrawn." : params.developerInstructions);
23
+ let outcome = "unknown";
24
+ try {
25
+ await requestCodexAppServerClientJson({
26
+ ...params,
27
+ method: "thread/inject_items",
28
+ requestParams: {
29
+ threadId: params.threadId,
30
+ items: [{
31
+ type: "message",
32
+ role: "developer",
33
+ content: [{
34
+ type: "input_text",
35
+ text
36
+ }]
37
+ }]
38
+ }
39
+ });
40
+ outcome = "acknowledged";
41
+ params.assertCurrent();
42
+ params.signal?.throwIfAborted();
43
+ } catch (cause) {
44
+ if (outcome !== "acknowledged" && (cause instanceof CodexAppServerScopedRequestRejectedError || isCodexAppServerPrewriteRequestCancellationError(cause) || isCodexAppServerOverloadError(cause))) outcome = "not-written";
45
+ throw new CodexThreadPolicyHandoffError(outcome, cause);
46
+ }
47
+ }
48
+ /** Native lineage classifies the exact bound thread; it never grants session authority. */
49
+ function assertCodexSupervisionThreadLineage(binding, thread) {
50
+ if (binding.connectionScope !== "supervision" || binding.pendingSupervisionBranch) return;
51
+ if (thread.id !== binding.threadId || !binding.supervisionSourceThreadId || thread.forkedFromId !== null && (typeof thread.forkedFromId !== "string" || !thread.forkedFromId.trim() || thread.forkedFromId === thread.id)) throw new Error("Codex supervision lineage could not be verified; reconnect before continuing.");
52
+ }
53
+ //#endregion
54
+ export { refreshCodexThreadPolicy as i, CodexThreadPolicyHandoffError as n, assertCodexSupervisionThreadLineage as r, CodexIncognitoPolicyChangeError as t };
@@ -0,0 +1,52 @@
1
+ import { l as isCodexAppServerOverloadError, u as isCodexAppServerPrewriteRequestCancellationError, y as assertCodexThreadResumeResponse } from "./client-B57KWPQx.js";
2
+ import { t as CodexAppServerRpcError } from "./rpc-error-ttN_QjEm.js";
3
+ import { t as CodexAppServerScopedRequestRejectedError } from "./request-B7hEkBGq.js";
4
+ import { B as forgetCodexWorkspaceReferences, N as isCodexAppServerStartupError, u as isCodexAppServerStartSelectionChangedError } from "./shared-client-CscigXXL.js";
5
+ import { d as unsubscribeCodexThreadBestEffort, i as assertCodexThreadResumeSubscription, r as CodexAppServerUnsafeSubscriptionError } from "./attempt-client-cleanup-DKHzbwt5.js";
6
+ //#region extensions/codex/src/app-server/thread-resume.ts
7
+ /** Owns Codex thread/resume subscription safety. */
8
+ /** Resumes one thread, releasing or isolating every possible native subscription. */
9
+ async function resumeCodexAppServerThread(params) {
10
+ const threadId = params.request.threadId;
11
+ let response;
12
+ let ownershipRejected = false;
13
+ const assertCurrent = params.assertCurrent && (() => {
14
+ try {
15
+ params.assertCurrent?.();
16
+ } catch (error) {
17
+ ownershipRejected = true;
18
+ throw error;
19
+ }
20
+ });
21
+ try {
22
+ response = assertCodexThreadResumeResponse(await (params.requestResume ? params.requestResume(params.request) : params.client.request("thread/resume", params.request, {
23
+ ...params.timeoutMs !== void 0 ? { timeoutMs: params.timeoutMs } : {},
24
+ ...params.signal ? { signal: params.signal } : {},
25
+ assertCurrent
26
+ })));
27
+ assertCodexThreadResumeSubscription(threadId, response.thread.id);
28
+ forgetCodexWorkspaceReferences(params.client, threadId);
29
+ } catch (error) {
30
+ if (ownershipRejected || isCodexAppServerStartSelectionChangedError(error) || isCodexAppServerStartupError(error) || error instanceof CodexAppServerScopedRequestRejectedError || isCodexAppServerPrewriteRequestCancellationError(error) || isCodexAppServerOverloadError(error)) throw error;
31
+ if (error instanceof CodexAppServerRpcError) {
32
+ if (await unsubscribeCodexThreadBestEffort(params.client, {
33
+ threadId,
34
+ timeoutMs: 5e3,
35
+ assertCurrent: params.assertCurrent
36
+ }).catch(() => false)) {
37
+ params.onSubscriptionReleased?.();
38
+ throw error;
39
+ }
40
+ }
41
+ try {
42
+ await params.abandonClient();
43
+ } catch (abandonError) {
44
+ throw new CodexAppServerUnsafeSubscriptionError(`Codex thread/resume client could not be retired for ${threadId}`, { cause: abandonError });
45
+ }
46
+ if (error instanceof CodexAppServerUnsafeSubscriptionError) throw error;
47
+ throw new CodexAppServerUnsafeSubscriptionError(error instanceof Error ? error.message : `Codex thread/resume outcome is indeterminate for ${threadId}`, { cause: error });
48
+ }
49
+ return response;
50
+ }
51
+ //#endregion
52
+ export { resumeCodexAppServerThread as t };
@@ -0,0 +1,33 @@
1
+ import { withTimeout } from "openclaw/plugin-sdk/time-runtime";
2
+ //#region extensions/codex/src/app-server/timeout.ts
3
+ /**
4
+ * Thin Codex app-server timeout adapter around OpenClaw's shared timeout helper.
5
+ */
6
+ function resolveAbortError(signal) {
7
+ return signal.reason instanceof Error ? signal.reason : new Error("Codex app-server operation aborted", { cause: signal.reason });
8
+ }
9
+ /** Awaits a promise with a Codex-specific timeout error message. */
10
+ async function withTimeout$1(promise, timeoutMs, timeoutMessage, createError) {
11
+ return await withTimeout(promise, timeoutMs, {
12
+ message: timeoutMessage,
13
+ ...createError ? { createError } : {}
14
+ });
15
+ }
16
+ /** Bounds an operation by both its owner lifecycle and one total wall-clock budget. */
17
+ async function withAbortableTimeout(params) {
18
+ const signal = params.signal;
19
+ if (signal?.aborted) throw resolveAbortError(signal);
20
+ let removeAbortListener;
21
+ const operation = signal ? Promise.race([params.promise, new Promise((_, reject) => {
22
+ const onAbort = () => reject(resolveAbortError(signal));
23
+ signal.addEventListener("abort", onAbort, { once: true });
24
+ removeAbortListener = () => signal.removeEventListener("abort", onAbort);
25
+ })]) : params.promise;
26
+ try {
27
+ return await withTimeout$1(operation, params.timeoutMs, params.timeoutMessage, params.createTimeoutError);
28
+ } finally {
29
+ removeAbortListener?.();
30
+ }
31
+ }
32
+ //#endregion
33
+ export { withTimeout$1 as n, withAbortableTimeout as t };
@@ -0,0 +1,238 @@
1
+ import { c as itemName, l as itemStatus, t as auditNativeToolName } from "./event-projector-items-5VhsECCO.js";
2
+ import { t as attachCodexMirrorIdentity } from "./upstream-prompt-provenance-LphB8slG.js";
3
+ import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
4
+ import { truncateUtf8Prefix } from "openclaw/plugin-sdk/text-utility-runtime";
5
+ import { Buffer } from "node:buffer";
6
+ //#region extensions/codex/src/app-server/transcript-history-projection.ts
7
+ const CODEX_HISTORY_IMPORT_MAX_MESSAGES = 200;
8
+ const CODEX_HISTORY_IMPORT_MAX_BYTES = 524288;
9
+ const CODEX_HISTORY_IMPORT_MAX_MESSAGE_BYTES = 65536;
10
+ const CODEX_HISTORY_TRUNCATION_SUFFIX = "\n\n[Message truncated during Codex history import.]";
11
+ const CODEX_HISTORY_ASSISTANT_API = "openai-chatgpt-responses";
12
+ const CODEX_HISTORY_ASSISTANT_PROVIDER = "openai";
13
+ const CODEX_HISTORY_ASSISTANT_MODEL = "native-history";
14
+ const CODEX_HISTORY_ZERO_USAGE = {
15
+ input: 0,
16
+ output: 0,
17
+ cacheRead: 0,
18
+ cacheWrite: 0,
19
+ totalTokens: 0,
20
+ cost: {
21
+ input: 0,
22
+ output: 0,
23
+ cacheRead: 0,
24
+ cacheWrite: 0,
25
+ total: 0
26
+ }
27
+ };
28
+ function normalizeImportedHistoryText(value) {
29
+ if (typeof value !== "string") return;
30
+ const text = value.trim();
31
+ if (!text) return;
32
+ if (Buffer.byteLength(text, "utf8") <= CODEX_HISTORY_IMPORT_MAX_MESSAGE_BYTES) return text;
33
+ const suffixBytes = Buffer.byteLength(CODEX_HISTORY_TRUNCATION_SUFFIX, "utf8");
34
+ const contentLimitBytes = Math.max(0, CODEX_HISTORY_IMPORT_MAX_MESSAGE_BYTES - suffixBytes);
35
+ return `${truncateUtf8Prefix(text, contentLimitBytes)}${CODEX_HISTORY_TRUNCATION_SUFFIX}`;
36
+ }
37
+ function projectCodexUserItemText(item) {
38
+ if (!Array.isArray(item.content)) return;
39
+ const parts = [];
40
+ for (const value of item.content) {
41
+ if (!value || typeof value !== "object" || Array.isArray(value)) continue;
42
+ const input = value;
43
+ if (input.type === "text") {
44
+ const text = normalizeImportedHistoryText(input.text);
45
+ if (text) parts.push(text);
46
+ continue;
47
+ }
48
+ if (input.type === "image" || input.type === "localImage") {
49
+ parts.push("[Image attachment]");
50
+ continue;
51
+ }
52
+ if (input.type === "audio" || input.type === "localAudio" || input.type === "local_audio") parts.push("[Audio attachment]");
53
+ if (input.type === "skill" || input.type === "mention") {
54
+ const name = normalizeOptionalString(input.name);
55
+ if (name) parts.push(`${input.type === "skill" ? "$" : "@"}${name}`);
56
+ }
57
+ }
58
+ return normalizeImportedHistoryText(parts.join("\n"));
59
+ }
60
+ function selectTurnsThroughBoundary(thread, throughTurnId) {
61
+ if (throughTurnId === null) return [];
62
+ const turns = thread.turns ?? [];
63
+ const boundaryIndex = turns.findIndex((turn) => turn.id === throughTurnId);
64
+ if (boundaryIndex < 0) throw new Error(`Codex history boundary turn not found: ${throughTurnId}`);
65
+ const boundary = turns[boundaryIndex];
66
+ if (boundary?.status !== "completed" && boundary?.status !== "interrupted" && boundary?.status !== "failed") throw new Error(`Codex history boundary turn is not terminal: ${throughTurnId}`);
67
+ return turns.slice(0, boundaryIndex + 1);
68
+ }
69
+ function projectCodexThreadHistory(params) {
70
+ const projected = [];
71
+ const threadTimestamp = typeof params.thread.createdAt === "number" && Number.isFinite(params.thread.createdAt) ? params.thread.createdAt * 1e3 : params.importedAt;
72
+ let itemOffset = 0;
73
+ for (const turn of params.turns) for (const value of turn.items) {
74
+ const item = value;
75
+ const itemId = normalizeOptionalString(item.id);
76
+ const identity = `${turn.id}:${itemId ?? itemOffset}`;
77
+ const timestampSeconds = item.type === "agentMessage" ? turn.completedAt ?? turn.startedAt : turn.startedAt ?? turn.completedAt;
78
+ const timestamp = typeof timestampSeconds === "number" && Number.isFinite(timestampSeconds) ? timestampSeconds * 1e3 + itemOffset : threadTimestamp + itemOffset;
79
+ const text = item.type === "userMessage" ? projectCodexUserItemText(item) : item.type === "agentMessage" ? normalizeImportedHistoryText(item.text) : void 0;
80
+ const role = item.type === "userMessage" ? "user" : item.type === "agentMessage" ? "assistant" : void 0;
81
+ itemOffset += 1;
82
+ if (!text || !role) continue;
83
+ const phase = item.phase === "commentary" || item.phase === "final_answer" ? item.phase : void 0;
84
+ const asyncDelivery = item.delivery === "async";
85
+ const message = role === "assistant" ? attachCodexMirrorIdentity({
86
+ role,
87
+ content: [{
88
+ type: "text",
89
+ text
90
+ }],
91
+ api: CODEX_HISTORY_ASSISTANT_API,
92
+ provider: normalizeOptionalString(params.modelProvider) ?? normalizeOptionalString(params.thread.modelProvider) ?? CODEX_HISTORY_ASSISTANT_PROVIDER,
93
+ model: CODEX_HISTORY_ASSISTANT_MODEL,
94
+ usage: CODEX_HISTORY_ZERO_USAGE,
95
+ stopReason: turn.status === "interrupted" ? "aborted" : turn.status === "failed" ? "error" : "stop",
96
+ ...turn.status === "failed" && turn.error?.message ? { errorMessage: turn.error.message } : {},
97
+ ...phase ? { phase } : {},
98
+ ...asyncDelivery && itemId ? { openclawAsyncDelivery: { itemId } } : {},
99
+ timestamp
100
+ }, identity) : attachCodexMirrorIdentity({
101
+ role,
102
+ content: text,
103
+ timestamp
104
+ }, identity);
105
+ projected.push({
106
+ message,
107
+ responseItem: {
108
+ type: "message",
109
+ role,
110
+ content: [{
111
+ type: role === "assistant" ? "output_text" : "input_text",
112
+ text
113
+ }],
114
+ ...role === "assistant" && phase ? { phase } : {}
115
+ },
116
+ textBytes: Buffer.byteLength(text, "utf8")
117
+ });
118
+ }
119
+ return projected;
120
+ }
121
+ function selectBoundedCodexHistoryTail(projected) {
122
+ const selected = [];
123
+ let selectedBytes = 0;
124
+ for (let index = projected.length - 1; index >= 0; index -= 1) {
125
+ const candidate = projected[index];
126
+ if (!candidate) continue;
127
+ if (selected.length >= CODEX_HISTORY_IMPORT_MAX_MESSAGES || selectedBytes + candidate.textBytes > CODEX_HISTORY_IMPORT_MAX_BYTES) break;
128
+ selected.push(candidate);
129
+ selectedBytes += candidate.textBytes;
130
+ }
131
+ return selected.toReversed();
132
+ }
133
+ /** Projects one terminal Codex history prefix into transcript and Responses API items. */
134
+ function projectBoundedCodexThreadHistory(params) {
135
+ const projected = projectCodexThreadHistory({
136
+ thread: params.thread,
137
+ turns: selectTurnsThroughBoundary(params.thread, params.throughTurnId),
138
+ importedAt: params.importedAt,
139
+ ...params.modelProvider ? { modelProvider: params.modelProvider } : {}
140
+ });
141
+ const selected = selectBoundedCodexHistoryTail(projected);
142
+ return {
143
+ importedMessages: selected.length,
144
+ omittedMessages: projected.length - selected.length,
145
+ responseItems: selected.filter(({ message }) => message.role !== "assistant" || message.stopReason !== "aborted" && message.stopReason !== "error" && !("openclawAsyncDelivery" in message)).map(({ responseItem }) => responseItem),
146
+ transcriptMessages: selected.map(({ message }) => message)
147
+ };
148
+ }
149
+ /** Projects only visible local user/assistant messages through the same bounded history policy. */
150
+ function projectBoundedCodexVisibleSessionHistory(entries) {
151
+ const projected = [];
152
+ for (const entry of entries) {
153
+ if (entry.role !== "user" && entry.role !== "assistant" || !("content" in entry.message)) continue;
154
+ if (entry.role === "assistant" && ("stopReason" in entry.message && (entry.message.stopReason === "aborted" || entry.message.stopReason === "error") || "openclawAsyncDelivery" in entry.message)) continue;
155
+ const content = entry.message.content;
156
+ const text = normalizeImportedHistoryText(typeof content === "string" ? content : Array.isArray(content) ? content.flatMap((part) => part && typeof part === "object" && "text" in part && typeof part.text === "string" ? [part.text] : []).join("\n") : void 0);
157
+ if (!text) continue;
158
+ projected.push({
159
+ message: entry.message,
160
+ responseItem: {
161
+ type: "message",
162
+ role: entry.role,
163
+ content: [{
164
+ type: entry.role === "assistant" ? "output_text" : "input_text",
165
+ text
166
+ }]
167
+ },
168
+ textBytes: Buffer.byteLength(text, "utf8")
169
+ });
170
+ }
171
+ return selectBoundedCodexHistoryTail(projected).map(({ responseItem }) => responseItem);
172
+ }
173
+ /** Displays native items through the shared transcript roles, including an unfinished turn. */
174
+ function projectCodexThreadHistoryItem(thread, entry, toolItems) {
175
+ const { item } = entry;
176
+ const timestamp = (entry.turn?.startedAt ?? thread.createdAt ?? 0) * 1e3;
177
+ if (item.type === "userMessage" || item.type === "agentMessage") return projectCodexThreadHistory({
178
+ thread,
179
+ turns: [{
180
+ ...entry.turn,
181
+ id: entry.turnId,
182
+ items: [item]
183
+ }],
184
+ importedAt: timestamp
185
+ }).map(({ message }) => message);
186
+ const identity = `${entry.turnId}:${item.id}`;
187
+ const assistant = (content, toolUse = false) => attachCodexMirrorIdentity({
188
+ role: "assistant",
189
+ content,
190
+ api: CODEX_HISTORY_ASSISTANT_API,
191
+ provider: normalizeOptionalString(thread.modelProvider) ?? CODEX_HISTORY_ASSISTANT_PROVIDER,
192
+ model: CODEX_HISTORY_ASSISTANT_MODEL,
193
+ usage: CODEX_HISTORY_ZERO_USAGE,
194
+ stopReason: toolUse ? "toolUse" : "stop",
195
+ timestamp
196
+ }, identity);
197
+ if (item.type === "reasoning") {
198
+ const parts = Array.isArray(item.summary) && item.summary.length > 0 ? item.summary : item.content;
199
+ const thinking = normalizeImportedHistoryText(Array.isArray(parts) ? parts.filter((part) => typeof part === "string").join("\n") : item.text);
200
+ return thinking ? [assistant([{
201
+ type: "thinking",
202
+ thinking
203
+ }])] : [];
204
+ }
205
+ if (item.type === "contextCompaction") return [assistant([{
206
+ type: "text",
207
+ text: "Context compacted."
208
+ }])];
209
+ const toolName = itemName(item) ?? auditNativeToolName(item);
210
+ if (!toolName) {
211
+ const text = normalizeImportedHistoryText(item.text ?? item.title);
212
+ return text ? [assistant([{
213
+ type: "text",
214
+ text
215
+ }])] : [];
216
+ }
217
+ const messages = [assistant([{
218
+ type: "toolCall",
219
+ id: item.id,
220
+ name: toolName,
221
+ arguments: toolItems.itemToolArgs(item) ?? {}
222
+ }], true)];
223
+ const status = itemStatus(item);
224
+ if (status !== "running") messages.push(attachCodexMirrorIdentity({
225
+ role: "toolResult",
226
+ toolCallId: item.id,
227
+ toolName,
228
+ content: [{
229
+ type: "text",
230
+ text: toolItems.itemTranscriptResultText(item) ?? status
231
+ }],
232
+ isError: status === "failed" || status === "blocked",
233
+ timestamp
234
+ }, `${identity}:result`));
235
+ return messages;
236
+ }
237
+ //#endregion
238
+ export { projectCodexUserItemText as i, projectBoundedCodexVisibleSessionHistory as n, projectCodexThreadHistoryItem as r, projectBoundedCodexThreadHistory as t };