@openclaw/codex 2026.9.8 → 2026.10.1-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 (151) hide show
  1. package/README.md +8 -0
  2. package/dist/.setup/{account-usage-runtime-G348lY1q.mjs → account-usage-runtime-DGqFpAud.mjs} +5 -5
  3. package/dist/.setup/app-server-policy-Bg4FZw1f.mjs +23 -0
  4. package/dist/.setup/{apply-Cqb-YoCS.mjs → apply-CXTudl9p.mjs} +48 -39
  5. package/dist/.setup/attempt-client-cleanup-BH0hW2xU.mjs +155 -0
  6. package/dist/.setup/{attempt-workspace-context-BJ5Z_olH.mjs → attempt-workspace-context-BY0jprWJ.mjs} +11 -15
  7. package/dist/.setup/{auth-binding-BLWz7stm.mjs → auth-binding-BoMwpuPN.mjs} +17 -25
  8. package/dist/.setup/{auth-cache-key-Dnps4W4_.mjs → auth-cache-key-CGm0UJOr.mjs} +244 -82
  9. package/dist/.setup/{auth-profile-B0okYl2D.mjs → auth-profile-CgHQ8Vot.mjs} +2 -1
  10. package/dist/.setup/{auth-profile-selection-DFu9e167.mjs → auth-profile-selection-hr8ocLtz.mjs} +5 -7
  11. package/dist/.setup/{binding-connection-DTtN1KrX.mjs → binding-connection-C-08ez1w.mjs} +2 -2
  12. package/dist/.setup/{binding-connection.runtime-6TpgD1M6.mjs → binding-connection.runtime-Dn2p-fdy.mjs} +3 -3
  13. package/dist/.setup/{bounded-turn-isolation-B8K_ylqk.mjs → bounded-turn-isolation-DklXNk3k.mjs} +4 -4
  14. package/dist/.setup/{bounded-turn-BNunZPtz.mjs → bounded-turn-pGsfXcmH.mjs} +14 -13
  15. package/dist/.setup/{build-state-DIQ5O_-S.mjs → build-state-CqQnsg7T.mjs} +1 -1
  16. package/dist/.setup/{capabilities-B3WEZl4e.mjs → capabilities-kQntafj_.mjs} +1 -1
  17. package/dist/.setup/{client-qyUBJlGZ.mjs → client-C8lgBOoO.mjs} +438 -160
  18. package/dist/.setup/{client-catalog-response-DRvx_wCC.mjs → client-catalog-response-Bqp7WG51.mjs} +57 -25
  19. package/dist/.setup/command-authorization-AikPDtcc.mjs +15 -0
  20. package/dist/.setup/{command-dispatch-Btrs1D6f.mjs → command-dispatch-DhBbFIQ5.mjs} +3 -3
  21. package/dist/.setup/{command-formatters-R3ckE3Co.mjs → command-formatters-DV3DHhdr.mjs} +7 -5
  22. package/dist/.setup/{command-handlers-DvlCHJch.mjs → command-handlers-ztOOzm6O.mjs} +82 -144
  23. package/dist/.setup/{command-rpc-skzRq4wD.mjs → command-rpc-CuC5fPom.mjs} +23 -31
  24. package/dist/.setup/{compact-8ttks5U5.mjs → compact-tUb9AYfH.mjs} +117 -65
  25. package/dist/.setup/{plugin-metadata-cache-BRwtRct9.mjs → computer-use-BBN9y326.mjs} +65 -202
  26. package/dist/.setup/{config-DKhXquav.mjs → config-0Gxk3_eq.mjs} +5 -6
  27. package/dist/.setup/{config-options-CzyWLTJt.mjs → config-options-HG_Rr3W_.mjs} +13 -23
  28. package/dist/.setup/{config-parsing-b088LyhT.mjs → config-parsing-BQq-CHTF.mjs} +41 -4
  29. package/dist/.setup/{config-runtime-C0NbLms1.mjs → config-runtime-cUYrqu_a.mjs} +2 -2
  30. package/dist/.setup/{config-security-CE-FcGw9.mjs → config-security-KAPScztc.mjs} +20 -36
  31. package/dist/.setup/{context-engine-projection-PezSESth.mjs → context-engine-projection-CsgYSQhW.mjs} +11 -14
  32. package/dist/.setup/{conversation-binding-74LaGGH-.mjs → conversation-binding-B3MNMVzb.mjs} +36 -48
  33. package/dist/.setup/{conversation-binding-data-C746z5Pn.mjs → conversation-binding-data-DJ4ix-W5.mjs} +1 -1
  34. package/dist/.setup/{conversation-control-OrN6zuaY.mjs → conversation-control-CYsMlCuE.mjs} +19 -21
  35. package/dist/.setup/{cyber-failover-XV0nNRZu.mjs → cyber-failover-Bb1J6hS1.mjs} +1 -1
  36. package/dist/.setup/{cyber-failover-notice-RNpGpTyP.mjs → cyber-failover-notice-XR03ef31.mjs} +1 -1
  37. package/dist/.setup/doctor-start-options-DPW9JxIE.mjs +63 -0
  38. package/dist/.setup/dynamic-tool-build-C8xGEXmR.mjs +463 -0
  39. package/dist/.setup/{dynamic-tools-Db2sY5cZ.mjs → dynamic-tools-DyERJnR6.mjs} +238 -878
  40. package/dist/.setup/{effective-mcp-catalog-Bi6-SQ7i.mjs → effective-mcp-catalog-C26Mio5l.mjs} +83 -11
  41. package/dist/.setup/{elicitation-input-DPoK8F7w.mjs → elicitation-input-r9axtppm.mjs} +4 -2
  42. package/dist/.setup/{ephemeral-turn-DiCS1ijR.mjs → ephemeral-turn-D8VcDTNo.mjs} +2 -2
  43. package/dist/.setup/{event-projector-assistant-message-MV_1dj-3.mjs → event-projector-assistant-message-BN7CNUB5.mjs} +2 -2
  44. package/dist/.setup/{event-projector-values-DJSz8BTk.mjs → event-projector-values-DTqZHizf.mjs} +2 -12
  45. package/dist/.setup/{inference-dispatch-CMZtjQyz.mjs → inference-dispatch-B5UKEUyC.mjs} +12 -21
  46. package/dist/.setup/{inference-proxy-DhcXOgUE.mjs → inference-proxy-DUO5E2QQ.mjs} +6 -5
  47. package/dist/.setup/{isolated-completion-D80IXfQF.mjs → isolated-completion-C0jrcplS.mjs} +8 -8
  48. package/dist/.setup/{managed-binary-kiWRhNRE.mjs → managed-binary-C1VFoVPf.mjs} +31 -38
  49. package/dist/.setup/mcp-app-session-preparation-BxN0_CYe.mjs +223 -0
  50. package/dist/.setup/mcp-tool-metadata-j10HhfTC.mjs +43 -0
  51. package/dist/.setup/{model-catalog-DiC0Tkha.mjs → model-catalog-DZyNeDKG.mjs} +7 -7
  52. package/dist/.setup/{models-DfLmPV0k.mjs → models-DSseKSMg.mjs} +10 -7
  53. package/dist/.setup/{native-auth-CuG53tu4.mjs → native-auth-Cjb9y7IZ.mjs} +5 -6
  54. package/dist/.setup/{native-execution-policy-BxZJy5mP.mjs → native-execution-policy-ClzpdG3D.mjs} +1 -12
  55. package/dist/.setup/native-mcp-app-CqcPVmhH.mjs +310 -0
  56. package/dist/.setup/{native-subagent-monitor-BwkQXf9e.mjs → native-subagent-monitor-BUYOUp9X.mjs} +235 -318
  57. package/dist/.setup/{native-subagent-pending-assignments-DwkCzLvD.mjs → native-subagent-pending-assignments-BDqhOdJp.mjs} +0 -4
  58. package/dist/.setup/{native-task-assignments-DMQ0g3hu.mjs → native-task-assignments-C6KVqiN1.mjs} +9 -8
  59. package/dist/.setup/{node-cli-sessions-HC4W6FLI.mjs → node-cli-sessions-B5oNDkUS.mjs} +11 -17
  60. package/dist/.setup/{node-exec-server.runtime-BgBfWQqo.mjs → node-exec-server.runtime-0xSEjKYt.mjs} +2 -2
  61. package/dist/.setup/{plan-DPdMk1Oy.mjs → plan-BJ37d2Og.mjs} +67 -89
  62. package/dist/.setup/{plugin-activation-cNHRfaxU.mjs → plugin-activation-BcyBv8PG.mjs} +4 -4
  63. package/dist/.setup/{plugin-app-cache-key-BL9B5H0L.mjs → plugin-app-cache-key-BW8rd98k.mjs} +11 -15
  64. package/dist/.setup/plugin-approval-roundtrip-CuahdPLC.mjs +109 -0
  65. package/dist/.setup/{plugin-inventory-Cky2XJUw.mjs → plugin-inventory-Bf0_piTw.mjs} +29 -51
  66. package/dist/.setup/{plugin-marketplace-discovery-D_dV9FXa.mjs → plugin-marketplace-discovery-SQPhSuic.mjs} +2 -16
  67. package/dist/.setup/plugin-metadata-cache-DWnB7VMj.mjs +84 -0
  68. package/dist/.setup/plugin-thread-config-deadline-B8LGaZNW.mjs +124 -0
  69. package/dist/.setup/{provider-D6F_7p1I.mjs → provider-BnwHVD_z.mjs} +4 -4
  70. package/dist/.setup/provider-capabilities-D68Whix6.mjs +50 -0
  71. package/dist/.setup/{rate-limits-B7-X2TgG.mjs → rate-limits-CMPy24F5.mjs} +1 -5
  72. package/dist/.setup/{request-BZOfsSXW.mjs → request-jSbhc1sg.mjs} +189 -49
  73. package/dist/.setup/rpc-error-hmWM21RB.mjs +57 -0
  74. package/dist/.setup/{run-attempt-dYJhjZrp.mjs → run-attempt-BLDZeYLD.mjs} +553 -727
  75. package/dist/.setup/{run-attempt-lifecycle-C-6O3Exn.mjs → run-attempt-lifecycle-BuZgVbDA.mjs} +19 -3
  76. package/dist/.setup/{runtime-artifact-DDQ-HGXf.mjs → runtime-artifact-CUTOOnKw.mjs} +5 -6
  77. package/dist/.setup/{runtime-artifact-connection-D68qQn1m.mjs → runtime-artifact-connection-CADz3_BY.mjs} +5 -4
  78. package/dist/.setup/{sandbox-guard-DjCz2eOw.mjs → sandbox-guard-WqE8yPge.mjs} +3 -3
  79. package/dist/.setup/service-tier-normalization-Cei89SW6.mjs +15 -0
  80. package/dist/.setup/{session-binding-DGCYAfvD.mjs → session-binding-Ce7BqiPN.mjs} +92 -102
  81. package/dist/.setup/session-binding-meta-Lkm5Lpf4.mjs +15 -0
  82. package/dist/.setup/session-binding-record-BZB8RgcF.mjs +179 -0
  83. package/dist/.setup/session-binding-record-codec-z4ZpDn6E.mjs +216 -0
  84. package/dist/.setup/{session-binding-sidecars-jo6H8dFr.mjs → session-binding-sidecars-BrdV95Fg.mjs} +8 -2
  85. package/dist/.setup/{session-catalog-adoption-BU_pHWG7.mjs → session-catalog-adoption-CPIP4S_y.mjs} +34 -18
  86. package/dist/.setup/{session-catalog-archive-spHfihri.mjs → session-catalog-archive-DcgwvSbF.mjs} +24 -29
  87. package/dist/.setup/{session-catalog-events-BMCFMZw-.mjs → session-catalog-events-Bdjw9HEn.mjs} +5 -5
  88. package/dist/.setup/{session-catalog-index-DwJjnF5k.mjs → session-catalog-index-DufISKJ6.mjs} +361 -72
  89. package/dist/.setup/{session-catalog-index-order-BcQpHks3.mjs → session-catalog-index-order-nhyO0wdW.mjs} +1 -1
  90. package/dist/.setup/{session-catalog-limits-DDxOsQeC.mjs → session-catalog-limits-DEU36Qlo.mjs} +1 -1
  91. package/dist/.setup/{session-catalog-index-state-TeO7EyO-.mjs → session-catalog-list-request-tXephOB4.mjs} +180 -6
  92. package/dist/.setup/{session-catalog-native-projection-CuaFZuQE.mjs → session-catalog-native-projection-D6IiLtMb.mjs} +7 -6
  93. package/dist/.setup/{session-catalog-node-adoption-DgXvSGu0.mjs → session-catalog-node-adoption-7-WEQTB1.mjs} +12 -2
  94. package/dist/.setup/{session-catalog-node-continue-DjKXHBbi.mjs → session-catalog-node-continue-DLWBwAAO.mjs} +11 -15
  95. package/dist/.setup/{session-catalog-node-lookup-CtAXI5W5.mjs → session-catalog-node-lookup-Uufckwcm.mjs} +2 -2
  96. package/dist/.setup/{session-catalog-parsing-CPGaPYr-.mjs → session-catalog-parsing-B-qWJh2x.mjs} +70 -28
  97. package/dist/.setup/{session-catalog-projection-CGfzfP93.mjs → session-catalog-projection-8aHNwzWD.mjs} +6 -122
  98. package/dist/.setup/{session-catalog-provenance-DoAvktcj.mjs → session-catalog-provenance-CmsOE5mh.mjs} +6 -1
  99. package/dist/.setup/{session-cli-DlmBHYIe.mjs → session-cli-kH4vuGod.mjs} +1 -2
  100. package/dist/.setup/{session-history-D83lJWHG.mjs → session-history-BogBHKLk.mjs} +1 -1
  101. package/dist/.setup/{session-history-import-WhX-X33a.mjs → session-history-import-NWKPa4ZO.mjs} +4 -4
  102. package/dist/.setup/{session-history-read-Ov3StuL4.mjs → session-history-read-CNN8zwbD.mjs} +8 -19
  103. package/dist/.setup/{session-history.worker-MnPKncqP.mjs → session-history.worker-Cq_4DYgN.mjs} +3 -3
  104. package/dist/.setup/{session-initialization-6aveB9qb.mjs → session-initialization-D6dtFQkE.mjs} +2 -2
  105. package/dist/.setup/{session-permission-policy-Ci_fVX6y.mjs → session-permission-policy-BxIUJ0Zd.mjs} +8 -37
  106. package/dist/.setup/{session-retirement-LlYWBKTJ.mjs → session-retirement-Czbchv_O.mjs} +14 -15
  107. package/dist/.setup/{settled-turn-context-D4yj4rxf.mjs → settled-turn-context-BZsMjkIO.mjs} +13 -6
  108. package/dist/.setup/{settled-turn-finalizer-DW9W3gza.mjs → settled-turn-finalizer-DjZsIwbZ.mjs} +8 -8
  109. package/dist/.setup/{shared-client-CJCTeFpQ.mjs → shared-client-qhyYWbew.mjs} +291 -272
  110. package/dist/.setup/{provider-capabilities-DG5qbsUZ.mjs → shell-dynamic-tools-D3Brj3g9.mjs} +16 -55
  111. package/dist/.setup/{side-question-BLeGj7TQ.mjs → side-question-D3NJlgbl.mjs} +99 -91
  112. package/dist/.setup/{source-CJis_1EF.mjs → source-BYu0T780.mjs} +24 -40
  113. package/dist/.setup/{thread-lifecycle-_bAbjedG.mjs → thread-lifecycle-Cbz_7ySv.mjs} +262 -305
  114. package/dist/.setup/{thread-ownership-B6pPt21M.mjs → thread-ownership-DwuSrt3s.mjs} +10 -8
  115. package/dist/.setup/{thread-policy-gNPzzpVp.mjs → thread-policy-DoNxbhqt.mjs} +22 -21
  116. package/dist/.setup/{thread-requests-OWGOiDaV.mjs → thread-requests-CL1e8Wmx.mjs} +107 -98
  117. package/dist/.setup/{thread-resume-GOry0AYh.mjs → thread-resume-BT6NHMkM.mjs} +10 -18
  118. package/dist/.setup/{transcript-history-projection-DRSifI-1.mjs → transcript-history-projection-B9a7HwUV.mjs} +11 -16
  119. package/dist/.setup/{transcript-mirror-kxmCYsuF.mjs → transcript-mirror-BfLRARNL.mjs} +64 -67
  120. package/dist/.setup/{transport-stdio-Bdegpn2V.mjs → transport-stdio-a0HDa2Mj.mjs} +27 -8
  121. package/dist/.setup/{transport-websocket-BTBE-LD9.mjs → transport-websocket-zqJ0Cmtn.mjs} +3 -8
  122. package/dist/.setup/{attempt-client-cleanup-B-S7ngS_.mjs → turn-router-sS69wYnI.mjs} +75 -170
  123. package/dist/.setup/{upstream-session-fork-gkdRj2yH.mjs → upstream-session-fork-ChSld66u.mjs} +35 -46
  124. package/dist/.setup/{usage-CApUvLOV.mjs → usage-D8e8Xiqf.mjs} +4 -4
  125. package/dist/.setup/{usage-limit-error-wSMQkbpV.mjs → usage-limit-error-GbT-5NcW.mjs} +4 -4
  126. package/dist/.setup/{web-search-provider.runtime-UKgeiBUG.mjs → web-search-provider.runtime-dL2GD1Kl.mjs} +4 -20
  127. package/dist/.setup/websocket-data-XlRvt8Ys.mjs +6 -0
  128. package/dist/.setup/workspace-write-sandbox-probe-DmUHLrrl.mjs +118 -0
  129. package/dist/api.js +34 -54
  130. package/dist/catalog-page.worker.js +1 -1
  131. package/dist/cli-metadata.js +1 -1
  132. package/dist/doctor-contract-api.js +15 -27
  133. package/dist/harness.js +37 -22
  134. package/dist/index.js +2880 -276
  135. package/dist/media-understanding-provider.js +2 -2
  136. package/dist/migration-provider-api.js +1 -1
  137. package/dist/native-session-binding-api.js +2 -0
  138. package/dist/provider-discovery.js +1 -1
  139. package/dist/session-history-worker-runtime.js +33 -4
  140. package/dist/session-history.worker.js +1 -1
  141. package/openclaw.plugin.json +3 -3
  142. package/package.json +6 -6
  143. package/dist/.setup/config-utils-D0CXecki.mjs +0 -57
  144. package/dist/.setup/incognito-session-DWYapfwf.mjs +0 -2
  145. package/dist/.setup/managed-thread-store-BMqgThVL.mjs +0 -100
  146. package/dist/.setup/rpc-error-BlD2vuzn.mjs +0 -31
  147. package/dist/.setup/session-binding-meta-B7aEMU7g.mjs +0 -6
  148. package/dist/.setup/session-binding-record-Oe9L-CNY.mjs +0 -375
  149. package/dist/.setup/session-catalog-BFafIiF6.mjs +0 -2599
  150. package/dist/.setup/session-catalog-list-request-CvtxrYSe.mjs +0 -170
  151. package/dist/.setup/shared-client-lifecycle-7xgtlo15.mjs +0 -153
@@ -1,2599 +0,0 @@
1
- import { A as unwrapNodeInvokePayload, C as readGatewayParams, E as requireOnlyKeys, S as readControlCursor, _ as normalizeLimit, a as CODEX_LOCAL_SESSION_HOST_ID, b as parseTranscriptPage, f as catalogError, g as isInteractiveThreadSource, h as filterCatalogPageByTitle, i as CODEX_CATALOG_TRANSCRIPT_READ_COMMAND, l as MAX_TRANSCRIPT_PAGE_BYTES, n as CODEX_APP_SERVER_THREADS_LIST_COMMAND, o as CatalogParamsError, r as CODEX_APP_SERVER_THREAD_TURNS_LIST_COMMAND, s as MAX_CURSOR_LENGTH, t as CODEX_APP_SERVER_THREADS_CAPABILITY, u as NODE_INVOKE_TIMEOUT_MS, v as parseCatalogPage, w as readPageParams, x as readBoundedOptionalString, y as parseJsonParams } from "./session-catalog-parsing-CPGaPYr-.mjs";
2
- import { n as assertCodexThreadForkParams } from "./protocol-CANUwXJ3.mjs";
3
- import { v as sessionBindingIdentity } from "./session-binding-record-Oe9L-CNY.mjs";
4
- import { d as readCodexPluginConfig } from "./config-parsing-b088LyhT.mjs";
5
- import { n as resolveCodexAppServerLocalHomeDir, r as resolveCodexAppServerUserHomeDir, t as resolveCodexAppServerHomeDir } from "./auth-start-options-BPIPeEX8.mjs";
6
- import { i as hasActiveSharedCodexAppServerWork, r as getSharedCodexAppServerClientState } from "./shared-client-lifecycle-7xgtlo15.mjs";
7
- import { n as CodexAppServerRpcError, r as isCodexThreadReadMissingError } from "./rpc-error-BlD2vuzn.mjs";
8
- import { t as CODEX_CONTROL_METHODS } from "./capabilities-B3WEZl4e.mjs";
9
- import { n as codexCatalogHomeIdFromCanonicalPath } from "./session-catalog-home-id-vlih0B_g.mjs";
10
- import { i as withTimeout } from "./timeout-CXOfNoaX.mjs";
11
- import { a as CodexCatalogLoadingError, n as currentCodexCatalogListRequest, r as withCodexCatalogListRequest, t as CodexCatalogListRequest } from "./session-catalog-list-request-CvtxrYSe.mjs";
12
- import { t as lookupNodeCodexCatalogRecord } from "./session-catalog-node-lookup-CtAXI5W5.mjs";
13
- import { r as projectCodexUserItemText } from "./transcript-history-projection-DRSifI-1.mjs";
14
- import { r as codexUpstreamContinueResult } from "./session-upstream-marker-D15C9NHp.mjs";
15
- import { t as buildCodexAppServerConnectionFingerprint } from "./plugin-app-cache-key-BL9B5H0L.mjs";
16
- import { n as readCodexSessionMeta } from "./session-catalog-provenance-DoAvktcj.mjs";
17
- import { t as codexCatalogResidentHomeKey } from "./session-catalog-events-BMCFMZw-.mjs";
18
- import { a as setCodexCatalogConnectionHomeResolver } from "./binding-connection-DTtN1KrX.mjs";
19
- import { n as findCodexAppServerSpawnError } from "./spawn-error-CL3n6MAa.mjs";
20
- import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
21
- import { randomUUID } from "node:crypto";
22
- import { resolveDefaultAgentDir } from "openclaw/plugin-sdk/agent-harness-registration";
23
- import { listAgentIds, resolveAgentDir, resolveDefaultAgentId, resolveSessionAgentIdsStrict } from "openclaw/plugin-sdk/agent-scope-runtime";
24
- import { z } from "zod";
25
- import path from "node:path";
26
- import fs from "node:fs/promises";
27
- import { canonicalPathFromExistingAncestor } from "openclaw/plugin-sdk/file-access-runtime";
28
- import { scheduler } from "node:timers/promises";
29
- import { AsyncLocalStorage } from "node:async_hooks";
30
- import { isMainThread, threadId } from "node:worker_threads";
31
- import { areDiagnosticsEnabledForProcess, createSubsystemLogger } from "openclaw/plugin-sdk/diagnostic-runtime";
32
- import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
33
- import { publishSessionCatalogHost, sessionCatalogPaging } from "openclaw/plugin-sdk/session-catalog-paging";
34
- import { decodeNodePtyResumeParams, decodeNodePtyStartParams, resolveNodeHostExecutable, runNodePtyCommand } from "openclaw/plugin-sdk/node-host";
35
- //#region extensions/codex/src/session-catalog-create.ts
36
- const CODEX_AGENT_RUNTIME_ID = "codex";
37
- const CODEX_CATALOG_DEFAULT_MODEL_REF = "openai/gpt-6-astra";
38
- function resolveCodexCatalogCreateSession(modelConfig, config, requestedAgentId) {
39
- if (!config) return;
40
- const agentId = requestedAgentId ?? resolveDefaultAgentId(config);
41
- const defaultModel = modelConfig.resolveDefaultModelForAgent({
42
- cfg: config,
43
- agentId
44
- });
45
- const modelRef = defaultModel.provider === "openai" ? `${defaultModel.provider}/${defaultModel.model}` : CODEX_CATALOG_DEFAULT_MODEL_REF;
46
- const allowed = modelConfig.resolveAllowedModelRef({
47
- cfg: config,
48
- catalog: [],
49
- raw: modelRef,
50
- defaultProvider: defaultModel.provider,
51
- defaultModel: defaultModel.model,
52
- agentId
53
- });
54
- return "error" in allowed ? void 0 : {
55
- model: allowed.key,
56
- agentRuntime: CODEX_AGENT_RUNTIME_ID
57
- };
58
- }
59
- //#endregion
60
- //#region extensions/codex/src/app-server/request-observation.ts
61
- const CODEX_REQUEST_WAITER_OUTCOMES = [
62
- "resolved",
63
- "native-error",
64
- "timed-out",
65
- "aborted",
66
- "authority-rejected",
67
- "local-failed",
68
- "client-closed"
69
- ];
70
- const CODEX_REQUEST_WIRE_OUTCOMES = [
71
- "retained-pending",
72
- "native-ok",
73
- "native-error",
74
- "ingress-rejected",
75
- "correlation-closed",
76
- "not-written"
77
- ];
78
- //#endregion
79
- //#region extensions/codex/src/session-catalog-diagnostics.ts
80
- const log = createSubsystemLogger("gateway/session-catalog");
81
- const listScope = new AsyncLocalStorage();
82
- let epoch;
83
- let sequence = 0;
84
- let active = 0;
85
- let windowStart = 0;
86
- let emitted = 0;
87
- let omitted = 0;
88
- const WAITER_OUTCOMES = new Set(CODEX_REQUEST_WAITER_OUTCOMES);
89
- const WIRE_OUTCOMES = new Set(CODEX_REQUEST_WIRE_OUTCOMES);
90
- function controlWaiterTuple(controlCallOrdinal, summary) {
91
- const ordinals = [
92
- controlCallOrdinal,
93
- summary.overloadAttemptOrdinal,
94
- summary.rpcId,
95
- summary.waiterOrdinal
96
- ];
97
- const times = [
98
- summary.attemptCreatedAtMs,
99
- summary.waiterAttachedAtMs,
100
- summary.waiterSettledAtMs
101
- ];
102
- const optionalTimes = [summary.firstPossibleWriteAtMs, summary.wireObservedAtMs];
103
- const validTime = (value) => Number.isFinite(value) && value >= 0 && Number.isSafeInteger(Math.round(value));
104
- if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(summary.clientInstanceId) || !ordinals.every((value) => Number.isSafeInteger(value) && value > 0) || !times.every(validTime) || !optionalTimes.every((value) => value === null || validTime(value)) || summary.disposition !== "new" && summary.disposition !== "joined" || !WAITER_OUTCOMES.has(summary.waiterOutcome) || !WIRE_OUTCOMES.has(summary.wireOutcomeAtWaiterSettlement)) return;
105
- return [
106
- controlCallOrdinal,
107
- summary.overloadAttemptOrdinal,
108
- summary.clientInstanceId,
109
- summary.rpcId,
110
- summary.waiterOrdinal,
111
- summary.disposition,
112
- Math.round(summary.attemptCreatedAtMs),
113
- summary.firstPossibleWriteAtMs === null ? null : Math.round(summary.firstPossibleWriteAtMs),
114
- Math.round(summary.waiterAttachedAtMs),
115
- Math.round(summary.waiterSettledAtMs),
116
- summary.waiterOutcome,
117
- summary.wireOutcomeAtWaiterSettlement,
118
- summary.wireObservedAtMs === null ? null : Math.round(summary.wireObservedAtMs)
119
- ];
120
- }
121
- function fitsMetadata(metadata) {
122
- return Object.keys(metadata).length <= 28 && Buffer.byteLength(JSON.stringify(metadata)) <= 2048;
123
- }
124
- function withControlWaiters(metadata, fields) {
125
- if (!("origin" in fields) || !fields.controlWaitersV1) return metadata;
126
- const kept = fields.controlWaitersV1.slice();
127
- let count = fields.controlWaitersOmitted ?? 0;
128
- while (true) {
129
- const complete = {
130
- ...metadata,
131
- controlWaitersV1: JSON.stringify(kept),
132
- controlWaitersOmitted: count
133
- };
134
- if (fitsMetadata(complete)) return complete;
135
- if (kept.length === 0) {
136
- const countOnly = {
137
- ...metadata,
138
- controlWaitersOmitted: count
139
- };
140
- return fitsMetadata(countOnly) ? countOnly : metadata;
141
- }
142
- kept.splice(kept.length > 2 ? kept.length - 2 : 0, 1);
143
- count = Math.min(Number.MAX_SAFE_INTEGER, count + 1);
144
- }
145
- }
146
- const CONTROL_PHASE_FIELDS = {
147
- "load-control": "controlLoadMs",
148
- prepare: "controlPrepareMs",
149
- "acquire-client": "controlAcquireClientMs",
150
- "client-request": "controlClientRequestMs",
151
- "release-client": "controlReleaseClientMs"
152
- };
153
- function enabled() {
154
- return areDiagnosticsEnabledForProcess() && log.isEnabled("warn");
155
- }
156
- function start(kind, fields) {
157
- if (!enabled()) return;
158
- if (active >= 64) {
159
- omitted = Math.min(Number.MAX_SAFE_INTEGER, omitted + 1);
160
- return;
161
- }
162
- active++;
163
- epoch ??= randomUUID();
164
- const started = performance.now();
165
- const observation = {
166
- operationId: String(++sequence),
167
- fields,
168
- closed: false,
169
- finish(outcome) {
170
- if (observation.closed) return;
171
- observation.closed = true;
172
- active--;
173
- const elapsedMs = performance.now() - started;
174
- try {
175
- if (elapsedMs < 1e3 || !enabled()) return;
176
- if (performance.now() - windowStart >= 6e4) {
177
- windowStart = performance.now();
178
- emitted = 0;
179
- }
180
- if (emitted >= 60) {
181
- omitted = Math.min(Number.MAX_SAFE_INTEGER, omitted + 1);
182
- return;
183
- }
184
- const metadata = {
185
- diagnosticEpoch: epoch,
186
- operationId: observation.operationId,
187
- pid: process.pid,
188
- threadId,
189
- isMainThread,
190
- elapsedMs: Math.round(elapsedMs),
191
- outcome,
192
- omittedObservations: omitted,
193
- ...Object.fromEntries(Object.entries(fields).filter(([key, value]) => value !== void 0 && key !== "controlWaitersV1" && key !== "controlWaitersOmitted").map(([key, value]) => [key, typeof value === "number" ? Math.round(value) : value]))
194
- };
195
- if (!fitsMetadata(metadata)) {
196
- omitted = Math.min(Number.MAX_SAFE_INTEGER, omitted + 1);
197
- return;
198
- }
199
- emitted++;
200
- log.warn(`slow Codex catalog ${kind}`, withControlWaiters(metadata, fields));
201
- omitted = 0;
202
- } catch {}
203
- }
204
- };
205
- return observation;
206
- }
207
- function currentCodexCatalogListDiagnostics() {
208
- const observation = listScope.getStore();
209
- return observation?.closed ? void 0 : observation;
210
- }
211
- function startCodexCatalogListTiming(field, counter) {
212
- const observation = currentCodexCatalogListDiagnostics();
213
- const started = observation ? performance.now() : 0;
214
- if (observation && counter) observation.fields[counter]++;
215
- return () => {
216
- if (observation && !observation.closed) observation.fields[field] = (observation.fields[field] ?? 0) + performance.now() - started;
217
- };
218
- }
219
- /** One logical list scope survives admission pauses; finishing drops its captured context. */
220
- function createCodexCatalogListScope() {
221
- const observation = start("list phases", {
222
- controlPageCalls: 0,
223
- exclusionMarkCalls: 0,
224
- adoptionCalls: 0
225
- });
226
- let captured = listScope.run(observation, () => AsyncLocalStorage.snapshot());
227
- return {
228
- run(run) {
229
- if (!captured) throw new Error("Codex catalog diagnostic scope is closed");
230
- return captured(run);
231
- },
232
- finish(outcome) {
233
- const finishInScope = captured;
234
- captured = void 0;
235
- finishInScope?.(() => observation?.finish(outcome));
236
- }
237
- };
238
- }
239
- function startCodexCatalogPageDiagnostics(origin) {
240
- return start("page producer", {
241
- origin,
242
- listOperationId: currentCodexCatalogListDiagnostics()?.operationId,
243
- controlRequestCalls: 0,
244
- provenanceChecks: 0,
245
- provenanceCacheHits: 0,
246
- provenanceReadCalls: 0
247
- });
248
- }
249
- function startCodexCatalogControlRequestDiagnostics(page) {
250
- if (!page) return;
251
- let state = "active";
252
- const controlCallOrdinal = page.fields.controlRequestCalls;
253
- let phase = "load-control";
254
- let phaseStarted = performance.now();
255
- const finishPhase = () => {
256
- const now = performance.now();
257
- const field = CONTROL_PHASE_FIELDS[phase];
258
- page.fields[field] = (page.fields[field] ?? 0) + (now - phaseStarted);
259
- phaseStarted = now;
260
- };
261
- const observation = {
262
- attemptWaiterFinished(summary) {
263
- if (state === "closed" || page.closed) return;
264
- const kept = page.fields.controlWaitersV1 ??= [];
265
- page.fields.controlWaitersOmitted ??= 0;
266
- const tuple = controlWaiterTuple(controlCallOrdinal, summary);
267
- if (!tuple) {
268
- page.fields.controlWaitersOmitted = Math.min(Number.MAX_SAFE_INTEGER, page.fields.controlWaitersOmitted + 1);
269
- return;
270
- }
271
- if (kept.length === 4) {
272
- kept.splice(2, 1);
273
- page.fields.controlWaitersOmitted = Math.min(Number.MAX_SAFE_INTEGER, page.fields.controlWaitersOmitted + 1);
274
- }
275
- kept.push(tuple);
276
- },
277
- phase(next) {
278
- if (state === "active" && !page.closed) {
279
- finishPhase();
280
- phase = next;
281
- }
282
- },
283
- failed(failure) {
284
- if (state === "active" && !page.closed) {
285
- finishPhase();
286
- state = "failed";
287
- page.fields.controlFailurePhase = failure.phase;
288
- page.fields.controlFailureCategory = failure.category;
289
- }
290
- },
291
- rejected() {
292
- observation.failed({
293
- phase,
294
- category: "other"
295
- });
296
- },
297
- close() {
298
- if (state === "active" && !page.closed) finishPhase();
299
- state = "closed";
300
- }
301
- };
302
- return observation;
303
- }
304
- //#endregion
305
- //#region extensions/codex/src/session-catalog-node-snapshot.ts
306
- /** One query-compatible native page per node, owned by the registered catalog provider. */
307
- var CodexCatalogNodeSnapshots = class {
308
- constructor() {
309
- this.generation = 0;
310
- this.inventoryGeneration = 0;
311
- this.configGeneration = 0;
312
- this.nodes = /* @__PURE__ */ new Map();
313
- }
314
- start(config) {
315
- if (this.config !== config) {
316
- this.nodes.clear();
317
- this.config = config;
318
- this.configGeneration = this.generation + 1;
319
- this.inventoryGeneration = this.configGeneration;
320
- }
321
- return ++this.generation;
322
- }
323
- observe(generation, nodes) {
324
- if (generation < this.inventoryGeneration) return;
325
- this.inventoryGeneration = generation;
326
- const connected = new Map(nodes.filter((node) => node.connected).map((node) => [node.nodeId, node]));
327
- for (const [nodeId, publication] of this.nodes) {
328
- const node = connected.get(nodeId);
329
- if (!node || node.connectedAtMs !== publication.connection) this.nodes.delete(nodeId);
330
- }
331
- for (const node of connected.values()) if (!this.nodes.has(node.nodeId)) this.nodes.set(node.nodeId, {
332
- connection: node.connectedAtMs,
333
- generation: 0
334
- });
335
- }
336
- forNode(node, generation, key) {
337
- let publication = this.nodes.get(node.nodeId);
338
- if (!publication) {
339
- publication = {
340
- connection: node.connectedAtMs,
341
- generation: 0
342
- };
343
- if (generation >= this.inventoryGeneration) this.nodes.set(node.nodeId, publication);
344
- }
345
- const valid = () => generation >= this.configGeneration && this.nodes.get(node.nodeId) === publication && publication.connection === node.connectedAtMs;
346
- return {
347
- read: () => valid() && publication.snapshot?.key === key ? publication.snapshot : void 0,
348
- publish: (host) => {
349
- if (!valid() || generation < publication.generation) return false;
350
- publication.generation = generation;
351
- publication.snapshot = node.connected && host.connected ? {
352
- key,
353
- generation,
354
- host
355
- } : void 0;
356
- return true;
357
- },
358
- isCurrent: (snapshot) => valid() && publication.snapshot === snapshot,
359
- valid
360
- };
361
- }
362
- };
363
- function createNodeHostPublication(publication, adopted, sourceKey, onHost, signal, partial, waitUntil) {
364
- let publishedSnapshot;
365
- let publishedHost;
366
- const project = (host) => ({
367
- ...host,
368
- sessions: host.sessions.map((session) => {
369
- const entry = session.sourceHomeId ? adopted.get(sourceKey(host.hostId, session.threadId, session.sourceHomeId)) : void 0;
370
- return entry ? {
371
- ...session,
372
- sessionKey: entry.key
373
- } : session;
374
- })
375
- });
376
- const emit = (host) => {
377
- publishedHost = project(host);
378
- return onHost?.(publishedHost);
379
- };
380
- return {
381
- project,
382
- readPublished: () => publishedHost,
383
- publish: (host) => {
384
- if (signal?.aborted) return partial ? void 0 : onHost?.(project(host));
385
- if (!publication.valid()) return;
386
- if (publication.publish(host)) {
387
- publishedSnapshot = publication.read();
388
- return emit(host);
389
- }
390
- const latest = publication.read();
391
- return emit(latest?.host ?? host);
392
- },
393
- publishCached: (snapshot) => {
394
- if (signal?.aborted || snapshot === publishedSnapshot || !publication.isCurrent(snapshot)) return;
395
- const completion = createDeferred();
396
- completion.promise.catch(() => void 0);
397
- try {
398
- waitUntil?.(completion.promise);
399
- completion.resolve(emit(snapshot.host));
400
- publishedSnapshot = snapshot;
401
- } catch (error) {
402
- completion.reject(error);
403
- throw error;
404
- }
405
- }
406
- };
407
- }
408
- //#endregion
409
- //#region extensions/codex/src/session-catalog-terminal.ts
410
- const CODEX_TERMINAL_RESUME_COMMAND = "codex.terminal.resume.v1";
411
- const CODEX_TERMINAL_START_COMMAND = "codex.terminal.start.v1";
412
- function createCodexTerminalStartNodeHostCommand() {
413
- return {
414
- command: CODEX_TERMINAL_START_COMMAND,
415
- cap: CODEX_APP_SERVER_THREADS_CAPABILITY,
416
- dangerous: false,
417
- duplex: true,
418
- hasActiveWork: () => false,
419
- isAvailable: ({ env }) => Boolean(resolveNodeHostExecutable("codex", {
420
- env,
421
- strategy: "direct"
422
- })),
423
- handle: async (paramsJSON, io) => {
424
- if (!io) throw new Error("Codex terminal command requires duplex transport");
425
- const params = decodeNodePtyStartParams(paramsJSON);
426
- const resolution = resolveNodeHostExecutable("codex", { strategy: "direct" });
427
- if (!resolution) throw new Error("Codex CLI is unavailable; install codex on this node and reconnect");
428
- return JSON.stringify(await runNodePtyCommand({
429
- file: resolution.executable,
430
- args: params.initialMessage !== void 0 ? ["--", params.initialMessage] : [],
431
- cwd: params.cwd,
432
- requiredCwd: true,
433
- cols: params.cols,
434
- rows: params.rows
435
- }, io));
436
- }
437
- };
438
- }
439
- function resolveCodexCatalogTerminalHome(sources) {
440
- sources.source?.assertCurrent();
441
- const runtimeConfig = sources.getRuntimeConfig();
442
- if (!runtimeConfig) throw new Error("OpenClaw runtime config is unavailable");
443
- const agentDir = sources.source?.agentDir ?? (sources.agentId ? resolveAgentDir(runtimeConfig, sources.agentId) : resolveDefaultAgentDir(runtimeConfig));
444
- const startOptions = sources.source?.appServer.start ?? sources.resolveRuntimeOptions({ pluginConfig: sources.getPluginConfig() }).start;
445
- if (startOptions.transport !== "stdio") throw new CatalogParamsError("Native terminal requires a local Codex source");
446
- return resolveCodexAppServerLocalHomeDir(startOptions, agentDir);
447
- }
448
- function resolveLocalCodexTerminalExecutable(env = process.env) {
449
- return resolveLocalCodexTerminalResolution(env)?.executable;
450
- }
451
- function resolveLocalCodexTerminalResolution(env = process.env) {
452
- return resolveNodeHostExecutable("codex", {
453
- env,
454
- pathEnv: env.PATH ?? env.Path ?? "",
455
- strategy: "fallback"
456
- });
457
- }
458
- function codexNodeTerminalCapability(node) {
459
- const commands = node.invocableCommands ?? node.commands;
460
- return {
461
- canOpenTerminalCodex: node.connected === true && commands?.includes("codex.terminal.resume.v1") === true,
462
- canStartTerminal: node.connected === true && node.invocableCommands?.includes("codex.terminal.start.v1") === true
463
- };
464
- }
465
- function createCodexTerminalNodeHostCommand(bindRequest) {
466
- return {
467
- command: CODEX_TERMINAL_RESUME_COMMAND,
468
- cap: CODEX_APP_SERVER_THREADS_CAPABILITY,
469
- dangerous: false,
470
- duplex: true,
471
- hasActiveWork: () => false,
472
- isAvailable: ({ config, env }) => (readCodexPluginConfig(config.plugins?.entries?.codex?.config).appServer?.transport ?? "stdio") === "stdio" && Boolean(resolveNodeHostExecutable("codex", {
473
- env,
474
- pathEnv: env.PATH ?? env.Path ?? "",
475
- strategy: "direct"
476
- })),
477
- handle: async (paramsJSON, io) => {
478
- if (!io) throw new Error("Codex terminal command requires duplex transport");
479
- const request = await bindRequest(paramsJSON);
480
- if (request.transport !== "stdio") throw new CatalogParamsError("Native terminal requires a local Codex source");
481
- const resume = decodeNodePtyResumeParams(request.paramsJSON, (value) => {
482
- if (typeof value !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(value)) throw new CatalogParamsError("threadId must be a UUID");
483
- return value;
484
- });
485
- const record = await request.control.requireEligibleThread(resume.threadId);
486
- const resolution = resolveNodeHostExecutable("codex", {
487
- env: process.env,
488
- pathEnv: process.env.PATH ?? process.env.Path ?? "",
489
- strategy: "direct"
490
- });
491
- if (!resolution) throw new Error("Codex CLI is unavailable");
492
- request.assertCurrent();
493
- return JSON.stringify(await runNodePtyCommand({
494
- file: resolution.executable,
495
- args: ["resume", resume.threadId],
496
- assertCurrent: () => request.assertCurrent(),
497
- ...record.cwd ? { cwd: record.cwd } : {},
498
- env: { CODEX_HOME: request.codexHome },
499
- cols: resume.cols,
500
- rows: resume.rows
501
- }, io));
502
- }
503
- };
504
- }
505
- async function openCodexCatalogTerminal(params) {
506
- const title = `codex resume ${params.threadId.slice(0, 8)}…`;
507
- if (params.hostId === "gateway:local" || params.hostId.startsWith(`gateway:local:`)) {
508
- const record = await params.control.requireEligibleThread(params.threadId);
509
- const resolution = resolveLocalCodexTerminalResolution();
510
- if (!resolution) throw new CatalogParamsError("Codex CLI is unavailable");
511
- return {
512
- kind: "local",
513
- argv: [
514
- resolution.executable,
515
- "resume",
516
- params.threadId
517
- ],
518
- ...record.cwd ? { cwd: record.cwd } : {},
519
- env: { CODEX_HOME: resolveCodexCatalogTerminalHome(params) },
520
- ...resolution.pathEnv ? { pathEnv: resolution.pathEnv } : {},
521
- title
522
- };
523
- }
524
- if (!params.hostId.startsWith("node:")) throw new CatalogParamsError("hostId is invalid");
525
- const nodeId = params.hostId.slice(5);
526
- if (!(await params.api.runtime.nodes.list()).nodes.find((candidate) => {
527
- const commands = candidate.invocableCommands ?? candidate.commands;
528
- return candidate.nodeId === nodeId && candidate.connected === true && commands?.includes("codex.appServer.threads.list.v1") === true && commands.includes("codex.terminal.resume.v1");
529
- })) throw new CatalogParamsError("paired-node Codex terminal is unavailable");
530
- const lookup = await lookupNodeCodexCatalogRecord({
531
- agentId: params.agentId,
532
- runtime: params.api.runtime,
533
- nodeId,
534
- threadId: params.threadId,
535
- sourceHomeId: params.sourceHomeId
536
- });
537
- if (lookup.kind !== "found" || !isInteractiveThreadSource(lookup.record.source)) throw new CatalogParamsError("Codex session is not a non-archived interactive Codex session");
538
- const record = lookup.record;
539
- return {
540
- kind: "node",
541
- nodeId,
542
- command: CODEX_TERMINAL_RESUME_COMMAND,
543
- uploadPathStyle: "native",
544
- paramsJSON: JSON.stringify({
545
- agentId: params.agentId,
546
- threadId: params.threadId,
547
- ...lookup.sourceHomeId ? { sourceHomeId: lookup.sourceHomeId } : {}
548
- }),
549
- ...record.cwd ? { cwd: record.cwd } : {},
550
- title
551
- };
552
- }
553
- async function startCodexCatalogTerminal(params) {
554
- if (params.nodeId) return {
555
- kind: "node",
556
- nodeId: params.nodeId,
557
- command: CODEX_TERMINAL_START_COMMAND,
558
- uploadPathStyle: "native",
559
- paramsJSON: JSON.stringify({
560
- cwd: params.cwd,
561
- initialMessage: params.initialMessage
562
- }),
563
- cwd: params.cwd,
564
- title: "codex"
565
- };
566
- const resolution = resolveLocalCodexTerminalResolution();
567
- if (!resolution) throw new CatalogParamsError("Codex CLI is unavailable; install Codex or add codex to PATH, then try again");
568
- return {
569
- kind: "local",
570
- argv: [resolution.executable, ...params.initialMessage !== void 0 ? ["--", params.initialMessage] : []],
571
- cwd: params.cwd,
572
- env: { CODEX_HOME: resolveCodexCatalogTerminalHome(params) },
573
- ...resolution.pathEnv ? { pathEnv: resolution.pathEnv } : {},
574
- title: "codex"
575
- };
576
- }
577
- //#endregion
578
- //#region extensions/codex/src/session-catalog-visible-page.ts
579
- /** Fill exclusions from bounded resident pages. */
580
- var CodexCatalogVisiblePage = class {
581
- constructor(params) {
582
- this.params = params;
583
- this.sessions = [];
584
- this.seenCursors = /* @__PURE__ */ new Set();
585
- this.pages = 0;
586
- this.complete = false;
587
- this.request = new CodexCatalogListRequest();
588
- this.cursor = params.cursor;
589
- }
590
- async next() {
591
- try {
592
- const step = await this.request.run(() => this.nextPage());
593
- if (step.done) this.request.resolved();
594
- return step;
595
- } catch (error) {
596
- if (this.params.signal?.aborted) this.request.close();
597
- else this.request.rejected(error);
598
- throw error;
599
- }
600
- }
601
- close() {
602
- this.complete = true;
603
- this.request.close();
604
- }
605
- async nextPage() {
606
- if (this.complete) throw new Error("Codex catalog page is already complete");
607
- const params = this.params;
608
- params.signal?.throwIfAborted();
609
- const finishTiming = startCodexCatalogListTiming("controlWaitSumMs", "controlPageCalls");
610
- let rawPage;
611
- try {
612
- rawPage = await params.control.listPage({
613
- limit: params.limit - this.sessions.length,
614
- ...this.cursor ? { cursor: this.cursor } : {},
615
- ...params.searchTerm ? { searchTerm: params.searchTerm } : {},
616
- ...params.cwd ? { cwd: params.cwd } : {}
617
- });
618
- } finally {
619
- finishTiming();
620
- }
621
- this.request.assertActive();
622
- params.signal?.throwIfAborted();
623
- const page = filterCatalogPageByTitle(parseCatalogPage(rawPage), params.searchTerm);
624
- if (this.pages++ === 0) this.backwardsCursor = page.backwardsCursor;
625
- let excludedFromPage = false;
626
- for (const managed of rawPage.managedThreads ?? []) {
627
- excludedFromPage = true;
628
- params.signal?.throwIfAborted();
629
- await params.onExcludedThread?.(managed);
630
- }
631
- for (const session of page.sessions) {
632
- if (!params.excludedThreadIds?.has(session.threadId)) {
633
- this.sessions.push(session);
634
- continue;
635
- }
636
- excludedFromPage = true;
637
- params.signal?.throwIfAborted();
638
- await params.onExcludedThread?.({ threadId: session.threadId });
639
- }
640
- const nextCursor = page.nextCursor;
641
- if (!nextCursor || this.sessions.length >= params.limit || !excludedFromPage) this.complete = true;
642
- else {
643
- if (this.seenCursors.has(nextCursor)) throw new Error("Codex session catalog returned a repeated exclusion cursor");
644
- this.seenCursors.add(nextCursor);
645
- this.cursor = nextCursor;
646
- this.complete = this.pages >= 20 || !this.request.hasPages;
647
- }
648
- return this.complete ? {
649
- done: true,
650
- page: {
651
- sessions: this.sessions.slice(0, params.limit),
652
- ...nextCursor ? { nextCursor } : {},
653
- ...this.backwardsCursor ? { backwardsCursor: this.backwardsCursor } : {}
654
- }
655
- } : { done: false };
656
- }
657
- };
658
- /** Node and direct callers finish the same bounded outer algorithm inline. */
659
- async function listVisiblePage(params) {
660
- const operation = new CodexCatalogVisiblePage(params);
661
- try {
662
- for (;;) {
663
- const step = await operation.next();
664
- if (step.done) return step.page;
665
- }
666
- } finally {
667
- operation.close();
668
- }
669
- }
670
- //#endregion
671
- //#region extensions/codex/src/session-catalog-list-operation.ts
672
- async function boundedHost(pending) {
673
- let timer;
674
- try {
675
- return await Promise.race([pending, new Promise((resolve) => {
676
- timer = setTimeout(() => resolve(void 0), 250);
677
- })]);
678
- } finally {
679
- clearTimeout(timer);
680
- }
681
- }
682
- function measureNodeHost(host, diagnostics, started) {
683
- return diagnostics ? host.finally(() => {
684
- if (!diagnostics.closed) {
685
- diagnostics.fields.pairedNodeSettled = (diagnostics.fields.pairedNodeSettled ?? 0) + 1;
686
- diagnostics.fields.nodeWaitSumMs = (diagnostics.fields.nodeWaitSumMs ?? 0) + performance.now() - started;
687
- }
688
- }) : host;
689
- }
690
- function hostFailure(source, error) {
691
- return {
692
- hostId: source?.hostId ?? "gateway:local",
693
- label: source?.label ?? "Local Codex",
694
- kind: "gateway",
695
- connected: false,
696
- sessions: [],
697
- error: error instanceof CodexCatalogLoadingError ? {
698
- code: error.code,
699
- message: error.message
700
- } : catalogError("APP_SERVER_UNAVAILABLE", error)
701
- };
702
- }
703
- async function projectLocalHost(params, agentId, source, page) {
704
- params.signal?.throwIfAborted();
705
- const { listAdoptedSessionEntries } = await import("./session-catalog-adoption-BU_pHWG7.mjs");
706
- const { sessionCatalogAdoptedSourceKey } = await import("openclaw/plugin-sdk/session-catalog");
707
- params.signal?.throwIfAborted();
708
- const finishTiming = startCodexCatalogListTiming("adoptionSumMs", "adoptionCalls");
709
- let adopted;
710
- try {
711
- adopted = await listAdoptedSessionEntries({
712
- agentId,
713
- bindingStore: params.bindingStore,
714
- config: params.config,
715
- runtime: params.runtime,
716
- sessionEntries: params.sessionEntries
717
- });
718
- } finally {
719
- finishTiming();
720
- }
721
- const hostId = source?.hostId ?? "gateway:local";
722
- const sourceHomeId = source?.sourceHomeId ?? "gateway:local";
723
- return {
724
- hostId,
725
- label: source?.label ?? "Local Codex",
726
- kind: "gateway",
727
- connected: true,
728
- ...page,
729
- sessions: page.sessions.map((session) => {
730
- const entry = adopted.get(sessionCatalogAdoptedSourceKey(sourceHomeId, session.threadId)) ?? (hostId === "gateway:local" ? adopted.get(sessionCatalogAdoptedSourceKey("gateway:local", session.threadId)) : void 0);
731
- const sourced = source ? {
732
- ...session,
733
- sourceHomeId: source.sourceHomeId
734
- } : session;
735
- return entry ? {
736
- ...sourced,
737
- sessionKey: entry.key
738
- } : sourced;
739
- })
740
- };
741
- }
742
- function managedMarker(store, sourceHomeId, managed) {
743
- return async ({ threadId, rolloutPath }) => {
744
- if (managed?.has(threadId)) return;
745
- const finishTiming = startCodexCatalogListTiming("exclusionMarkSumMs", "exclusionMarkCalls");
746
- try {
747
- await store.mark({
748
- sourceHomeId,
749
- threadId,
750
- ...rolloutPath ? { rolloutPath } : {}
751
- });
752
- } finally {
753
- finishTiming();
754
- }
755
- };
756
- }
757
- async function finishLocalHost(params, agentId, host) {
758
- try {
759
- for (;;) {
760
- const step = await host.page.next();
761
- params.signal?.throwIfAborted();
762
- if (step.done) return await projectLocalHost(params, agentId, host.source, step.page);
763
- }
764
- } catch (error) {
765
- return hostFailure(host.source, error);
766
- } finally {
767
- host.page.close();
768
- }
769
- }
770
- function createNodePublicationTracker(publications, waitUntil) {
771
- const settled = () => {
772
- publications.pending--;
773
- };
774
- return (completion) => {
775
- publications.pending++;
776
- completion.then(settled, settled);
777
- waitUntil?.(completion);
778
- };
779
- }
780
- /** Holds only one logical filled list; no native producer is suspended between next calls. */
781
- var CodexCatalogListDriver = class {
782
- constructor(params) {
783
- this.locals = [];
784
- this.nodeActive = false;
785
- this.nodeResults = [];
786
- this.nodeDiscoveryFailed = false;
787
- this.nodePublications = { pending: 0 };
788
- this.nodesStarted = false;
789
- this.localFailed = false;
790
- this.active = 0;
791
- this.running = false;
792
- this.complete = false;
793
- this.params = params;
794
- this.nodeSnapshots = params.nodeSnapshots ?? new CodexCatalogNodeSnapshots();
795
- this.nodeGeneration = this.nodeSnapshots.start(params.config);
796
- }
797
- request() {
798
- if (!this.params) throw new Error("Codex catalog list operation is closed");
799
- return this.params;
800
- }
801
- selection() {
802
- if (!this.prepared) throw new Error("Codex catalog list operation is not initialized");
803
- return this.prepared;
804
- }
805
- async initialize() {
806
- const params = this.request();
807
- const agentId = resolveSessionAgentIdsStrict({
808
- config: params.config ?? {},
809
- agentId: params.agentId
810
- }).sessionAgentId;
811
- const query = readGatewayParams(params.query);
812
- const requestedHostIds = query.hostIds ? new Set(query.hostIds) : void 0;
813
- const localSources = params.localHomes?.filter((source) => !requestedHostIds || requestedHostIds.has(source.hostId)) ?? (params.includeLocal !== false && (!requestedHostIds || requestedHostIds.has("gateway:local")) ? [void 0] : []);
814
- const diagnostics = currentCodexCatalogListDiagnostics();
815
- if (diagnostics) diagnostics.fields.localHostCount = localSources.length;
816
- const store = params.bindingStore.managedThreads;
817
- const started = diagnostics && store ? performance.now() : 0;
818
- let managed;
819
- try {
820
- managed = await store?.snapshot();
821
- } finally {
822
- if (diagnostics && !diagnostics.closed && store) diagnostics.fields.managedSnapshotMs = performance.now() - started;
823
- }
824
- params.signal?.throwIfAborted();
825
- const fallback = localSources.some((source) => source === void 0) ? (await params.control.homesForAgent(agentId))[0] : void 0;
826
- params.signal?.throwIfAborted();
827
- this.prepared = {
828
- agentId,
829
- query,
830
- requestedHostIds
831
- };
832
- if (requestedHostIds && !query.hostIds?.some((host) => host.startsWith("node:"))) this.nodeHosts = [];
833
- for (const source of localSources) {
834
- const selected = source ?? fallback;
835
- const excluded = selected ? managed?.get(selected.sourceHomeId) : void 0;
836
- const host = {
837
- source,
838
- page: new CodexCatalogVisiblePage({
839
- control: params.control.forRequest(agentId, selected),
840
- cursor: query.cursors?.[source?.hostId ?? "gateway:local"],
841
- limit: query.limitPerHost,
842
- excludedThreadIds: excluded,
843
- searchTerm: query.search,
844
- signal: params.signal,
845
- ...selected && store ? { onExcludedThread: managedMarker(store, selected.sourceHomeId, excluded) } : {}
846
- }),
847
- completion: createDeferred()
848
- };
849
- this.locals.push(host);
850
- publishSessionCatalogHost(params, host.completion.promise);
851
- }
852
- }
853
- canPause() {
854
- return !this.localFailed && this.nodeHosts !== void 0 && !this.nodeDiscoveryFailed && !this.nodeActive && this.nodePublications.pending === 0;
855
- }
856
- async readHost(host) {
857
- const params = this.request();
858
- if (params.allowPartialResults === true && params.onHost && params.waitUntil) {
859
- host.background = true;
860
- const completion = finishLocalHost(params, this.selection().agentId, host);
861
- completion.then(host.completion.resolve, host.completion.reject);
862
- host.value = await boundedHost(completion) ?? {
863
- hostId: host.source?.hostId ?? "gateway:local",
864
- label: host.source?.label ?? "Local Codex",
865
- kind: "gateway",
866
- connected: true,
867
- pending: true,
868
- sessions: []
869
- };
870
- return;
871
- }
872
- try {
873
- const page = await host.page.next();
874
- params.signal?.throwIfAborted();
875
- if (page.done) host.value = await projectLocalHost(params, this.selection().agentId, host.source, page.page);
876
- } catch (error) {
877
- this.localFailed = true;
878
- host.value = hostFailure(host.source, error);
879
- }
880
- if (host.value) host.completion.resolve(host.value);
881
- }
882
- startHost(host) {
883
- if (host.value || host.active || this.failure) return;
884
- this.active++;
885
- host.active = this.readHost(host).then(() => {
886
- host.active = void 0;
887
- this.active--;
888
- if (!host.value && (!this.canPause() || this.active > 0)) this.startHost(host);
889
- this.checkpoint();
890
- }, (error) => {
891
- host.active = void 0;
892
- this.active--;
893
- this.failure ??= { error };
894
- this.checkpoint();
895
- });
896
- }
897
- async readNodes() {
898
- const params = this.request();
899
- const { agentId, query, requestedHostIds } = this.selection();
900
- const diagnostics = currentCodexCatalogListDiagnostics();
901
- const started = diagnostics ? performance.now() : 0;
902
- if (diagnostics) diagnostics.fields.nodeRegistryCalls = 1;
903
- let nodes;
904
- let inventory;
905
- try {
906
- try {
907
- inventory = (await (params.listNodes?.() ?? params.runtime.nodes.list())).nodes;
908
- nodes = inventory.filter((node) => node.gatewayLocal !== true && (node.commands?.includes("codex.appServer.threads.list.v1") || codexNodeTerminalCapability(node).canStartTerminal) && (!requestedHostIds || requestedHostIds.has(`node:${node.nodeId}`))).slice(0, 100 - this.locals.length);
909
- } finally {
910
- if (diagnostics && !diagnostics.closed) diagnostics.fields.nodeRegistryMs = performance.now() - started;
911
- }
912
- } catch (error) {
913
- this.nodeDiscoveryFailed = true;
914
- const host = {
915
- hostId: "node:registry",
916
- label: "Paired nodes",
917
- kind: "node",
918
- connected: false,
919
- canStartTerminal: false,
920
- sessions: [],
921
- error: catalogError("NODE_LIST_FAILED", error)
922
- };
923
- params.onHost?.(host);
924
- return [host];
925
- }
926
- params.signal?.throwIfAborted();
927
- this.nodeSnapshots.observe(this.nodeGeneration, inventory);
928
- const { listNodeAdoptedSessionEntries, nodeAdoptedSourceKey } = await import("./session-catalog-node-adoption-DgXvSGu0.mjs");
929
- const { compareNodeLabels, listPairedNode, nodeLabel } = await import("./session-catalog-node-continue-DjKXHBbi.mjs");
930
- params.signal?.throwIfAborted();
931
- const adopted = listNodeAdoptedSessionEntries({
932
- agentId,
933
- config: params.config,
934
- runtime: params.runtime,
935
- sessionEntries: params.sessionEntries
936
- });
937
- if (diagnostics && !diagnostics.closed) {
938
- diagnostics.fields.pairedNodeCalls = 0;
939
- diagnostics.fields.pairedNodeSettled = 0;
940
- }
941
- const trackPublication = createNodePublicationTracker(this.nodePublications, params.waitUntil);
942
- const partial = params.allowPartialResults === true && Boolean(params.onHost && params.waitUntil);
943
- const pendingHosts = nodes.toSorted(compareNodeLabels).map((node) => {
944
- const key = JSON.stringify([
945
- agentId,
946
- query.limitPerHost,
947
- query.search,
948
- query.cursors?.[`node:${node.nodeId}`],
949
- node.displayName,
950
- node.remoteIp,
951
- node.caps,
952
- node.commands,
953
- node.invocableCommands
954
- ]);
955
- const publication = this.nodeSnapshots.forNode(node, this.nodeGeneration, key);
956
- const { project, publish, publishCached, readPublished } = createNodeHostPublication(publication, adopted, nodeAdoptedSourceKey, params.onHost, params.signal, partial, trackPublication);
957
- const cached = partial ? publication.read() : void 0;
958
- let result;
959
- this.nodeResults.push(() => {
960
- const latest = partial ? publication.read() : void 0;
961
- if (latest) {
962
- publishCached(latest);
963
- return project(latest.host);
964
- }
965
- return !partial ? result : publication.valid() ? readPublished() ?? result : void 0;
966
- });
967
- if (cached) publishCached(cached);
968
- const nodeStarted = diagnostics ? performance.now() : 0;
969
- if (diagnostics && !diagnostics.closed) diagnostics.fields.pairedNodeCalls = (diagnostics.fields.pairedNodeCalls ?? 0) + 1;
970
- const completion = measureNodeHost(listPairedNode({
971
- agentId,
972
- runtime: params.runtime,
973
- node,
974
- query,
975
- terminalCapabilities: codexNodeTerminalCapability(node),
976
- waitUntil: trackPublication,
977
- signal: params.signal,
978
- onHost: publish
979
- }), diagnostics, nodeStarted);
980
- if (cached) {
981
- completion.catch(() => void 0);
982
- return Promise.resolve(project(cached.host));
983
- }
984
- return (partial ? boundedHost(completion) : completion).then((value) => {
985
- result = value ? project(value) : {
986
- hostId: `node:${node.nodeId}`,
987
- label: nodeLabel(node),
988
- kind: "node",
989
- nodeId: node.nodeId,
990
- connected: true,
991
- pending: true,
992
- ...codexNodeTerminalCapability(node),
993
- sessions: []
994
- };
995
- return result;
996
- });
997
- });
998
- try {
999
- return await Promise.all(pendingHosts);
1000
- } catch (error) {
1001
- await Promise.allSettled(pendingHosts);
1002
- throw error;
1003
- }
1004
- }
1005
- startNodes() {
1006
- if (this.nodeHosts !== void 0 || this.nodesStarted) return;
1007
- this.nodesStarted = true;
1008
- this.nodeActive = true;
1009
- this.readNodes().then((hosts) => {
1010
- this.nodeHosts = hosts;
1011
- this.nodeActive = false;
1012
- this.checkpoint();
1013
- }, (error) => {
1014
- this.nodeActive = false;
1015
- this.failure ??= { error };
1016
- this.checkpoint();
1017
- });
1018
- }
1019
- checkpoint() {
1020
- if (this.active > 0 || !this.step) return;
1021
- if (this.failure) {
1022
- if (!this.nodeActive) this.step.reject(this.failure.error);
1023
- } else if (this.nodeHosts && this.locals.every((host) => host.value !== void 0)) try {
1024
- this.complete = true;
1025
- this.step.resolve({
1026
- done: true,
1027
- hosts: [...this.locals.flatMap((host) => host.value ? [host.value] : []), ...this.nodeResults.length ? this.nodeResults.flatMap((read) => {
1028
- const host = read();
1029
- return host ? [host] : [];
1030
- }) : this.nodeHosts]
1031
- });
1032
- } catch (error) {
1033
- this.failure ??= { error };
1034
- this.step.reject(error);
1035
- }
1036
- else if (this.canPause()) this.step.resolve({ done: false });
1037
- }
1038
- async next() {
1039
- const params = this.request();
1040
- if (this.running || this.complete) throw new Error("Codex catalog list operation cannot advance");
1041
- params.signal?.throwIfAborted();
1042
- this.running = true;
1043
- try {
1044
- if (!this.prepared) await this.initialize();
1045
- this.step = createDeferred();
1046
- for (const host of this.locals) this.startHost(host);
1047
- this.startNodes();
1048
- this.checkpoint();
1049
- return await this.step.promise;
1050
- } finally {
1051
- this.running = false;
1052
- this.step = void 0;
1053
- }
1054
- }
1055
- close() {
1056
- if (!this.params) return;
1057
- if (this.running) throw new Error("Cannot close an active Codex catalog list step");
1058
- const reason = this.failure?.error ?? this.params.signal?.reason ?? /* @__PURE__ */ new Error("Codex catalog list operation closed");
1059
- this.params = void 0;
1060
- for (const host of this.locals) {
1061
- if (!host.background) host.page.close();
1062
- if (!host.value) host.completion.reject(reason);
1063
- }
1064
- this.locals = [];
1065
- this.prepared = void 0;
1066
- this.nodeHosts = void 0;
1067
- this.nodeResults = [];
1068
- this.failure = void 0;
1069
- }
1070
- };
1071
- function createCodexSessionCatalogListOperation(params) {
1072
- const driver = new CodexCatalogListDriver(params);
1073
- return {
1074
- next: () => driver.next(),
1075
- close: () => driver.close()
1076
- };
1077
- }
1078
- async function runCatalogListInline(operation) {
1079
- try {
1080
- for (;;) {
1081
- const step = await operation.next();
1082
- if (step.done) return step.hosts;
1083
- }
1084
- } finally {
1085
- operation.close();
1086
- }
1087
- }
1088
- async function listCodexSessionCatalog(params) {
1089
- return { hosts: await runCatalogListInline(createCodexSessionCatalogListOperation(params)) };
1090
- }
1091
- //#endregion
1092
- //#region extensions/codex/src/app-server/thread-history-page.ts
1093
- const TURN_ITEM_CURSOR_PREFIX = "turn-item:";
1094
- function encodeTurnItemCursor(turnCursor, itemId) {
1095
- return TURN_ITEM_CURSOR_PREFIX + Buffer.from(JSON.stringify([turnCursor, itemId])).toString("base64url");
1096
- }
1097
- function decodeTurnItemCursor(cursor) {
1098
- if (!cursor?.startsWith(TURN_ITEM_CURSOR_PREFIX)) return { turnCursor: cursor };
1099
- let value;
1100
- try {
1101
- value = JSON.parse(Buffer.from(cursor.slice(10), "base64url").toString());
1102
- } catch {
1103
- throw new CatalogParamsError("invalid Codex transcript item cursor");
1104
- }
1105
- if (!Array.isArray(value) || value.length !== 2 || typeof value[0] !== "string" || !value[0] || typeof value[1] !== "string" || !value[1]) throw new CatalogParamsError("invalid Codex transcript item cursor");
1106
- return {
1107
- turnCursor: value[0],
1108
- itemId: value[1]
1109
- };
1110
- }
1111
- /** Legacy stores expose only turn cursors; an item identity preserves paging across appends. */
1112
- async function readLegacyCodexHistoryPage(readTurns, request, projection) {
1113
- const { turnCursor, itemId } = decodeTurnItemCursor(request.cursor);
1114
- const page = parseTranscriptPage(await readTurns({
1115
- threadId: request.threadId,
1116
- limit: 1,
1117
- sortDirection: "desc",
1118
- itemsView: "full",
1119
- ...turnCursor ? { cursor: turnCursor } : {}
1120
- }));
1121
- const source = page.data.flatMap(({ items, ...turn }) => items.toReversed().map((item) => ({
1122
- turnId: turn.id,
1123
- item,
1124
- turn
1125
- })));
1126
- const anchorIndex = itemId ? source.findIndex(({ item }) => item.id === itemId) : -1;
1127
- if (itemId && anchorIndex < 0) throw new CatalogParamsError("Codex transcript changed; refresh the session before loading older items");
1128
- const remaining = source.slice(anchorIndex + 1);
1129
- const items = projection.project(remaining.slice(0, request.limit), request.limit);
1130
- const result = () => {
1131
- const lastSource = remaining[items.length - 1];
1132
- const partial = lastSource !== void 0 && items.length < remaining.length;
1133
- const nativeCursor = partial ? page.backwardsCursor : page.nextCursor;
1134
- const cursor = nativeCursor ? partial ? encodeTurnItemCursor(nativeCursor, lastSource.item.id) : nativeCursor : void 0;
1135
- if (partial && !cursor) throw new Error("Codex app-server did not provide a transcript continuation anchor");
1136
- return {
1137
- items,
1138
- ...cursor ? { nextCursor: cursor } : {}
1139
- };
1140
- };
1141
- let bounded = result();
1142
- while (!projection.fits(bounded)) {
1143
- if (items.length <= 1) throw new Error("Codex transcript item exceeds the safe response size");
1144
- items.pop();
1145
- bounded = result();
1146
- }
1147
- return bounded;
1148
- }
1149
- /** Callers authorize the thread; this reader owns native cursor and response-size semantics. */
1150
- async function readCodexThreadHistoryPage(control, thread, request, projection) {
1151
- if (thread.historyMode !== "paginated") return readLegacyCodexHistoryPage((params) => control.listTurnPage(params), request, projection);
1152
- let limit = request.limit;
1153
- for (;;) {
1154
- const page = await control.listItemPage({
1155
- threadId: request.threadId,
1156
- limit,
1157
- sortDirection: "desc",
1158
- ...request.cursor ? { cursor: request.cursor } : {}
1159
- });
1160
- const nextCursor = readControlCursor(page.nextCursor, "transcript next response");
1161
- const items = projection.project(page.data, limit);
1162
- const result = {
1163
- items,
1164
- ...nextCursor ? { nextCursor } : {}
1165
- };
1166
- const fittingCount = items.length - (projection.fits(result) ? 0 : 1);
1167
- if (fittingCount === page.data.length) return result;
1168
- if (fittingCount < 1) throw new Error("Codex transcript item exceeds the safe response size");
1169
- limit = fittingCount;
1170
- }
1171
- }
1172
- //#endregion
1173
- //#region extensions/codex/src/session-catalog-transcript-item.ts
1174
- const CODEX_MESSAGE_TYPES = /* @__PURE__ */ new Map([
1175
- ["userMessage", "userMessage"],
1176
- ["agentMessage", "agentMessage"],
1177
- ["reasoning", "reasoning"]
1178
- ]);
1179
- const CODEX_TOOL_TYPES = /* @__PURE__ */ new Set([
1180
- "commandExecution",
1181
- "fileChange",
1182
- "mcpToolCall",
1183
- "dynamicToolCall",
1184
- "collabAgentToolCall",
1185
- "webSearch",
1186
- "imageView",
1187
- "imageGeneration"
1188
- ]);
1189
- function toGenericTranscriptItem(item) {
1190
- let type = CODEX_MESSAGE_TYPES.get(item.type);
1191
- if (!type && CODEX_TOOL_TYPES.has(item.type)) type = item.result !== void 0 || Boolean(item.aggregatedOutput) ? "toolResult" : "toolCall";
1192
- type ??= "other";
1193
- const fallback = item.title ?? item.name ?? item.tool ?? item.command ?? item.query ?? void 0;
1194
- const resultText = item.aggregatedOutput || (item.result === void 0 ? void 0 : JSON.stringify(item.result, null, 2));
1195
- const changesText = Array.isArray(item.changes) ? item.changes.map((change) => `${change.kind}: ${change.path}`).join("\n") || void 0 : void 0;
1196
- const text = item.type === "userMessage" ? projectCodexUserItemText(item) : item.text || resultText || changesText || fallback;
1197
- return {
1198
- id: item.id,
1199
- type,
1200
- ...text ? { text } : {},
1201
- raw: item
1202
- };
1203
- }
1204
- //#endregion
1205
- //#region extensions/codex/src/session-catalog-transcript.ts
1206
- const transcriptPageSchema = z.strictObject({
1207
- items: z.array(z.strictObject({
1208
- id: z.string(),
1209
- type: z.enum([
1210
- "userMessage",
1211
- "agentMessage",
1212
- "reasoning",
1213
- "toolCall",
1214
- "toolResult",
1215
- "other"
1216
- ]),
1217
- text: z.string().optional(),
1218
- raw: z.record(z.string(), z.json()).optional(),
1219
- truncated: z.boolean().optional()
1220
- })),
1221
- nextCursor: z.string().optional()
1222
- });
1223
- function parseCodexCatalogTranscriptPage(value) {
1224
- return transcriptPageSchema.parse(value);
1225
- }
1226
- function projectTranscriptPage(entries, limit) {
1227
- const projected = entries.map(({ item }) => toGenericTranscriptItem(item));
1228
- const page = sessionCatalogPaging.boundTranscriptPage(projected.toReversed(), limit, 0).items;
1229
- for (const [index, item] of page.entries()) if (item.text !== projected[index]?.text && projected[index]?.text) item.truncated = true;
1230
- return page;
1231
- }
1232
- function pageFitsNodeTransport(page) {
1233
- return Buffer.byteLength(JSON.stringify({ payloadJSON: JSON.stringify(page) }), "utf8") <= MAX_TRANSCRIPT_PAGE_BYTES;
1234
- }
1235
- /** The legacy API can anchor a turn, but cannot continue within that turn. */
1236
- async function readLegacyCodexTranscriptPage(readTurns, request) {
1237
- return readLegacyCodexHistoryPage(readTurns, request, {
1238
- project: projectTranscriptPage,
1239
- fits: pageFitsNodeTransport
1240
- });
1241
- }
1242
- /** Uses the native store's item cursor whenever that store supports item history. */
1243
- async function readCodexCatalogTranscriptPage(control, request) {
1244
- return readCodexThreadHistoryPage(control, await control.requireEligibleThread(request.threadId), request, {
1245
- project: projectTranscriptPage,
1246
- fits: pageFitsNodeTransport
1247
- });
1248
- }
1249
- //#endregion
1250
- //#region extensions/codex/src/session-catalog-listing.ts
1251
- /** Builds the node-local read-only Codex app-server catalog command. */
1252
- function createCodexSessionCatalogNodeHostCommands(controlFactory, bindingStore) {
1253
- const bindRequest = async (paramsJSON) => {
1254
- const parsed = parseJsonParams(paramsJSON);
1255
- if (!isRecord(parsed)) throw new CatalogParamsError("Codex session catalog parameters must be an object");
1256
- const agentId = readBoundedOptionalString(parsed, "agentId", 256);
1257
- const sourceHomeId = readBoundedOptionalString(parsed, "sourceHomeId", 256);
1258
- const source = await controlFactory.forNode(agentId);
1259
- if (sourceHomeId && sourceHomeId !== source.sourceHomeId) throw new CatalogParamsError("Codex catalog source home changed. Reopen the session from the catalog.");
1260
- const request = { ...parsed };
1261
- delete request.agentId;
1262
- delete request.sourceHomeId;
1263
- return {
1264
- ...source,
1265
- params: request,
1266
- paramsJSON: JSON.stringify(request)
1267
- };
1268
- };
1269
- const transcriptCommand = (command, read) => ({
1270
- command,
1271
- cap: CODEX_APP_SERVER_THREADS_CAPABILITY,
1272
- dangerous: false,
1273
- hasActiveWork: controlFactory.hasActiveWork,
1274
- onDisconnect: controlFactory.disconnect,
1275
- handle: async (paramsJSON) => {
1276
- const request = await bindRequest(paramsJSON);
1277
- const action = readNodeTranscriptParams(request.params);
1278
- try {
1279
- return JSON.stringify(await read(request.control, action));
1280
- } catch (error) {
1281
- if (error instanceof CatalogParamsError) throw error;
1282
- throw new Error("Codex app-server transcript is unavailable", { cause: error });
1283
- }
1284
- }
1285
- });
1286
- const commands = [
1287
- {
1288
- command: CODEX_APP_SERVER_THREADS_LIST_COMMAND,
1289
- cap: CODEX_APP_SERVER_THREADS_CAPABILITY,
1290
- dangerous: false,
1291
- hasActiveWork: controlFactory.hasActiveWork,
1292
- onDisconnect: controlFactory.disconnect,
1293
- handle: async (paramsJSON) => {
1294
- const request = await bindRequest(paramsJSON);
1295
- const pageParams = readPageParams(request.params);
1296
- try {
1297
- const managedThreads = await bindingStore?.managedThreads?.snapshot();
1298
- const sourceHomeId = request.sourceHomeId;
1299
- const managedThreadIds = sourceHomeId ? managedThreads?.get(sourceHomeId) : void 0;
1300
- const page = await listVisiblePage({
1301
- control: request.control,
1302
- cursor: pageParams.cursor,
1303
- cwd: pageParams.cwd,
1304
- excludedThreadIds: managedThreadIds,
1305
- limit: pageParams.limit,
1306
- ...sourceHomeId && bindingStore?.managedThreads ? { onExcludedThread: async ({ threadId, rolloutPath }) => {
1307
- if (!managedThreadIds?.has(threadId)) await bindingStore.managedThreads?.mark({
1308
- sourceHomeId,
1309
- threadId,
1310
- ...rolloutPath ? { rolloutPath } : {}
1311
- });
1312
- } } : {},
1313
- searchTerm: pageParams.searchTerm
1314
- });
1315
- return JSON.stringify({
1316
- ...page,
1317
- sourceHomeId: request.sourceHomeId,
1318
- canContinueCodex: request.transport === "stdio"
1319
- });
1320
- } catch {
1321
- throw new Error("Codex app-server catalog is unavailable");
1322
- }
1323
- }
1324
- },
1325
- transcriptCommand(CODEX_APP_SERVER_THREAD_TURNS_LIST_COMMAND, async (control, action) => {
1326
- await control.requireEligibleThread(action.threadId);
1327
- return parseTranscriptPage(await control.listTurnPage({
1328
- threadId: action.threadId,
1329
- limit: action.limit,
1330
- sortDirection: "desc",
1331
- itemsView: "full",
1332
- ...action.cursor ? { cursor: action.cursor } : {}
1333
- }));
1334
- }),
1335
- transcriptCommand(CODEX_CATALOG_TRANSCRIPT_READ_COMMAND, readCodexCatalogTranscriptPage),
1336
- createCodexTerminalNodeHostCommand(bindRequest),
1337
- createCodexTerminalStartNodeHostCommand()
1338
- ];
1339
- return process.env.OPENCLAW_NODE_EXEC_HOST?.trim().toLowerCase() === "app" ? commands.filter(({ command }) => command !== CODEX_CATALOG_TRANSCRIPT_READ_COMMAND) : commands;
1340
- }
1341
- function readNodeTranscriptParams(value) {
1342
- if (!isRecord(value)) throw new CatalogParamsError("Codex session read parameters must be an object");
1343
- requireOnlyKeys(value, /* @__PURE__ */ new Set([
1344
- "threadId",
1345
- "cursor",
1346
- "limit"
1347
- ]));
1348
- const threadId = readBoundedOptionalString(value, "threadId", 256);
1349
- if (!threadId) throw new CatalogParamsError("threadId is required");
1350
- const cursor = readBoundedOptionalString(value, "cursor", MAX_CURSOR_LENGTH);
1351
- return {
1352
- threadId,
1353
- limit: normalizeLimit(value.limit, "limit", 20, 50),
1354
- ...cursor ? { cursor } : {}
1355
- };
1356
- }
1357
- /** Reads the persisted transcript for a Gateway-local or paired-node Codex session. */
1358
- async function readCodexSessionTranscript(params) {
1359
- const cursor = readControlCursor(params.cursor, "transcript request");
1360
- const limit = normalizeLimit(params.limit, "limit", 20, 50);
1361
- if (params.source || params.hostId === "gateway:local") {
1362
- const page = await readCodexCatalogTranscriptPage(params.control, {
1363
- threadId: params.threadId,
1364
- limit,
1365
- cursor
1366
- });
1367
- return {
1368
- hostId: params.hostId,
1369
- label: params.source?.label ?? "Local Codex",
1370
- threadId: params.threadId,
1371
- ...page
1372
- };
1373
- }
1374
- const nodeId = params.hostId.slice(5);
1375
- const node = (await params.runtime.nodes.list()).nodes.find((candidate) => candidate.nodeId === nodeId && candidate.connected === true && candidate.commands?.includes("codex.appServer.thread.turns.list.v1"));
1376
- if (!node) throw new CatalogParamsError("paired-node Codex session host is offline or unavailable");
1377
- const invoke = async (command, request) => unwrapNodeInvokePayload(await params.runtime.nodes.invoke({
1378
- nodeId,
1379
- command,
1380
- params: {
1381
- agentId: params.agentId,
1382
- threadId: params.threadId,
1383
- ...params.sourceHomeId ? { sourceHomeId: params.sourceHomeId } : {},
1384
- ...request
1385
- },
1386
- timeoutMs: NODE_INVOKE_TIMEOUT_MS,
1387
- scopes: ["operator.write"]
1388
- }));
1389
- const page = node.commands?.includes("codex.sessionCatalog.transcript.read.v1") ? parseCodexCatalogTranscriptPage(await invoke(CODEX_CATALOG_TRANSCRIPT_READ_COMMAND, {
1390
- cursor,
1391
- limit
1392
- })) : await readLegacyCodexTranscriptPage(async ({ cursor: turnCursor, limit: turnLimit }) => parseTranscriptPage(await invoke(CODEX_APP_SERVER_THREAD_TURNS_LIST_COMMAND, {
1393
- cursor: turnCursor,
1394
- limit: turnLimit
1395
- })), {
1396
- threadId: params.threadId,
1397
- cursor,
1398
- limit
1399
- });
1400
- const { nodeLabel } = await import("./session-catalog-node-continue-DjKXHBbi.mjs");
1401
- return {
1402
- hostId: params.hostId,
1403
- label: nodeLabel(node),
1404
- threadId: params.threadId,
1405
- ...page
1406
- };
1407
- }
1408
- //#endregion
1409
- //#region extensions/codex/src/session-upstream-activity.ts
1410
- const CODEX_UPSTREAM_TURN_LIMIT = 100;
1411
- function readMarker(probe) {
1412
- if (!isRecord(probe.marker)) return;
1413
- const turnId = probe.marker.turnId;
1414
- if (turnId !== null && typeof turnId !== "string") return;
1415
- const count = probe.marker.userMessageCount;
1416
- if (count !== void 0 && (typeof count !== "number" || !Number.isSafeInteger(count) || count < 0)) return;
1417
- return {
1418
- turnId,
1419
- ...count === void 0 ? {} : { userMessageCount: count }
1420
- };
1421
- }
1422
- function upstreamConnectionFingerprint(probe) {
1423
- return isRecord(probe.upstreamRef) && typeof probe.upstreamRef.connectionFingerprint === "string" ? probe.upstreamRef.connectionFingerprint : void 0;
1424
- }
1425
- function classifyCodexUpstreamTurns(params) {
1426
- const marker = readMarker(params.probe);
1427
- if (!marker) return;
1428
- const newest = params.turns[0];
1429
- if (!newest?.id) return;
1430
- const markerIndex = marker.turnId === null ? -1 : params.turns.findIndex((turn) => turn.id === marker.turnId);
1431
- const candidateTurns = markerIndex < 0 ? params.turns : params.turns.slice(0, markerIndex + 1);
1432
- const newestUserMessageCount = newest.items.filter((item) => item.type === "userMessage").length;
1433
- if (!(marker.turnId !== newest.id || marker.userMessageCount === void 0 || newestUserMessageCount > marker.userMessageCount)) return;
1434
- const ownTexts = new Set(params.probe.ownRecentUserTexts);
1435
- let humanTurns = 0;
1436
- let occurredAt;
1437
- for (const turn of candidateTurns) {
1438
- const userMessages = turn.items.filter((item) => item.type === "userMessage");
1439
- const alreadySeen = turn.id === marker.turnId ? marker.userMessageCount ?? userMessages.length : 0;
1440
- for (const item of userMessages.slice(alreadySeen)) {
1441
- const texts = normalizeUserMessageTexts(item);
1442
- if (ownTexts.has(texts.join(" ")) || texts.length > 1 && texts.every((text) => ownTexts.has(text))) continue;
1443
- humanTurns += 1;
1444
- if (occurredAt === void 0) {
1445
- const timestampSeconds = turn.completedAt ?? turn.startedAt;
1446
- occurredAt = typeof timestampSeconds === "number" && Number.isFinite(timestampSeconds) ? timestampSeconds * 1e3 : params.now ?? Date.now();
1447
- }
1448
- }
1449
- }
1450
- const activityId = `${newest.id}:${newestUserMessageCount}`;
1451
- return {
1452
- kind: "activity",
1453
- sessionKey: params.probe.sessionKey,
1454
- humanTurns,
1455
- nextMarker: {
1456
- turnId: newest.id,
1457
- userMessageCount: newestUserMessageCount
1458
- },
1459
- ...humanTurns > 0 ? {
1460
- occurredAt: occurredAt ?? params.now ?? Date.now(),
1461
- dedupeId: activityId
1462
- } : {}
1463
- };
1464
- }
1465
- function normalizeUserMessageTexts(item) {
1466
- const typed = item;
1467
- const contentTexts = typed.content?.filter((input) => input.type === "text").map((input) => input.text.trim().replace(/\s+/g, " ")).filter(Boolean);
1468
- return contentTexts?.length ? contentTexts : [(typed.text ?? "").trim().replace(/\s+/g, " ")];
1469
- }
1470
- async function checkCodexUpstreamActivity(probes, control, resolveThreadId = (probe) => probe.threadId) {
1471
- return await control.withPinnedConnection(async (pinned) => {
1472
- const activities = [];
1473
- for (const probe of probes) {
1474
- const fingerprint = upstreamConnectionFingerprint(probe);
1475
- if (probe.upstreamKind !== "codex-app-server" || !fingerprint || fingerprint !== pinned.connectionFingerprint) continue;
1476
- try {
1477
- const threadId = resolveThreadId(probe);
1478
- const page = await pinned.listTurnPage({
1479
- threadId,
1480
- limit: CODEX_UPSTREAM_TURN_LIMIT,
1481
- sortDirection: "desc",
1482
- itemsView: "full"
1483
- }).catch((error) => {
1484
- if (error instanceof CodexAppServerRpcError && error.code === -32600) return;
1485
- throw error;
1486
- });
1487
- if (!page?.data.length && readMarker(probe)) {
1488
- try {
1489
- await pinned.readThread(threadId, false);
1490
- } catch (error) {
1491
- if (isCodexThreadReadMissingError(error, threadId)) activities.push({
1492
- kind: "missing",
1493
- sessionKey: probe.sessionKey
1494
- });
1495
- }
1496
- continue;
1497
- }
1498
- const activity = page && classifyCodexUpstreamTurns({
1499
- probe,
1500
- turns: page.data
1501
- });
1502
- if (activity) activities.push(activity);
1503
- } catch {}
1504
- }
1505
- return activities;
1506
- });
1507
- }
1508
- function createChecker(params) {
1509
- const resolveThreadId = (probe) => {
1510
- const config = params.getRuntimeConfig();
1511
- const sessionId = params.api.runtime.agent.session.getSessionEntry({
1512
- agentId: probe.agentId,
1513
- sessionKey: probe.sessionKey,
1514
- readConsistency: "latest"
1515
- })?.sessionId?.trim();
1516
- if (!sessionId) return probe.threadId;
1517
- const binding = params.bindingStore.read(sessionBindingIdentity({
1518
- sessionId,
1519
- sessionKey: probe.sessionKey,
1520
- config
1521
- }));
1522
- return binding?.connectionScope === "supervision" && binding.supervisionSourceThreadId === probe.threadId ? binding.threadId : probe.threadId;
1523
- };
1524
- return async (probes) => {
1525
- const groups = /* @__PURE__ */ new Map();
1526
- for (const probe of probes) {
1527
- const fingerprint = upstreamConnectionFingerprint(probe);
1528
- if (!fingerprint) continue;
1529
- const control = await params.control.forUpstream(probe.agentId, fingerprint);
1530
- if (!control) continue;
1531
- const key = `${probe.agentId}\0${fingerprint}`;
1532
- const group = groups.get(key) ?? {
1533
- control,
1534
- probes: []
1535
- };
1536
- group.probes.push(probe);
1537
- groups.set(key, group);
1538
- }
1539
- return (await Promise.all([...groups.values()].map((group) => checkCodexUpstreamActivity(group.probes, group.control, resolveThreadId)))).flat();
1540
- };
1541
- }
1542
- //#endregion
1543
- //#region extensions/codex/src/session-catalog-eligibility.ts
1544
- /** Exact identity and native membership are independent of resident retention. */
1545
- async function requireEligibleCodexThread(params) {
1546
- const { requests, threadId } = params;
1547
- const deadline = params.now() + requests.requestTimeoutMs;
1548
- const unverified = () => new CatalogParamsError("Codex session eligibility could not be verified. Refresh the catalog and verify the session in its native Codex home before retrying.");
1549
- const remaining = () => {
1550
- const timeoutMs = Math.ceil(deadline - params.now());
1551
- if (timeoutMs <= 0) throw unverified();
1552
- return timeoutMs;
1553
- };
1554
- const verify = async () => {
1555
- if (params.sourceHomeId && await params.managedThreads?.has(params.sourceHomeId, threadId)) throw unverified();
1556
- remaining();
1557
- const index = await requests.index();
1558
- const root = params.localSessionsRoot;
1559
- if (root && index.get(threadId)?.archived) throw unverified();
1560
- const thread = await requests.readThread(threadId, false, remaining());
1561
- remaining();
1562
- if (thread.id !== threadId || thread.ephemeral === true || !isInteractiveThreadSource(thread.source)) throw unverified();
1563
- if (!root) {
1564
- const { CODEX_CATALOG_NATIVE_PAGE_LIMIT } = await import("./session-catalog-native-projection-CuaFZuQE.mjs").then((n) => n.a);
1565
- const { CODEX_CATALOG_MAX_ROWS } = await import("./session-catalog-limits-DDxOsQeC.mjs").then((n) => n.r);
1566
- let cursor;
1567
- const seenCursors = /* @__PURE__ */ new Set();
1568
- for (;;) {
1569
- const page = await requests.listThreads({
1570
- archived: false,
1571
- limit: CODEX_CATALOG_NATIVE_PAGE_LIMIT,
1572
- modelProviders: [],
1573
- sortKey: "recency_at",
1574
- sortDirection: "desc",
1575
- ...thread.cwd ? { cwd: thread.cwd } : {},
1576
- ...cursor ? { cursor } : {}
1577
- }, remaining());
1578
- remaining();
1579
- const listed = page.data.find((entry) => entry.id === threadId);
1580
- if (listed) {
1581
- if (listed.ephemeral === true || !isInteractiveThreadSource(listed.source)) throw unverified();
1582
- break;
1583
- }
1584
- const nextCursor = readControlCursor(page.nextCursor, "next response");
1585
- if (!nextCursor || seenCursors.has(nextCursor)) throw unverified();
1586
- seenCursors.add(nextCursor);
1587
- if (seenCursors.size > CODEX_CATALOG_MAX_ROWS) {
1588
- const oldest = seenCursors.values().next().value;
1589
- if (oldest !== void 0) seenCursors.delete(oldest);
1590
- }
1591
- cursor = nextCursor;
1592
- }
1593
- }
1594
- if (root) {
1595
- if (!thread.path) throw unverified();
1596
- const metadata = await readCodexSessionMeta(root, thread.path, threadId);
1597
- remaining();
1598
- if (!metadata || !isInteractiveThreadSource(metadata.source) || metadata.originator === "openclaw") throw unverified();
1599
- await index.upsertThread(thread);
1600
- remaining();
1601
- }
1602
- return thread;
1603
- };
1604
- return await withTimeout(verify(), requests.requestTimeoutMs, "Codex session eligibility could not be verified", unverified);
1605
- }
1606
- //#endregion
1607
- //#region extensions/codex/src/session-catalog-control-requests.ts
1608
- function createCodexCatalogRequestSnapshot(requestTimeoutMs, request, index, beginList, catalogRead = false) {
1609
- const read = (method, params, timeoutMs, observation) => {
1610
- const scope = catalogRead ? void 0 : currentCodexCatalogListRequest();
1611
- if (!scope) return request(method, params, timeoutMs, void 0, observation);
1612
- return scope.read(timeoutMs ?? requestTimeoutMs, async (remaining) => {
1613
- const attempt = beginList(scope);
1614
- if (!attempt.allowed) throw attempt.error;
1615
- return await request(method, params, remaining, void 0, observation);
1616
- });
1617
- };
1618
- return {
1619
- index,
1620
- beginList,
1621
- get requestTimeoutMs() {
1622
- return catalogRead ? requestTimeoutMs : currentCodexCatalogListRequest()?.remaining(requestTimeoutMs) ?? requestTimeoutMs;
1623
- },
1624
- listThreads: (params, timeoutMs, observation) => read(CODEX_CONTROL_METHODS.listThreads, params, timeoutMs, observation),
1625
- listThreadTurns: (params) => read(CODEX_CONTROL_METHODS.listThreadTurns, params),
1626
- listThreadItems: (params) => read(CODEX_CONTROL_METHODS.listThreadItems, params),
1627
- forkThread: (params, assertCurrent) => request(CODEX_CONTROL_METHODS.forkThread, assertCodexThreadForkParams(params), void 0, assertCurrent),
1628
- readThread: async (threadId, includeTurns, timeoutMs) => (await read(CODEX_CONTROL_METHODS.readThread, {
1629
- threadId,
1630
- includeTurns
1631
- }, timeoutMs)).thread,
1632
- archiveThread: async (threadId, assertCurrent) => {
1633
- await request(CODEX_CONTROL_METHODS.archiveThread, { threadId }, void 0, assertCurrent);
1634
- }
1635
- };
1636
- }
1637
- function createCodexSessionCatalogControlFromRequests(params) {
1638
- return {
1639
- forkContext: params.forkContext,
1640
- ...params.clientId ? { clientId: params.clientId } : {},
1641
- ...params.connectionFingerprint ? { connectionFingerprint: params.connectionFingerprint } : {},
1642
- withPinnedConnection: params.withPinnedConnection,
1643
- async initialize() {
1644
- await (await params.createRequestSnapshot().index()).initialize();
1645
- },
1646
- requireEligibleThread: (threadId) => requireEligibleCodexThread({
1647
- threadId,
1648
- requests: params.createRequestSnapshot(),
1649
- localSessionsRoot: params.localSessionsRoot,
1650
- sourceHomeId: params.sourceHomeId,
1651
- managedThreads: params.managedThreads,
1652
- now: params.now
1653
- }),
1654
- retireConnection: params.retireConnection,
1655
- async listPage(pageParams) {
1656
- readControlCursor(pageParams.cursor, "request");
1657
- const query = readPageParams(pageParams);
1658
- return await withCodexCatalogListRequest(async (request) => {
1659
- const requests = params.createRequestSnapshot();
1660
- const timeoutMs = Math.min(requests.requestTimeoutMs, 5e3);
1661
- const deadline = request.constrainDeadline(performance.now() + timeoutMs);
1662
- return await (await withTimeout(requests.index(), request.remaining(timeoutMs), "Codex session catalog is still loading", () => new CodexCatalogLoadingError())).list(query, deadline);
1663
- });
1664
- },
1665
- async listDescendantPage(listParams) {
1666
- const requests = params.createRequestSnapshot();
1667
- return await requests.listThreads(listParams, requests.requestTimeoutMs);
1668
- },
1669
- async readThread(threadId, includeTurns = false) {
1670
- return await params.createRequestSnapshot().readThread(threadId, includeTurns);
1671
- },
1672
- async listTurnPage(listParams) {
1673
- return await params.createRequestSnapshot().listThreadTurns(listParams);
1674
- },
1675
- listItemPage: (listParams) => params.createRequestSnapshot().listThreadItems(listParams),
1676
- async forkThread(forkParams, assertCurrent) {
1677
- const requests = params.createRequestSnapshot();
1678
- const index = forkParams.ephemeral === true ? void 0 : await requests.index();
1679
- const response = await requests.forkThread(forkParams, assertCurrent);
1680
- if (index && !index.get(response.thread.id)) await index.upsertThread(response.thread);
1681
- return response;
1682
- },
1683
- async archiveThread(threadId, assertCurrent) {
1684
- const requests = params.createRequestSnapshot();
1685
- const index = await requests.index();
1686
- await requests.archiveThread(threadId, assertCurrent);
1687
- index.archive(threadId);
1688
- }
1689
- };
1690
- }
1691
- //#endregion
1692
- //#region extensions/codex/src/session-catalog-homes.ts
1693
- /** Discovers path facts on demand; runtime projections belong only to their requesting owner. */
1694
- function createCodexCatalogHomeResolver(params) {
1695
- const env = params.env ?? process.env;
1696
- const generations = /* @__PURE__ */ new WeakMap();
1697
- let lastConfig = params.config;
1698
- const currentConfig = () => lastConfig = params.getRuntimeConfig() ?? lastConfig;
1699
- const generation = () => {
1700
- const config = currentConfig();
1701
- let current = generations.get(config);
1702
- if (!current) {
1703
- current = {
1704
- config,
1705
- assertCurrent: () => {
1706
- if (currentConfig() !== config) throw new CatalogParamsError("Codex session catalog configuration changed; retry the request");
1707
- },
1708
- pluginConfig: params.getPluginConfig(),
1709
- agentDirs: /* @__PURE__ */ new Map(),
1710
- paths: /* @__PURE__ */ new Map(),
1711
- directories: /* @__PURE__ */ new Set()
1712
- };
1713
- generations.set(config, current);
1714
- }
1715
- return current;
1716
- };
1717
- const agentIds = (snapshot) => snapshot.agentIds ??= listAgentIds(snapshot.config).toSorted((a, b) => a.localeCompare(b));
1718
- const agentDir = (snapshot, agentId) => {
1719
- let directory = snapshot.agentDirs.get(agentId);
1720
- if (!directory) {
1721
- directory = resolveAgentDir(snapshot.config, agentId, env);
1722
- snapshot.agentDirs.set(agentId, directory);
1723
- }
1724
- return directory;
1725
- };
1726
- const homePath = async (snapshot, value) => {
1727
- const cached = snapshot.paths.get(value);
1728
- if (cached !== void 0) return cached;
1729
- const resolved = path.resolve(value);
1730
- const discovery = canonicalPathFromExistingAncestor(resolved).catch(() => resolved).then(async (canonical) => {
1731
- if (await fs.stat(canonical).then((stat) => stat.isDirectory(), () => false)) snapshot.directories.add(value);
1732
- snapshot.paths.set(value, canonical);
1733
- return canonical;
1734
- });
1735
- snapshot.paths.set(value, discovery);
1736
- return discovery;
1737
- };
1738
- const sharedCandidates = (snapshot) => snapshot.candidates ??= (async () => {
1739
- const candidates = [];
1740
- const seen = /* @__PURE__ */ new Set();
1741
- const append = async (value, label) => {
1742
- const codexHome = await homePath(snapshot, value);
1743
- if (!snapshot.directories.has(value) || seen.has(codexHome)) return;
1744
- seen.add(codexHome);
1745
- candidates.push({
1746
- codexHome,
1747
- label: `Local Codex · ${label ?? path.basename(codexHome)}`
1748
- });
1749
- };
1750
- for (const id of agentIds(snapshot)) {
1751
- await scheduler.yield();
1752
- const directory = await homePath(snapshot, agentDir(snapshot, id));
1753
- await append(resolveCodexAppServerHomeDir(directory), id);
1754
- if (candidates.length === 100) return candidates;
1755
- }
1756
- for (const entry of readCodexPluginConfig(snapshot.pluginConfig).sessionCatalog?.homes ?? []) {
1757
- await scheduler.yield();
1758
- const { path: home, label } = typeof entry === "string" ? { path: entry } : entry;
1759
- await append(home, label);
1760
- if (candidates.length === 100) break;
1761
- }
1762
- return candidates;
1763
- })().then((candidates) => snapshot.candidates = candidates, (error) => {
1764
- snapshot.candidates = void 0;
1765
- throw error;
1766
- });
1767
- const prepareAgentHomes = async (snapshot, agentId, fleet) => {
1768
- await scheduler.yield();
1769
- snapshot.assertCurrent();
1770
- if (!agentIds(snapshot).includes(agentId)) return [];
1771
- const ownerAgentDir = await homePath(snapshot, agentDir(snapshot, agentId));
1772
- const base = params.resolveRuntimeOptions({
1773
- config: snapshot.config,
1774
- pluginConfig: snapshot.pluginConfig,
1775
- agentDir: ownerAgentDir,
1776
- env
1777
- });
1778
- const processHomeConfigured = Boolean(env.CODEX_HOME?.trim());
1779
- const candidates = [{
1780
- codexHome: await homePath(snapshot, resolveCodexAppServerLocalHomeDir(base.start, ownerAgentDir, env)),
1781
- label: "Local Codex",
1782
- usesProcessHomeFallback: base.start.transport === "stdio" && base.start.homeScope === "user" && !processHomeConfigured
1783
- }];
1784
- if (fleet && base.start.transport === "stdio") {
1785
- candidates.push({
1786
- codexHome: await homePath(snapshot, resolveCodexAppServerUserHomeDir(env)),
1787
- label: "Local Codex · user",
1788
- usesProcessHomeFallback: !processHomeConfigured
1789
- });
1790
- const ownerHome = resolveCodexAppServerHomeDir(ownerAgentDir);
1791
- const codexHome = await homePath(snapshot, ownerHome);
1792
- if (snapshot.directories.has(ownerHome)) candidates.push({
1793
- codexHome,
1794
- label: `Local Codex · ${agentId}`
1795
- });
1796
- candidates.push(...await sharedCandidates(snapshot));
1797
- }
1798
- snapshot.assertCurrent();
1799
- const homes = [];
1800
- const seen = /* @__PURE__ */ new Set();
1801
- for (const candidate of candidates) {
1802
- if (seen.has(candidate.codexHome)) continue;
1803
- seen.add(candidate.codexHome);
1804
- const sourceHomeId = codexCatalogHomeIdFromCanonicalPath(candidate.codexHome);
1805
- const primary = homes.length === 0;
1806
- homes.push({
1807
- assertCurrent: snapshot.assertCurrent.bind(snapshot),
1808
- sourceHomeId,
1809
- hostId: primary ? CODEX_LOCAL_SESSION_HOST_ID : `${CODEX_LOCAL_SESSION_HOST_ID}:${sourceHomeId}`,
1810
- label: candidate.label,
1811
- agentDir: ownerAgentDir,
1812
- appServer: base.start.transport !== "stdio" ? base : {
1813
- ...base,
1814
- start: {
1815
- ...base.start,
1816
- codexHome: candidate.codexHome,
1817
- ...!primary ? {
1818
- homeScope: "user",
1819
- env: {
1820
- ...base.start.env,
1821
- CODEX_HOME: candidate.codexHome
1822
- }
1823
- } : {}
1824
- }
1825
- },
1826
- ...base.connectionClass === "remote" ? {} : { localSessionsRoot: path.join(candidate.codexHome, "sessions") },
1827
- usesProcessHomeFallback: candidate.usesProcessHomeFallback ?? false
1828
- });
1829
- if (homes.length === 100) break;
1830
- }
1831
- return homes;
1832
- };
1833
- setCodexCatalogConnectionHomeResolver(async (directory) => {
1834
- const snapshot = generation();
1835
- for (const id of agentIds(snapshot)) {
1836
- await scheduler.yield();
1837
- if (agentDir(snapshot, id) === directory) return prepareAgentHomes(snapshot, id, true);
1838
- }
1839
- snapshot.assertCurrent();
1840
- return [];
1841
- });
1842
- return {
1843
- forAgent: (agentId) => prepareAgentHomes(generation(), agentId, true),
1844
- async forNode(requestedAgentId) {
1845
- const snapshot = generation();
1846
- const configured = readCodexPluginConfig(snapshot.pluginConfig).appServer;
1847
- if (configured?.homeScope === "agent" || configured?.transport && configured.transport !== "stdio") {
1848
- const agentId = resolveSessionAgentIdsStrict({
1849
- config: snapshot.config,
1850
- agentId: requestedAgentId
1851
- }).sessionAgentId;
1852
- const source = (await prepareAgentHomes(snapshot, agentId, false))[0];
1853
- if (!source) throw new CatalogParamsError(`unknown Codex session catalog agent: ${agentId}`);
1854
- return {
1855
- ...source,
1856
- agentId,
1857
- codexHome: resolveCodexAppServerLocalHomeDir(source.appServer.start, source.agentDir, env)
1858
- };
1859
- }
1860
- const codexHome = await homePath(snapshot, resolveCodexAppServerUserHomeDir(env));
1861
- snapshot.assertCurrent();
1862
- const appServer = params.resolveRuntimeOptions({
1863
- pluginConfig: snapshot.pluginConfig,
1864
- config: snapshot.config,
1865
- env
1866
- });
1867
- return {
1868
- assertCurrent: snapshot.assertCurrent.bind(snapshot),
1869
- sourceHomeId: codexCatalogHomeIdFromCanonicalPath(codexHome),
1870
- codexHome,
1871
- localSessionsRoot: path.join(codexHome, "sessions"),
1872
- appServer: {
1873
- ...appServer,
1874
- start: {
1875
- ...appServer.start,
1876
- env: {
1877
- ...appServer.start.env,
1878
- CODEX_HOME: codexHome
1879
- }
1880
- }
1881
- }
1882
- };
1883
- }
1884
- };
1885
- }
1886
- //#endregion
1887
- //#region extensions/codex/src/session-catalog-source-backoff.ts
1888
- const INITIAL_BACKOFF_MS = 5e3;
1889
- const MAX_BACKOFF_MS = 6e4;
1890
- /** Source health is separate from query-keyed page sharing and cached page delivery. */
1891
- var CodexCatalogSourceBackoff = class {
1892
- constructor(now) {
1893
- this.now = now;
1894
- this.sourcesByConfig = /* @__PURE__ */ new WeakMap();
1895
- }
1896
- begin(config, agentId, sourceHomeId, scope) {
1897
- let sources = this.sourcesByConfig.get(config);
1898
- if (!sources) {
1899
- sources = /* @__PURE__ */ new Map();
1900
- this.sourcesByConfig.set(config, sources);
1901
- }
1902
- const key = JSON.stringify([agentId, sourceHomeId ?? null]);
1903
- if (scope) return scope.attempt(sources, key, () => this.begin(config, agentId, sourceHomeId));
1904
- let state = sources.get(key);
1905
- if (!state) {
1906
- state = {};
1907
- sources.set(key, state);
1908
- }
1909
- const failure = state.failure;
1910
- if (failure && (failure.probing || failure.retryAt > this.now())) return {
1911
- allowed: false,
1912
- error: failure.error
1913
- };
1914
- if (failure) failure.probing = true;
1915
- return {
1916
- allowed: true,
1917
- resolved: () => {
1918
- if (sources.get(key) === state) sources.set(key, {});
1919
- },
1920
- rejected: (error) => {
1921
- if (sources.get(key) !== state) return;
1922
- if (error instanceof CatalogParamsError || error instanceof Error && error.name === "AbortError" || error instanceof CodexAppServerRpcError && (error.code === -32600 || error.code === -32602)) {
1923
- if (failure) failure.probing = false;
1924
- return;
1925
- }
1926
- const delayMs = findCodexAppServerSpawnError(error) ? Infinity : failure ? Math.min(failure.delayMs * 2 || INITIAL_BACKOFF_MS, MAX_BACKOFF_MS) : 0;
1927
- sources.set(key, { failure: {
1928
- error,
1929
- delayMs,
1930
- retryAt: this.now() + delayMs,
1931
- probing: false
1932
- } });
1933
- },
1934
- abandoned: () => {
1935
- if (sources.get(key) === state && failure) failure.probing = false;
1936
- }
1937
- };
1938
- }
1939
- };
1940
- //#endregion
1941
- //#region extensions/codex/src/session-catalog-control.ts
1942
- /** Builds the passive catalog over the Codex plugin's canonical shared client. */
1943
- function createCodexSessionCatalogControl(params) {
1944
- const now = params.now ?? Date.now;
1945
- const sourceBackoff = new CodexCatalogSourceBackoff(now);
1946
- const noConfig = {};
1947
- const resolveRuntimeOptions = (options) => {
1948
- const runtime = params.resolveRuntimeOptions(options);
1949
- return runtime.start.transport === "stdio" && runtime.start.commandSource === "managed" ? {
1950
- ...runtime,
1951
- start: {
1952
- ...runtime.start,
1953
- managedCommandOrder: "package-only"
1954
- }
1955
- } : runtime;
1956
- };
1957
- const homeResolver = createCodexCatalogHomeResolver({
1958
- config: params.config ?? {},
1959
- getRuntimeConfig: params.getRuntimeConfig,
1960
- getPluginConfig: params.getPluginConfig,
1961
- resolveRuntimeOptions,
1962
- ...params.env ? { env: params.env } : {}
1963
- });
1964
- const requestOptionsByConfig = /* @__PURE__ */ new WeakMap();
1965
- const indexes = /* @__PURE__ */ new Map();
1966
- const retiringState = /* @__PURE__ */ new Map();
1967
- const directHomes = /* @__PURE__ */ new Map();
1968
- const residentRequests = /* @__PURE__ */ new Set();
1969
- let generation = params.getRuntimeConfig();
1970
- let residentEpoch = 0;
1971
- let closed = false;
1972
- let runBackground = (run) => run();
1973
- let retiring;
1974
- const retireIndexes = () => {
1975
- residentEpoch++;
1976
- const closing = [];
1977
- for (const [homeId, index] of indexes) {
1978
- const writes = index.retire().finally(() => {
1979
- if (retiringState.get(homeId) === writes) retiringState.delete(homeId);
1980
- });
1981
- retiringState.set(homeId, writes);
1982
- closing.push(writes, index.close());
1983
- }
1984
- indexes.clear();
1985
- directHomes.clear();
1986
- const drain = Promise.allSettled([retiring, ...closing]).then(() => {
1987
- if (retiring === drain) retiring = void 0;
1988
- });
1989
- retiring = drain;
1990
- return drain;
1991
- };
1992
- const resolveResident = async (agentId, source) => {
1993
- if (closed) throw new Error("Codex resident catalog is closed");
1994
- const config = params.getRuntimeConfig();
1995
- if (generation !== config) {
1996
- generation = config;
1997
- retireIndexes();
1998
- }
1999
- const epoch = residentEpoch;
2000
- const runtime = source?.appServer ?? resolveRuntimeOptions({ pluginConfig: params.getPluginConfig() });
2001
- const requestOptions = resolveRequestOptions(runtime.start, agentId, source);
2002
- const key = source?.sourceHomeId ?? agentId ?? "";
2003
- let home = directHomes.get(key);
2004
- if (!home) {
2005
- home = codexCatalogResidentHomeKey({
2006
- startOptions: requestOptions.startOptions,
2007
- agentDir: requestOptions.agentDir,
2008
- sourceHomeId: source?.sourceHomeId
2009
- });
2010
- directHomes.set(key, home);
2011
- }
2012
- const homeId = await home;
2013
- await retiringState.get(homeId);
2014
- if (closed || generation !== config || residentEpoch !== epoch) throw new Error("Codex catalog configuration changed");
2015
- let index = indexes.get(homeId);
2016
- if (!index) {
2017
- const [{ CodexCatalogIndex }, { canReuseCodexCatalogPreview, projectCodexCatalogDeltaPage, projectCodexCatalogPage }] = await Promise.all([import("./session-catalog-index-DwJjnF5k.mjs"), import("./session-catalog-projection-CGfzfP93.mjs")]);
2018
- source?.assertCurrent();
2019
- if (closed || generation !== config || residentEpoch !== epoch) throw new Error("Codex catalog configuration changed");
2020
- index = indexes.get(homeId);
2021
- if (index) return index;
2022
- const root = source?.localSessionsRoot ?? (runtime.connectionClass !== "remote" ? path.join(resolveCodexAppServerLocalHomeDir(requestOptions.startOptions, requestOptions.agentDir, params.env), "sessions") : void 0);
2023
- let nativeAttempt;
2024
- const readNativePage = async (query, remainingRows, project, foreground) => {
2025
- const requests = createRequestSnapshot(agentId, source, true, query.useStateDbOnly ? (thread) => {
2026
- const row = index?.get(thread.id);
2027
- return canReuseCodexCatalogPreview(row, thread) ? row?.preview : void 0;
2028
- } : void 0, remainingRows);
2029
- const attempt = foreground ? requests.beginList(foreground) : query.cursor && nativeAttempt ? nativeAttempt : requests.beginList();
2030
- if (!foreground) nativeAttempt = attempt;
2031
- if (!attempt.allowed) throw attempt.error;
2032
- const diagnostics = startCodexCatalogPageDiagnostics("cold");
2033
- if (diagnostics) diagnostics.fields.controlRequestCalls = 1;
2034
- const observation = startCodexCatalogControlRequestDiagnostics(diagnostics);
2035
- let outcome = "rejected";
2036
- try {
2037
- const started = performance.now();
2038
- let response;
2039
- try {
2040
- response = await requests.listThreads(query, foreground?.remaining(requests.requestTimeoutMs) ?? requests.requestTimeoutMs, observation);
2041
- } finally {
2042
- if (diagnostics) {
2043
- const elapsed = performance.now() - started;
2044
- diagnostics.fields.inclusiveControlRequestWaitMs = elapsed;
2045
- diagnostics.fields.inclusiveControlRequestWaitMaxMs = elapsed;
2046
- }
2047
- }
2048
- foreground?.assertActive();
2049
- const page = await project(response, diagnostics);
2050
- foreground?.assertActive();
2051
- outcome = "resolved";
2052
- return page;
2053
- } catch (error) {
2054
- observation?.rejected();
2055
- throw error;
2056
- } finally {
2057
- observation?.close();
2058
- diagnostics?.finish(outcome);
2059
- }
2060
- };
2061
- index = new CodexCatalogIndex({
2062
- homeId,
2063
- requestTimeoutMs: runtime.requestTimeoutMs,
2064
- runBackground: (run) => runBackground(run),
2065
- localSessionsRoot: root,
2066
- state: params.openResidentState?.(homeId),
2067
- runNativeWalk: async (run) => {
2068
- try {
2069
- const result = await run();
2070
- if (nativeAttempt?.allowed) nativeAttempt.resolved();
2071
- return result;
2072
- } catch (error) {
2073
- if (nativeAttempt?.allowed) nativeAttempt.rejected(error);
2074
- throw error;
2075
- } finally {
2076
- nativeAttempt = void 0;
2077
- }
2078
- },
2079
- assertCurrent: () => {
2080
- source?.assertCurrent();
2081
- if (closed || params.getRuntimeConfig() !== config || residentEpoch !== epoch) throw new Error("Codex catalog configuration changed");
2082
- },
2083
- readNative: (query, remainingRows, foreground) => readNativePage(query, Math.min(64, remainingRows), async (response, diagnostics) => {
2084
- const { sanitizeTerminalText } = await import("openclaw/plugin-sdk/text-chunking");
2085
- const bounded = {
2086
- ...response,
2087
- data: response.data.slice(0, remainingRows)
2088
- };
2089
- const projection = {
2090
- localSessionsRoot: root,
2091
- sanitize: sanitizeTerminalText,
2092
- diagnostics
2093
- };
2094
- return query.useStateDbOnly ? await projectCodexCatalogDeltaPage(bounded, {
2095
- ...projection,
2096
- getRow: (threadId) => index?.get(threadId)
2097
- }) : await projectCodexCatalogPage(bounded, projection);
2098
- }, foreground)
2099
- });
2100
- indexes.set(homeId, index);
2101
- }
2102
- return index;
2103
- };
2104
- const residentFor = (agentId, source) => {
2105
- const request = resolveResident(agentId, source);
2106
- residentRequests.add(request);
2107
- const release = () => residentRequests.delete(request);
2108
- request.then(release, release);
2109
- return request;
2110
- };
2111
- const resolveRequestOptions = (startOptions, agentId, source) => {
2112
- source?.assertCurrent();
2113
- const runtimeConfig = params.getRuntimeConfig();
2114
- const agentDir = source?.agentDir ?? (agentId ? resolveAgentDir(runtimeConfig ?? {}, agentId) : void 0);
2115
- const resolvedStartOptions = source?.appServer.start ?? startOptions;
2116
- if (!runtimeConfig) return {
2117
- agentDir,
2118
- config: void 0,
2119
- startOptions: structuredClone(resolvedStartOptions)
2120
- };
2121
- let snapshot = requestOptionsByConfig.get(runtimeConfig);
2122
- const cacheKey = `${agentId ?? ""}\0${source?.sourceHomeId ?? ""}`;
2123
- const cached = snapshot?.byAgent.get(cacheKey);
2124
- if (cached) return cached;
2125
- if (!snapshot) {
2126
- snapshot = {
2127
- config: structuredClone(runtimeConfig),
2128
- byAgent: /* @__PURE__ */ new Map()
2129
- };
2130
- requestOptionsByConfig.set(runtimeConfig, snapshot);
2131
- }
2132
- const resolved = {
2133
- agentDir,
2134
- config: snapshot.config,
2135
- startOptions: structuredClone(resolvedStartOptions)
2136
- };
2137
- snapshot.byAgent.set(cacheKey, resolved);
2138
- return resolved;
2139
- };
2140
- const createRequestSnapshot = (agentId, source, catalogPreview, catalogPreviewCache, catalogRows) => {
2141
- const pluginConfig = params.getPluginConfig();
2142
- const runtime = source?.appServer ?? resolveRuntimeOptions({ pluginConfig });
2143
- const requestOptions = resolveRequestOptions(runtime.start, agentId, source);
2144
- return createCodexCatalogRequestSnapshot(runtime.requestTimeoutMs, async (method, requestParams, timeoutMs, assertCurrent, observation) => {
2145
- const { codexControlRequest } = await import("./command-rpc-skzRq4wD.mjs").then((n) => n.n);
2146
- return await codexControlRequest(pluginConfig, method, requestParams, {
2147
- ...requestOptions,
2148
- authProfileId: null,
2149
- assertCurrent,
2150
- ...catalogPreview && method === CODEX_CONTROL_METHODS.listThreads ? {
2151
- catalogPreview,
2152
- catalogRows,
2153
- ...catalogPreviewCache ? { catalogPreviewCache } : {}
2154
- } : {},
2155
- ...observation ? { controlObservation: observation } : {},
2156
- ...timeoutMs === void 0 ? {} : { timeoutMs }
2157
- });
2158
- }, () => residentFor(agentId, source), (request) => sourceBackoff.begin(requestOptions.config ?? noConfig, agentId, source?.sourceHomeId, request), catalogPreview === true);
2159
- };
2160
- const forRequest = (agentId, source) => {
2161
- source?.assertCurrent();
2162
- const withPinnedConnection = async (run) => {
2163
- const pluginConfig = params.getPluginConfig();
2164
- const runtime = source?.appServer ?? resolveRuntimeOptions({ pluginConfig });
2165
- const { agentDir, config: runtimeConfig, startOptions } = resolveRequestOptions(runtime.start, agentId, source);
2166
- let catalogIndex;
2167
- const { getLeasedSharedCodexAppServerClient, releaseLeasedSharedCodexAppServerClient, retireSharedCodexAppServerClientIfCurrent } = await import("./shared-client-CJCTeFpQ.mjs").then((n) => n.v);
2168
- const { resolveCodexAppServerClientInstanceId } = await import("./client-qyUBJlGZ.mjs").then((n) => n.n);
2169
- const { requestCodexAppServerClientJson } = await import("./request-BZOfsSXW.mjs").then((n) => n.a);
2170
- const client = await getLeasedSharedCodexAppServerClient({
2171
- agentDir,
2172
- config: runtimeConfig,
2173
- startOptions,
2174
- authProfileId: null,
2175
- timeoutMs: currentCodexCatalogListRequest()?.remaining(runtime.requestTimeoutMs) ?? runtime.requestTimeoutMs
2176
- });
2177
- try {
2178
- const requests = createCodexCatalogRequestSnapshot(runtime.requestTimeoutMs, async (method, requestParams, timeoutMs, assertCurrent, observation) => await requestCodexAppServerClientJson({
2179
- client,
2180
- method,
2181
- requestParams,
2182
- config: runtimeConfig,
2183
- timeoutMs: timeoutMs ?? runtime.requestTimeoutMs,
2184
- assertCurrent,
2185
- ...observation ? { controlObservation: observation } : {}
2186
- }), () => catalogIndex ??= residentFor(agentId, source), (request) => sourceBackoff.begin(runtimeConfig ?? noConfig, agentId, source?.sourceHomeId, request));
2187
- const pinnedControl = createCodexSessionCatalogControlFromRequests({
2188
- forkContext: agentDir ? {
2189
- client,
2190
- appServer: runtime,
2191
- pluginConfig,
2192
- agentDir,
2193
- localSessionsRoot: source?.localSessionsRoot
2194
- } : void 0,
2195
- clientId: resolveCodexAppServerClientInstanceId(client),
2196
- retireConnection: () => {
2197
- retireSharedCodexAppServerClientIfCurrent(client);
2198
- },
2199
- connectionFingerprint: buildCodexAppServerConnectionFingerprint(runtime, agentDir),
2200
- createRequestSnapshot: () => requests,
2201
- ...source?.localSessionsRoot ? { localSessionsRoot: source.localSessionsRoot } : {},
2202
- sourceHomeId: source?.sourceHomeId,
2203
- managedThreads: params.managedThreads,
2204
- now,
2205
- withPinnedConnection: async (nestedRun) => await nestedRun(pinnedControl)
2206
- });
2207
- return await run(pinnedControl);
2208
- } finally {
2209
- releaseLeasedSharedCodexAppServerClient(client);
2210
- }
2211
- };
2212
- const control = createCodexSessionCatalogControlFromRequests({
2213
- createRequestSnapshot: () => createRequestSnapshot(agentId, source),
2214
- ...source?.localSessionsRoot ? { localSessionsRoot: source.localSessionsRoot } : {},
2215
- now,
2216
- withPinnedConnection
2217
- });
2218
- return {
2219
- ...control,
2220
- requireEligibleThread: (threadId) => withPinnedConnection((pinned) => pinned.requireEligibleThread(threadId)),
2221
- async listPage(pageParams) {
2222
- source?.assertCurrent();
2223
- return await control.listPage(pageParams);
2224
- }
2225
- };
2226
- };
2227
- const forUpstream = async (agentId, connectionFingerprint) => {
2228
- const source = (await homeResolver.forAgent(agentId)).find((home) => buildCodexAppServerConnectionFingerprint(home.appServer, home.agentDir) === connectionFingerprint);
2229
- return source ? forRequest(agentId, source) : void 0;
2230
- };
2231
- return {
2232
- hasActiveWork: () => residentRequests.size > 0 || retiring !== void 0 || hasActiveSharedCodexAppServerWork() || [...indexes.values()].some((index) => index.hasActiveWork()),
2233
- async disconnect() {
2234
- await retireIndexes();
2235
- await Promise.allSettled(residentRequests);
2236
- const clients = getSharedCodexAppServerClientState();
2237
- if (clients.liveClients.size > 0 || clients.startup.pending.size > 0) {
2238
- const { clearSharedCodexAppServerClientAndWait } = await import("./shared-client-CJCTeFpQ.mjs").then((n) => n.v);
2239
- await clearSharedCodexAppServerClientAndWait();
2240
- }
2241
- },
2242
- async start() {
2243
- const serviceScope = AsyncLocalStorage.snapshot();
2244
- runBackground = (run) => serviceScope(run);
2245
- },
2246
- async stop() {
2247
- closed = true;
2248
- await retireIndexes();
2249
- await Promise.allSettled(residentRequests);
2250
- },
2251
- forRequest,
2252
- forUpstream,
2253
- homesForAgent: homeResolver.forAgent,
2254
- async forNode(agentId) {
2255
- const source = await homeResolver.forNode(agentId);
2256
- return {
2257
- assertCurrent: () => source.assertCurrent(),
2258
- control: forRequest(source.agentId, source),
2259
- sourceHomeId: source.sourceHomeId,
2260
- codexHome: source.codexHome,
2261
- transport: source.appServer.start.transport
2262
- };
2263
- }
2264
- };
2265
- }
2266
- //#endregion
2267
- //#region extensions/codex/src/session-catalog.ts
2268
- /** Allows read-only catalog and transcript commands on supported paired-node platforms. */
2269
- function createCodexSessionCatalogNodeInvokePolicies() {
2270
- return [{
2271
- commands: [
2272
- CODEX_APP_SERVER_THREADS_LIST_COMMAND,
2273
- CODEX_APP_SERVER_THREAD_TURNS_LIST_COMMAND,
2274
- CODEX_CATALOG_TRANSCRIPT_READ_COMMAND,
2275
- CODEX_TERMINAL_RESUME_COMMAND,
2276
- CODEX_TERMINAL_START_COMMAND
2277
- ],
2278
- defaultPlatforms: [
2279
- "macos",
2280
- "linux",
2281
- "windows"
2282
- ],
2283
- handle: (context) => {
2284
- if (context.command === "codex.terminal.start.v1") return context.client?.scopes?.includes("operator.admin") && context.config.gateway?.cliAgents?.enabled === true && context.config.gateway?.terminal?.enabled !== false ? { ok: true } : {
2285
- ok: false,
2286
- message: "Native terminal start requires operator.admin and enabled CLI agents and terminals"
2287
- };
2288
- return context.command === "codex.terminal.resume.v1" ? { ok: true } : context.invokeNode();
2289
- }
2290
- }];
2291
- }
2292
- function toGenericCatalogHost(host, localTerminalAvailable) {
2293
- const local = isLocalCodexCatalogHost(host.hostId);
2294
- return {
2295
- hostId: host.hostId,
2296
- label: host.label,
2297
- kind: host.kind,
2298
- connected: host.connected,
2299
- ...host.pending ? { pending: true } : {},
2300
- ...host.nodeId ? { nodeId: host.nodeId } : {},
2301
- sessions: host.sessions.map((session) => {
2302
- const continuableStatus = !session.archived && (session.status === "idle" || session.status === "notLoaded");
2303
- const canContinue = (local || host.canContinueCodex === true) && continuableStatus && isInteractiveThreadSource(session.source);
2304
- const canArchive = local && continuableStatus && isInteractiveThreadSource(session.source);
2305
- const canOpenTerminal = isInteractiveThreadSource(session.source) && (local ? localTerminalAvailable : host.canOpenTerminalCodex === true);
2306
- const name = session.name ?? session.fallbackName;
2307
- return {
2308
- threadId: session.threadId,
2309
- ...session.sourceHomeId ? { sourceHomeId: session.sourceHomeId } : {},
2310
- ...name ? { name } : {},
2311
- ...session.cwd ? { cwd: session.cwd } : {},
2312
- status: session.status,
2313
- ...session.createdAt != null ? { createdAt: session.createdAt } : {},
2314
- ...session.updatedAt != null ? { updatedAt: session.updatedAt } : {},
2315
- ...session.recencyAt != null ? { recencyAt: session.recencyAt } : {},
2316
- ...session.source ? { source: session.source } : {},
2317
- ...session.modelProvider ? { modelProvider: session.modelProvider } : {},
2318
- ...session.cliVersion ? { cliVersion: session.cliVersion } : {},
2319
- ...session.gitBranch ? { gitBranch: session.gitBranch } : {},
2320
- archived: session.archived,
2321
- ...session.sessionKey ? { sessionKey: session.sessionKey } : {},
2322
- canContinue,
2323
- canArchive,
2324
- canOpenTerminal
2325
- };
2326
- }),
2327
- ...host.nextCursor ? { nextCursor: host.nextCursor } : {},
2328
- ...host.error ? { error: host.error } : {}
2329
- };
2330
- }
2331
- function isLocalCodexCatalogHost(hostId) {
2332
- return hostId === "gateway:local" || hostId.startsWith(`gateway:local:`);
2333
- }
2334
- function resolveLocalCatalogHomeForThread(params) {
2335
- if (params.homes.length === 0) throw new CatalogParamsError("local Codex sessions are unavailable in isolated state");
2336
- const exact = params.sourceHomeId ? params.homes.filter((home) => home.sourceHomeId === params.sourceHomeId) : params.homes.filter((home) => home.hostId === params.hostId);
2337
- if (exact.length === 0 || params.sourceHomeId && exact[0]?.hostId !== params.hostId) throw new CatalogParamsError("Codex session source home is unavailable");
2338
- return exact[0];
2339
- }
2340
- function withCatalogListScope(initialize) {
2341
- let create = initialize;
2342
- let operation;
2343
- let scope;
2344
- let running = false;
2345
- let closed = false;
2346
- let completed = false;
2347
- return {
2348
- async next() {
2349
- if (closed || running) throw new Error("Codex catalog list operation cannot advance");
2350
- running = true;
2351
- try {
2352
- scope ??= createCodexCatalogListScope();
2353
- return await scope.run(async () => {
2354
- if (create) {
2355
- const initializeOnce = create;
2356
- create = void 0;
2357
- operation = await initializeOnce();
2358
- }
2359
- if (!operation) throw new Error("Codex catalog list operation did not initialize");
2360
- const step = await operation.next();
2361
- completed ||= step.done;
2362
- return step;
2363
- });
2364
- } finally {
2365
- running = false;
2366
- }
2367
- },
2368
- close() {
2369
- if (closed) return;
2370
- if (running) throw new Error("Cannot close an active Codex catalog list step");
2371
- closed = true;
2372
- create = void 0;
2373
- const current = operation;
2374
- operation = void 0;
2375
- const currentScope = scope;
2376
- scope = void 0;
2377
- try {
2378
- if (currentScope) currentScope.run(() => current?.close());
2379
- } finally {
2380
- currentScope?.finish(completed ? "resolved" : "rejected");
2381
- }
2382
- }
2383
- };
2384
- }
2385
- function catalogHostMapper(localTerminalAvailable, localHomes) {
2386
- return (host) => {
2387
- const finishTiming = startCodexCatalogListTiming("mappingMs");
2388
- try {
2389
- const localSourceAvailable = localTerminalAvailable && localHomes.some((home) => home.hostId === host.hostId && home.appServer.start.transport === "stdio");
2390
- return {
2391
- ...toGenericCatalogHost(host, localSourceAvailable),
2392
- canStartTerminal: host.kind === "gateway" ? localSourceAvailable && host.hostId === "gateway:local" : host.canStartTerminal === true
2393
- };
2394
- } finally {
2395
- finishTiming();
2396
- }
2397
- };
2398
- }
2399
- function mappedHostPublisher(onHost, mapHost) {
2400
- return (host) => onHost(mapHost(host));
2401
- }
2402
- function mapCatalogListOperation(operation, mapHost) {
2403
- return {
2404
- async next() {
2405
- const step = await operation.next();
2406
- return step.done ? {
2407
- done: true,
2408
- hosts: step.hosts.map(mapHost)
2409
- } : step;
2410
- },
2411
- close: () => operation.close()
2412
- };
2413
- }
2414
- function registerCodexSessionCatalog(params) {
2415
- const catalogHomes = async (agentId, allowProcessHomeFallback) => {
2416
- const homes = await params.control.homesForAgent(agentId);
2417
- return allowProcessHomeFallback === false ? homes.filter((home) => !home.usesProcessHomeFallback) : homes;
2418
- };
2419
- const resolveRequestAgentId = (agentId) => resolveSessionAgentIdsStrict({
2420
- config: params.getRuntimeConfig() ?? params.api.config,
2421
- agentId
2422
- }).sessionAgentId;
2423
- const bindRequest = async (request) => {
2424
- const agentId = resolveRequestAgentId(request.agentId);
2425
- const source = isLocalCodexCatalogHost(request.hostId) ? resolveLocalCatalogHomeForThread({
2426
- homes: [...await catalogHomes(agentId, request.allowProcessHomeFallback)],
2427
- hostId: request.hostId,
2428
- ...request.sourceHomeId ? { sourceHomeId: request.sourceHomeId } : {}
2429
- }) : void 0;
2430
- return {
2431
- agentId,
2432
- source,
2433
- control: params.control.forRequest(agentId, source)
2434
- };
2435
- };
2436
- const bindLocalRequest = async (request) => {
2437
- const bound = await bindRequest(request);
2438
- if (!bound.source) throw new CatalogParamsError("Codex session catalog hostId is invalid");
2439
- return {
2440
- ...bound,
2441
- source: bound.source
2442
- };
2443
- };
2444
- const checkUpstreamActivity = createChecker(params);
2445
- const nodeSnapshots = new CodexCatalogNodeSnapshots();
2446
- const createListOperation = (query) => withCatalogListScope(async () => {
2447
- const { agentId: requestedAgentId, allowProcessHomeFallback, allowPartialResults, listNodes, onHost, waitUntil, signal, sessionEntries, ...gatewayQuery } = query;
2448
- const agentId = resolveRequestAgentId(requestedAgentId);
2449
- const selectedQuery = readGatewayParams(gatewayQuery);
2450
- const localHomes = selectedQuery.hostIds && !selectedQuery.hostIds.some(isLocalCodexCatalogHost) ? [] : [...await catalogHomes(agentId, allowProcessHomeFallback)];
2451
- const mapHost = catalogHostMapper(resolveLocalCodexTerminalExecutable() !== void 0, localHomes);
2452
- return mapCatalogListOperation(createCodexSessionCatalogListOperation({
2453
- agentId,
2454
- bindingStore: params.bindingStore,
2455
- config: params.getRuntimeConfig(),
2456
- runtime: params.api.runtime,
2457
- control: params.control,
2458
- query: selectedQuery,
2459
- listNodes,
2460
- waitUntil,
2461
- signal,
2462
- sessionEntries,
2463
- localHomes,
2464
- allowPartialResults,
2465
- nodeSnapshots,
2466
- ...onHost ? { onHost: mappedHostPublisher(onHost, mapHost) } : {}
2467
- }), mapHost);
2468
- });
2469
- const provider = {
2470
- id: "codex",
2471
- label: "Codex",
2472
- supportsProcessHomeIsolation: true,
2473
- resolveCreateSession: ({ agentId }) => resolveCodexCatalogCreateSession(params.api.runtime.modelConfig, params.getRuntimeConfig() ?? params.api.config, agentId),
2474
- list: (query) => runCatalogListInline(createListOperation(query)),
2475
- createListOperation,
2476
- read: async (request) => {
2477
- const { agentId, source, control } = await bindRequest(request);
2478
- return await readCodexSessionTranscript({
2479
- agentId,
2480
- runtime: params.api.runtime,
2481
- control,
2482
- hostId: request.hostId,
2483
- threadId: request.threadId,
2484
- sourceHomeId: request.sourceHomeId,
2485
- cursor: request.cursor,
2486
- limit: request.limit ?? 20,
2487
- ...source ? { source } : {}
2488
- });
2489
- },
2490
- continueSession: async (request) => {
2491
- const config = params.getRuntimeConfig();
2492
- if (!config) throw new Error("OpenClaw runtime config is unavailable");
2493
- if (request.hostId.startsWith("node:")) return await continueNodeCodexSession({
2494
- agentId: resolveRequestAgentId(request.agentId),
2495
- api: params.api,
2496
- config,
2497
- hostId: request.hostId,
2498
- threadId: request.threadId,
2499
- sourceHomeId: request.sourceHomeId,
2500
- clientScopes: request.clientScopes
2501
- });
2502
- if (!isLocalCodexCatalogHost(request.hostId)) throw new CatalogParamsError("Codex session catalog hostId is invalid");
2503
- const { agentId, source, control } = await bindLocalRequest(request);
2504
- source.assertCurrent();
2505
- let upstreamBaseline;
2506
- const continued = await continueLocalCodexSession({
2507
- agentId,
2508
- api: params.api,
2509
- bindingStore: params.bindingStore,
2510
- config,
2511
- control,
2512
- threadId: request.threadId,
2513
- hostId: source.hostId,
2514
- sourceHomeId: source.sourceHomeId,
2515
- ...source.hostId === "gateway:local" ? { allowLegacy: true } : {},
2516
- onContinued: (baseline) => {
2517
- upstreamBaseline = baseline;
2518
- }
2519
- });
2520
- return codexUpstreamContinueResult(continued.sessionKey, request.threadId, upstreamBaseline);
2521
- },
2522
- checkUpstreamActivity: async (probes, policy) => {
2523
- const filtered = [];
2524
- for (const probe of probes) if (!isLocalCodexCatalogHost(probe.hostId) || policy?.allowProcessHomeFallback !== false || (await catalogHomes(probe.agentId, false)).some((home) => home.hostId === probe.hostId)) filtered.push(probe);
2525
- return checkUpstreamActivity(filtered);
2526
- },
2527
- archive: async (request) => {
2528
- if (request.confirmNoOtherRunner !== true) throw new CatalogParamsError("archive requires confirmation that no other runner is active");
2529
- if (!isLocalCodexCatalogHost(request.hostId)) throw new CatalogParamsError("paired-node Codex sessions are view-only");
2530
- const config = params.getRuntimeConfig();
2531
- if (!config) throw new Error("OpenClaw runtime config is unavailable");
2532
- const { agentId, source, control } = await bindLocalRequest(request);
2533
- source.assertCurrent();
2534
- await archiveLocalCodexSession({
2535
- agentId,
2536
- bindingStore: params.bindingStore,
2537
- config,
2538
- control,
2539
- runtime: params.api.runtime,
2540
- threadId: request.threadId,
2541
- hostId: source.hostId,
2542
- sourceHomeId: source.sourceHomeId,
2543
- ...source.hostId === "gateway:local" ? { allowLegacy: true } : {}
2544
- });
2545
- return { ok: true };
2546
- },
2547
- openTerminal: async (request) => {
2548
- const { agentId, source, control } = await bindRequest(request);
2549
- return await openCodexCatalogTerminal({
2550
- api: params.api,
2551
- control,
2552
- getPluginConfig: params.getPluginConfig,
2553
- getRuntimeConfig: params.getRuntimeConfig,
2554
- resolveRuntimeOptions: params.resolveRuntimeOptions,
2555
- ...source ? { source } : {},
2556
- ...request,
2557
- agentId
2558
- });
2559
- },
2560
- startTerminalSession: async (request) => {
2561
- if (!request.nodeId && request.hostId && request.hostId !== "gateway:local") throw new CatalogParamsError("Codex terminal host is unavailable; select the local machine or a connected node");
2562
- const source = request.nodeId ? void 0 : resolveLocalCatalogHomeForThread({
2563
- homes: [...await catalogHomes(request.agentId, request.allowProcessHomeFallback)],
2564
- hostId: request.hostId ?? "gateway:local"
2565
- });
2566
- if (source && source.appServer.start.transport !== "stdio") throw new CatalogParamsError("Native terminal start requires a local Codex source");
2567
- return await startCodexCatalogTerminal({
2568
- getPluginConfig: params.getPluginConfig,
2569
- getRuntimeConfig: params.getRuntimeConfig,
2570
- resolveRuntimeOptions: params.resolveRuntimeOptions,
2571
- ...request,
2572
- source
2573
- });
2574
- }
2575
- };
2576
- params.api.registerSessionCatalog(provider);
2577
- }
2578
- const codexSessionCatalogRuntime = {
2579
- register: registerCodexSessionCatalog,
2580
- list: listCodexSessionCatalog,
2581
- readTranscript: readCodexSessionTranscript,
2582
- continueLocal: continueLocalCodexSession,
2583
- continueNode: continueNodeCodexSession,
2584
- archiveLocal: archiveLocalCodexSession
2585
- };
2586
- async function continueLocalCodexSession(...args) {
2587
- const { continueLocalCodexSession: run } = await import("./session-catalog-adoption-BU_pHWG7.mjs");
2588
- return run(...args);
2589
- }
2590
- async function archiveLocalCodexSession(...args) {
2591
- const { archiveLocalCodexSession: run } = await import("./session-catalog-archive-spHfihri.mjs");
2592
- return run(...args);
2593
- }
2594
- async function continueNodeCodexSession(...args) {
2595
- const { continueNodeCodexSession: run } = await import("./session-catalog-node-continue-DjKXHBbi.mjs");
2596
- return run(...args);
2597
- }
2598
- //#endregion
2599
- export { createCodexSessionCatalogNodeHostCommands as i, createCodexSessionCatalogNodeInvokePolicies as n, createCodexSessionCatalogControl as r, codexSessionCatalogRuntime as t };