@openclaw/codex 2026.8.1-beta.2 → 2026.9.1-beta.1

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 (60) hide show
  1. package/dist/api.js +147 -0
  2. package/dist/{attempt-client-cleanup-DMLXUfa8.js → attempt-client-cleanup-bfsmcQ6m.js} +21 -2
  3. package/dist/{binding-connection-I5Bo-AsX.js → binding-connection-BMvPX73o.js} +15 -3
  4. package/dist/{bounded-turn-qgZmzy_4.js → bounded-turn-B7iBUcuP.js} +22 -16
  5. package/dist/{capabilities-CybGI1oz.js → capabilities-BRMh0aIq.js} +1 -1
  6. package/dist/cli-metadata.js +1 -1
  7. package/dist/{command-formatters-B1AEz8ZA.js → command-formatters-DEsIufkt.js} +2 -2
  8. package/dist/{command-handlers-Db8pu_ds.js → command-handlers-D_-1_qRp.js} +65 -37
  9. package/dist/command-rpc-CCeCkf_v.js +90 -0
  10. package/dist/{compact-LspQaGfl.js → compact-BglNFZrQ.js} +35 -29
  11. package/dist/{session-binding-DPxIvMgE.js → config-giW8X0QA.js} +108 -914
  12. package/dist/context-compaction-activity-BOeJf7yo.js +58 -0
  13. package/dist/doctor-contract-api.js +23 -21
  14. package/dist/{dynamic-tools-BVdyWkUD.js → dynamic-tools-Dnlfa--w.js} +1345 -1424
  15. package/dist/{effective-mcp-catalog-DIIhAtOZ.js → effective-mcp-catalog-CTeGrnfO.js} +2 -2
  16. package/dist/elicitation-input-DMkeki8d.js +71 -0
  17. package/dist/{event-projector-assistant-message-BwxV4d6N.js → event-projector-assistant-message-C5-Ds8mA.js} +18 -1
  18. package/dist/{event-projector-usage-e5huIQWu.js → event-projector-usage-Bk1I90Bg.js} +18 -18
  19. package/dist/harness-Csz0F-DK.js +258 -0
  20. package/dist/harness.js +2 -226
  21. package/dist/index.js +262 -181
  22. package/dist/{isolated-completion-C58NbL40.js → isolated-completion-Cv6FqygM.js} +4 -4
  23. package/dist/managed-binary-DFYK4DWq.js +248 -0
  24. package/dist/media-understanding-provider.js +2 -2
  25. package/dist/model-catalog-i9rNBthX.js +48 -0
  26. package/dist/{models-BFlpn1Ex.js → models-TS3HBU-q.js} +4 -3
  27. package/dist/{native-subagent-monitor-DyTGmTUx.js → native-subagent-monitor-4Mfq2HDs.js} +354 -83
  28. package/dist/node-exec-server.runtime-BpWqJO1V.js +192 -0
  29. package/dist/{plugin-app-cache-key-C3H2CVp6.js → plugin-app-cache-key-C1CAdfcP.js} +19 -4
  30. package/dist/plugin-approval-roundtrip-bUm777tR.js +95 -0
  31. package/dist/{plugin-marketplace-discovery-CzrGJdCR.js → plugin-marketplace-discovery-B9DvaAG-.js} +59 -54
  32. package/dist/{plugin-metadata-cache-CNJPj4_b.js → plugin-metadata-cache-CTCT3w5L.js} +164 -134
  33. package/dist/{protocol-validators-B4F7L8Rf.js → protocol-validators-VeJxxJ0U.js} +80 -5
  34. package/dist/{rate-limits-DZXmOL8-.js → rate-limits-C5_D8Gmb.js} +1 -1
  35. package/dist/{request-BRl5_UfX.js → request-DXXGHko0.js} +2 -2
  36. package/dist/{run-attempt-P8BdxC1I.js → run-attempt-DYc0QCBF.js} +1276 -765
  37. package/dist/{runtime-artifact-BVSPdd6g.js → runtime-artifact-BvyT1uyd.js} +4 -7
  38. package/dist/{sandbox-guard-Cmwc9eIk.js → sandbox-guard-kuWTn9C5.js} +25 -19
  39. package/dist/session-binding-Bcynfd-_.js +874 -0
  40. package/dist/{session-catalog-xwNi_SDM.js → session-catalog-DaLKVtpH.js} +1534 -1288
  41. package/dist/session-catalog-home-id-BNwAJ9D7.js +18 -0
  42. package/dist/{session-cli-7hgXZDV7.js → session-cli-DMc4oS2w.js} +20 -7
  43. package/dist/session-permission-policy-BrNH1bjy.js +160 -0
  44. package/dist/{session-retirement-DoMMJFKm.js → session-retirement-CcNC3YSY.js} +3 -3
  45. package/dist/{session-upstream-marker-CrIFX06J.js → session-upstream-marker-BIkusb95.js} +1 -1
  46. package/dist/{settled-turn-finalizer-BRWBO4MO.js → settled-turn-finalizer-Dc3ApjU4.js} +24 -20
  47. package/dist/{shared-client-kIBbGjk4.js → shared-client-DKz23hHY.js} +1632 -372
  48. package/dist/{side-question-9HAL26l9.js → side-question-DjA_jsNe.js} +105 -54
  49. package/dist/{thread-lifecycle-Bu1BTDXr.js → thread-lifecycle-L7oEkTlq.js} +1147 -114
  50. package/dist/{thread-ownership-6kOQHlyC.js → thread-ownership-DZeuKH1j.js} +2 -2
  51. package/dist/{thread-resume-CPrJNQVM.js → thread-resume-BE9qNEW0.js} +3 -3
  52. package/dist/{transcript-mirror-B9gGgnJS.js → transcript-mirror-DsCMWBca.js} +137 -38
  53. package/dist/{transport-stdio-DIImwDVS.js → transport-stdio-DhoGy33Z.js} +2 -2
  54. package/dist/{upstream-prompt-provenance-ClRBije0.js → upstream-prompt-provenance-CFmsKwr9.js} +12 -14
  55. package/dist/{upstream-session-fork-CE-_LdnP.js → upstream-session-fork-DlaHxSLC.js} +12 -6
  56. package/dist/{usage-CHlV0e-o.js → usage-ROIaW3wo.js} +3 -3
  57. package/dist/{web-search-provider.runtime-DRw2Vl42.js → web-search-provider.runtime-ClaNPV7N.js} +3 -3
  58. package/openclaw.plugin.json +49 -2
  59. package/package.json +9 -8
  60. package/dist/app-server-policy-zcBDc1JU.js +0 -49
@@ -0,0 +1,874 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.js";
2
+ import { P as normalizeCodexServiceTier, y as CODEX_PLUGIN_MARKETPLACE_NAME_PATTERN } from "./config-giW8X0QA.js";
3
+ import { n as CODEX_APP_SERVER_BINDING_NAMESPACE, t as CODEX_APP_SERVER_BINDING_MAX_ENTRIES } from "./session-binding-meta-B7aEMU7g.js";
4
+ import { asOptionalRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
5
+ import { AgentHarnessSessionSupersededError, embeddedAgentLog } from "openclaw/plugin-sdk/agent-harness-runtime";
6
+ import { createHash, randomUUID } from "node:crypto";
7
+ import { ensureAuthProfileStore, resolveDefaultAgentDir, resolveProviderIdForAuth, resolveSessionAgentIds as resolveSessionAgentIds$1 } from "openclaw/plugin-sdk/agent-runtime";
8
+ import { z } from "zod";
9
+ import { AsyncLocalStorage } from "node:async_hooks";
10
+ import { getSessionEntry, resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime";
11
+ //#region extensions/codex/src/app-server/session-binding.ts
12
+ /** SQLite-backed Codex app-server thread bindings. */
13
+ var session_binding_exports = /* @__PURE__ */ __exportAll({
14
+ CODEX_APP_SERVER_BINDING_GUARDED_REQUEST_TIMEOUT_MS: () => CODEX_APP_SERVER_BINDING_GUARDED_REQUEST_TIMEOUT_MS,
15
+ CODEX_APP_SERVER_BINDING_MAX_ENTRIES: () => CODEX_APP_SERVER_BINDING_MAX_ENTRIES,
16
+ CODEX_APP_SERVER_BINDING_NAMESPACE: () => CODEX_APP_SERVER_BINDING_NAMESPACE,
17
+ CodexSupervisionBindingReplacementError: () => CodexSupervisionBindingReplacementError,
18
+ assertCodexBindingMayBeReplaced: () => assertCodexBindingMayBeReplaced,
19
+ bindingStoreKey: () => bindingStoreKey,
20
+ createCodexAppServerBindingStore: () => createCodexAppServerBindingStore,
21
+ createCodexSessionGenerationSupersededError: () => createCodexSessionGenerationSupersededError,
22
+ createStoredCodexAppServerBinding: () => createStoredCodexAppServerBinding,
23
+ hashCodexAppServerBindingFingerprint: () => hashCodexAppServerBindingFingerprint,
24
+ isCodexAppServerNativeAuthProfile: () => isCodexAppServerNativeAuthProfile,
25
+ normalizeCodexAppServerBindingModelProvider: () => normalizeCodexAppServerBindingModelProvider,
26
+ normalizeStoredCodexAppServerBindingFingerprints: () => normalizeStoredCodexAppServerBindingFingerprints,
27
+ readCodexAppServerThreadBinding: () => readCodexAppServerThreadBinding,
28
+ readStoredCodexAppServerBinding: () => readStoredCodexAppServerBinding,
29
+ reclaimCurrentCodexSessionGeneration: () => reclaimCurrentCodexSessionGeneration,
30
+ resolveCodexRunSessionBindingAuthority: () => resolveCodexRunSessionBindingAuthority,
31
+ scopeCodexRunBindingStore: () => scopeCodexRunBindingStore,
32
+ sessionBindingIdentity: () => sessionBindingIdentity
33
+ });
34
+ const CODEX_APP_SERVER_NATIVE_AUTH_PROVIDER = "openai";
35
+ const PUBLIC_OPENAI_MODEL_PROVIDER = "openai";
36
+ const BINDING_LEASE_RETRY_INTERVAL_MS = 1e3;
37
+ const BOUNDED_BINDING_FINGERPRINT_PATTERN = /^sha256:[a-f0-9]{64}$/i;
38
+ const CODEX_APP_SERVER_BINDING_GUARDED_REQUEST_TIMEOUT_MS = 6e4;
39
+ const BINDING_LEASE_STALE_MS = 65e3;
40
+ const BINDING_LEASE_WAIT_MS = 7e4;
41
+ const BINDING_LEASE_RENEW_INTERVAL_MS = Math.floor(BINDING_LEASE_STALE_MS / 3);
42
+ const PHYSICAL_SESSION_RETIRE_TTL_MS = BINDING_LEASE_WAIT_MS;
43
+ /** Resolves the same agent scope OpenClaw uses for transcript/session ownership. */
44
+ function sessionBindingIdentity(params) {
45
+ const { sessionAgentId } = resolveSessionAgentIds$1(params);
46
+ const sessionKey = params.sessionKey?.trim();
47
+ return {
48
+ kind: "session",
49
+ agentId: sessionAgentId,
50
+ sessionId: params.sessionId,
51
+ ...sessionKey ? { sessionKey } : {}
52
+ };
53
+ }
54
+ /** Decides whether a run may share the durable stable-key binding owner. */
55
+ function resolveCodexRunSessionBindingAuthority(params) {
56
+ const sessionKey = params.identity.sessionKey?.trim();
57
+ if (!sessionKey) return "ephemeral";
58
+ try {
59
+ const storePath = params.storePath?.trim() || resolveStorePath(params.config?.session?.store, { agentId: params.identity.agentId });
60
+ const entry = getSessionEntry({
61
+ agentId: params.identity.agentId,
62
+ hydrateSkillPromptRefs: false,
63
+ readConsistency: "latest",
64
+ sessionKey,
65
+ storePath
66
+ });
67
+ if (!entry) return "ephemeral";
68
+ return entry.sessionId === params.identity.sessionId ? "current" : "superseded";
69
+ } catch {
70
+ return "superseded";
71
+ }
72
+ }
73
+ /** Builds the terminal coordination error used when a newer OpenClaw session owns the binding. */
74
+ function createCodexSessionGenerationSupersededError(sessionId) {
75
+ return new AgentHarnessSessionSupersededError(`Codex session generation is no longer current: ${sessionId}`);
76
+ }
77
+ const optionalStringSchema = z.string().optional().catch(void 0);
78
+ const optionalBooleanSchema = z.boolean().optional().catch(void 0);
79
+ const optionalNonBlankStringSchema = z.string().refine((value) => Boolean(value.trim())).optional().catch(void 0);
80
+ const optionalTimestampSchema = z.string().refine((value) => Number.isFinite(Date.parse(value))).optional().catch(void 0);
81
+ const pendingSupervisionBranchSchema = z.object({
82
+ sourceThreadId: z.string().trim().min(1),
83
+ connectionFingerprint: z.string().trim().min(1).optional(),
84
+ lastTurnId: z.string().trim().min(1).optional(),
85
+ cleanupThreadIds: z.array(z.string().trim().min(1)).max(2).optional()
86
+ }).strict().superRefine((pending, context) => {
87
+ const cleanupThreadIds = pending.cleanupThreadIds ?? [];
88
+ if (new Set(cleanupThreadIds).size !== cleanupThreadIds.length) context.addIssue({
89
+ code: "custom",
90
+ message: "pending supervision cleanup thread ids must be unique"
91
+ });
92
+ if (cleanupThreadIds.includes(pending.sourceThreadId)) context.addIssue({
93
+ code: "custom",
94
+ message: "pending supervision cleanup cannot target its source"
95
+ });
96
+ });
97
+ const contextEngineProjectionSchema = z.object({
98
+ schemaVersion: z.literal(1),
99
+ mode: z.literal("thread_bootstrap"),
100
+ epoch: z.string().refine((value) => Boolean(value.trim())),
101
+ fingerprint: optionalStringSchema
102
+ }).strict();
103
+ const contextEngineSchema = z.object({
104
+ schemaVersion: z.literal(1),
105
+ engineId: z.string(),
106
+ policyFingerprint: z.string(),
107
+ projection: contextEngineProjectionSchema.optional().catch(void 0)
108
+ }).strict();
109
+ const destructiveApprovalModeSchema = z.enum([
110
+ "allow",
111
+ "deny",
112
+ "auto",
113
+ "ask"
114
+ ]).optional().catch(void 0);
115
+ const accountAppPolicyEntrySchema = z.object({
116
+ source: z.literal("account"),
117
+ appName: z.string(),
118
+ allowDestructiveActions: z.boolean(),
119
+ allowOpenWorld: z.boolean().optional(),
120
+ destructiveApprovalMode: destructiveApprovalModeSchema,
121
+ mcpServerNames: z.array(z.string())
122
+ }).strict();
123
+ const pluginAppPolicyEntrySchema = z.object({
124
+ source: z.literal("plugin").optional(),
125
+ configKey: z.string(),
126
+ marketplaceName: z.string().regex(CODEX_PLUGIN_MARKETPLACE_NAME_PATTERN),
127
+ pluginName: z.string(),
128
+ allowDestructiveActions: z.boolean(),
129
+ allowOpenWorld: z.boolean().optional(),
130
+ destructiveApprovalMode: destructiveApprovalModeSchema,
131
+ mcpServerNames: z.array(z.string())
132
+ }).strict();
133
+ const pluginAppPolicyContextSchema = z.object({
134
+ fingerprint: z.string(),
135
+ apps: z.record(z.string(), z.union([accountAppPolicyEntrySchema, pluginAppPolicyEntrySchema])),
136
+ pluginAppIds: z.record(z.string(), z.array(z.string())).default({})
137
+ }).strict();
138
+ const threadBindingSchema = z.object({
139
+ threadId: z.string().refine((value) => Boolean(value.trim())),
140
+ clientId: optionalStringSchema,
141
+ cwd: z.string(),
142
+ rolloutPath: optionalNonBlankStringSchema,
143
+ connectionScope: z.literal("supervision").optional(),
144
+ supervisionSourceThreadId: z.string().trim().min(1).optional(),
145
+ authProfileId: optionalStringSchema,
146
+ agentWorkspaceDeveloperInstructions: optionalNonBlankStringSchema,
147
+ model: optionalStringSchema,
148
+ preserveNativeModel: z.literal(true).optional().catch(void 0),
149
+ pendingSupervisionBranch: pendingSupervisionBranchSchema.optional(),
150
+ modelProvider: z.string().transform((value) => value.trim()).pipe(z.string().min(1)).optional().catch(void 0),
151
+ approvalPolicy: z.preprocess((value) => value === "on-failure" ? "on-request" : value, z.enum([
152
+ "never",
153
+ "on-request",
154
+ "untrusted"
155
+ ]).optional()).catch(void 0),
156
+ sandbox: z.enum([
157
+ "read-only",
158
+ "workspace-write",
159
+ "danger-full-access"
160
+ ]).optional().catch(void 0),
161
+ serviceTier: z.preprocess(normalizeCodexServiceTier, z.custom((value) => typeof value === "string").optional()).optional().catch(void 0),
162
+ networkProxyProfileName: optionalStringSchema,
163
+ networkProxyConfigFingerprint: optionalStringSchema,
164
+ dynamicToolsFingerprint: optionalStringSchema,
165
+ dynamicToolsContainDeferred: optionalBooleanSchema,
166
+ webSearchThreadConfigFingerprint: optionalStringSchema,
167
+ nativeSkillIsolationFingerprint: optionalStringSchema,
168
+ userMcpServersFingerprint: optionalStringSchema,
169
+ mcpServersFingerprint: optionalStringSchema,
170
+ configuredMcpOwnershipVersion: z.literal(1).optional().catch(void 0),
171
+ ringZeroConfigFingerprint: optionalStringSchema,
172
+ ringZeroClientInstanceId: optionalStringSchema,
173
+ /** Durable fact preventing a later unrestricted turn from widening this thread. */
174
+ nativeToolPolicyRestricted: z.literal(true).optional().catch(void 0),
175
+ nativeHookRelayGeneration: optionalNonBlankStringSchema,
176
+ appServerRuntimeFingerprint: optionalStringSchema,
177
+ pluginAppsFingerprint: optionalStringSchema,
178
+ pluginAppsInputFingerprint: optionalStringSchema,
179
+ pluginAppPolicyContext: pluginAppPolicyContextSchema.optional().catch(void 0),
180
+ contextEngine: contextEngineSchema.optional().catch(void 0),
181
+ environmentSelectionFingerprint: optionalStringSchema,
182
+ conversationStartId: optionalStringSchema,
183
+ conversationSourceTransferComplete: z.literal(true).optional().catch(void 0),
184
+ historyCoveredThrough: optionalTimestampSchema,
185
+ continuityCalibration: z.object({
186
+ promptChars: z.number().int().positive(),
187
+ inputTokens: z.number().int().positive()
188
+ }).optional().catch(void 0)
189
+ }).superRefine((binding, context) => {
190
+ if (binding.connectionScope === "supervision") {
191
+ if (!binding.supervisionSourceThreadId) context.addIssue({
192
+ code: "custom",
193
+ message: "supervision connection ownership requires its native source thread id"
194
+ });
195
+ if (binding.preserveNativeModel !== true) context.addIssue({
196
+ code: "custom",
197
+ message: "supervision connection ownership requires native model ownership"
198
+ });
199
+ if (binding.conversationSourceTransferComplete !== true) context.addIssue({
200
+ code: "custom",
201
+ message: "supervision connection ownership requires a completed source transfer"
202
+ });
203
+ if (!binding.pendingSupervisionBranch && (!binding.model?.trim() || !binding.modelProvider)) context.addIssue({
204
+ code: "custom",
205
+ message: "materialized supervision bindings require a native model and provider"
206
+ });
207
+ }
208
+ if (binding.supervisionSourceThreadId && binding.connectionScope !== "supervision") context.addIssue({
209
+ code: "custom",
210
+ message: "a supervision source thread id requires supervision connection ownership"
211
+ });
212
+ if (!binding.pendingSupervisionBranch) return;
213
+ if (binding.threadId !== binding.pendingSupervisionBranch.sourceThreadId) context.addIssue({
214
+ code: "custom",
215
+ message: "pending supervision source must match the provisional thread binding"
216
+ });
217
+ if (binding.supervisionSourceThreadId !== binding.pendingSupervisionBranch.sourceThreadId) context.addIssue({
218
+ code: "custom",
219
+ message: "pending supervision source must match its durable source identity"
220
+ });
221
+ if (binding.preserveNativeModel !== true) context.addIssue({
222
+ code: "custom",
223
+ message: "pending supervision bindings must defer model selection to Codex App Server"
224
+ });
225
+ if (binding.connectionScope !== "supervision") context.addIssue({
226
+ code: "custom",
227
+ message: "pending supervision bindings require supervision connection ownership"
228
+ });
229
+ });
230
+ var CodexSupervisionBindingReplacementError = class extends Error {
231
+ constructor(threadId, operation) {
232
+ super(`Refusing to replace supervised Codex thread ${threadId} while ${operation}; its native user-home connection and model ownership must be preserved`);
233
+ this.name = "CodexSupervisionBindingReplacementError";
234
+ }
235
+ };
236
+ function assertCodexBindingMayBeReplaced(binding, operation) {
237
+ if (binding?.connectionScope === "supervision") throw new CodexSupervisionBindingReplacementError(binding.threadId, operation);
238
+ }
239
+ const bindingLeaseSchema = z.object({
240
+ token: z.string().refine((value) => Boolean(value.trim())),
241
+ expiresAt: z.number().finite()
242
+ });
243
+ const storedSessionIdSchema = z.string().transform((value) => value.trim()).pipe(z.string().min(1)).optional().catch(void 0);
244
+ const storedBindingSchema = z.discriminatedUnion("state", [z.object({
245
+ version: z.literal(1),
246
+ state: z.literal("active"),
247
+ binding: threadBindingSchema,
248
+ sessionId: storedSessionIdSchema,
249
+ lease: bindingLeaseSchema.optional().catch(void 0)
250
+ }), z.object({
251
+ version: z.literal(1),
252
+ state: z.literal("cleared"),
253
+ sessionId: storedSessionIdSchema,
254
+ lease: bindingLeaseSchema.optional().catch(void 0),
255
+ retired: z.literal(true).optional().catch(void 0)
256
+ })]);
257
+ function hashCodexAppServerBindingFingerprint(canonical) {
258
+ return `sha256:${createHash("sha256").update(canonical).digest("hex")}`;
259
+ }
260
+ function normalizeLegacyBindingFingerprint(value) {
261
+ if (typeof value !== "string" || value === "" || value === "[]" || BOUNDED_BINDING_FINGERPRINT_PATTERN.test(value)) return value;
262
+ return hashCodexAppServerBindingFingerprint(value);
263
+ }
264
+ function normalizeLegacyBindingFingerprints(record) {
265
+ let normalized = record;
266
+ for (const key of ["dynamicToolsFingerprint", "userMcpServersFingerprint"]) {
267
+ const value = record[key];
268
+ const next = normalizeLegacyBindingFingerprint(value);
269
+ if (next === value) continue;
270
+ if (normalized === record) normalized = { ...record };
271
+ Object.assign(normalized, { [key]: next });
272
+ }
273
+ return normalized;
274
+ }
275
+ function normalizeStoredCodexAppServerBindingFingerprints(value) {
276
+ const stored = readStoredCodexAppServerBinding(value);
277
+ if (!stored || stored.state !== "active") return stored;
278
+ const binding = normalizeLegacyBindingFingerprints(stored.binding);
279
+ return binding === stored.binding ? stored : readStoredCodexAppServerBinding({
280
+ ...stored,
281
+ binding
282
+ });
283
+ }
284
+ /** Encodes a migrated sidecar binding as one canonical plugin-state row. */
285
+ function createStoredCodexAppServerBinding(value, options = {}) {
286
+ const rawRecord = asOptionalRecord(value);
287
+ if (!rawRecord) return;
288
+ const record = normalizeLegacyBindingFingerprints(rawRecord);
289
+ if (record.schemaVersion !== 1 && record.schemaVersion !== 2) return;
290
+ const pluginAppPolicyContext = readPluginAppPolicyContext(record.pluginAppPolicyContext, record.schemaVersion);
291
+ const historyCoveredThrough = readTimestamp(record.historyCoveredThrough) ?? readTimestamp(record.updatedAt) ?? readTimestamp(record.createdAt) ?? readTimestamp(options.now) ?? (/* @__PURE__ */ new Date()).toISOString();
292
+ const authProfileId = typeof record.authProfileId === "string" ? record.authProfileId : void 0;
293
+ const binding = readCodexAppServerThreadBinding({
294
+ ...record,
295
+ modelProvider: normalizeCodexAppServerBindingModelProvider({
296
+ ...options.lookup,
297
+ authProfileId,
298
+ modelProvider: typeof record.modelProvider === "string" ? record.modelProvider : void 0
299
+ }),
300
+ cwd: typeof record.cwd === "string" ? record.cwd : "",
301
+ pluginAppPolicyContext,
302
+ historyCoveredThrough
303
+ });
304
+ return binding ? {
305
+ version: 1,
306
+ state: "active",
307
+ binding: stripUndefinedBinding(binding)
308
+ } : void 0;
309
+ }
310
+ function bindingLeaseLostError(key, cause) {
311
+ return new Error(`Lost Codex binding lease: ${key}`, cause === void 0 ? void 0 : { cause });
312
+ }
313
+ /** Carries one prepared run identity through callers that rederive it from public params. */
314
+ function scopeCodexRunBindingStore(params) {
315
+ const mapSessionIdentity = (identity) => identity.agentId === params.logicalIdentity.agentId && identity.sessionId === params.logicalIdentity.sessionId && identity.sessionKey?.trim() === params.logicalIdentity.sessionKey?.trim() ? params.physicalIdentity : identity;
316
+ const mapIdentity = (identity) => identity.kind === "session" ? mapSessionIdentity(identity) : identity;
317
+ return {
318
+ ...params.bindingStore,
319
+ read: (identity) => params.bindingStore.read(mapIdentity(identity)),
320
+ hasOtherThreadOwner: (threadId, identity) => params.bindingStore.hasOtherThreadOwner(threadId, identity ? mapIdentity(identity) : void 0),
321
+ mutate: (identity, mutation) => params.bindingStore.mutate(mapIdentity(identity), mutation),
322
+ prepareSessionGenerationReclaim: (identity) => params.bindingStore.prepareSessionGenerationReclaim(mapSessionIdentity(identity)),
323
+ adoptSessionGeneration: (identity, expectedPreviousSessionId) => params.bindingStore.adoptSessionGeneration(mapSessionIdentity(identity), expectedPreviousSessionId),
324
+ resetSessionGeneration: (identity) => params.bindingStore.resetSessionGeneration(mapSessionIdentity(identity)),
325
+ retireSessionGeneration: (identity) => params.bindingStore.retireSessionGeneration(mapSessionIdentity(identity)),
326
+ withThreadArchiveFence: (run) => params.bindingStore.withThreadArchiveFence(run),
327
+ withLease: (identity, run) => params.bindingStore.withLease(mapIdentity(identity), run)
328
+ };
329
+ }
330
+ /** Lets the authoritative OpenClaw session generation claim a stale stable binding row. */
331
+ async function reclaimCurrentCodexSessionGeneration(params) {
332
+ const sessionKey = params.identity.sessionKey?.trim();
333
+ if (!sessionKey) return true;
334
+ const plan = await params.bindingStore.prepareSessionGenerationReclaim(params.identity);
335
+ if (plan.kind === "resolved") return plan.result;
336
+ try {
337
+ const storePath = params.storePath?.trim() || resolveStorePath(params.config?.session?.store, { agentId: params.identity.agentId });
338
+ if (getSessionEntry({
339
+ agentId: params.identity.agentId,
340
+ hydrateSkillPromptRefs: false,
341
+ readConsistency: "latest",
342
+ sessionKey,
343
+ storePath
344
+ })?.sessionId !== params.identity.sessionId) return false;
345
+ } catch {
346
+ return false;
347
+ }
348
+ return await params.bindingStore.mutate(params.identity, {
349
+ kind: "reclaim-generation",
350
+ expectedPreviousSessionId: plan.expectedPreviousSessionId
351
+ });
352
+ }
353
+ /** Creates the single binding facade owned by the Codex plugin runtime. */
354
+ function createCodexAppServerBindingStore(state) {
355
+ const update = state.update?.bind(state);
356
+ if (!update) throw new Error("Codex app-server bindings require atomic plugin-state updates");
357
+ const leaseContext = new AsyncLocalStorage();
358
+ const archiveContext = new AsyncLocalStorage();
359
+ let activeBindingMutations = 0;
360
+ let pendingArchives = 0;
361
+ let archiveTail = Promise.resolve();
362
+ let bindingMutationsDrained = [];
363
+ const waitForBindingMutations = async () => {
364
+ if (activeBindingMutations === 0) return;
365
+ await new Promise((resolve) => {
366
+ bindingMutationsDrained.push(resolve);
367
+ });
368
+ };
369
+ const runBindingMutation = async (run) => {
370
+ if (archiveContext.getStore() === true) return await run();
371
+ if (pendingArchives > 0) throw new Error("Codex binding mutation blocked while a native archive is in progress; retry");
372
+ activeBindingMutations += 1;
373
+ try {
374
+ return await run();
375
+ } finally {
376
+ activeBindingMutations -= 1;
377
+ if (activeBindingMutations === 0) {
378
+ const drained = bindingMutationsDrained;
379
+ bindingMutationsDrained = [];
380
+ for (const resolve of drained) resolve();
381
+ }
382
+ }
383
+ };
384
+ const renewLease = (key, owner) => {
385
+ if (owner.failure) return;
386
+ try {
387
+ let renewed = false;
388
+ const stored = update(key, (raw) => {
389
+ const current = readStoredCodexAppServerBinding(raw);
390
+ if (raw !== void 0 && !current) throw new Error(`Invalid Codex app-server binding row: ${key}`);
391
+ const lease = current?.lease;
392
+ const now = Date.now();
393
+ if (!lease || lease.token !== owner.token || lease.expiresAt <= now) return;
394
+ renewed = true;
395
+ return {
396
+ ...current,
397
+ lease: {
398
+ token: owner.token,
399
+ expiresAt: now + BINDING_LEASE_STALE_MS
400
+ }
401
+ };
402
+ });
403
+ if (!renewed || !stored) owner.failure = bindingLeaseLostError(key);
404
+ } catch (error) {
405
+ owner.failure = bindingLeaseLostError(key, error);
406
+ }
407
+ };
408
+ const transactKey = async (key, apply, ttlMs) => {
409
+ const deadline = Date.now() + BINDING_LEASE_WAIT_MS;
410
+ while (true) {
411
+ let busy = false;
412
+ let leaseLost = false;
413
+ let result;
414
+ const ownedLease = leaseContext.getStore()?.get(key);
415
+ if (ownedLease?.failure) throw ownedLease.failure;
416
+ const ownedToken = ownedLease?.token;
417
+ update(key, (raw) => {
418
+ const current = readStoredCodexAppServerBinding(raw);
419
+ if (raw !== void 0 && !current) throw new Error(`Invalid Codex app-server binding row: ${key}`);
420
+ const activeLease = current?.lease;
421
+ const now = Date.now();
422
+ if (ownedToken && (!activeLease || activeLease.token !== ownedToken || activeLease.expiresAt <= now)) {
423
+ leaseLost = true;
424
+ return;
425
+ }
426
+ if (activeLease && activeLease.token !== ownedToken && activeLease.expiresAt > now) {
427
+ busy = true;
428
+ return;
429
+ }
430
+ const applied = apply(current, ownedToken);
431
+ result = applied.result;
432
+ return applied.next;
433
+ }, ttlMs == null ? void 0 : { ttlMs });
434
+ if (leaseLost) {
435
+ const failure = bindingLeaseLostError(key);
436
+ if (ownedLease) ownedLease.failure = failure;
437
+ throw failure;
438
+ }
439
+ if (!busy) return result;
440
+ if (Date.now() >= deadline) throw new Error(`Timed out waiting for Codex binding lease: ${key}`);
441
+ await sleep(BINDING_LEASE_RETRY_INTERVAL_MS);
442
+ }
443
+ };
444
+ return {
445
+ async read(identity) {
446
+ const key = bindingStoreKey(identity);
447
+ const raw = state.lookup(key);
448
+ const stored = readStoredCodexAppServerBinding(raw);
449
+ if (raw !== void 0 && !stored) throw new Error(`Invalid Codex app-server binding row: ${key}`);
450
+ return stored?.state === "active" && ownsStoredSessionGeneration(identity, stored) ? stored.binding : void 0;
451
+ },
452
+ async hasOtherThreadOwner(threadId, currentIdentity) {
453
+ const currentKey = currentIdentity ? bindingStoreKey(currentIdentity) : void 0;
454
+ return state.entries().some(({ key, value }) => {
455
+ const stored = readStoredCodexAppServerBinding(value);
456
+ if (!stored) throw new Error(`Invalid Codex app-server binding row: ${key}`);
457
+ const isCurrentOwner = currentIdentity !== void 0 && key === currentKey && (currentIdentity.kind === "conversation" || stored.sessionId === currentIdentity.sessionId.trim());
458
+ if (stored.state !== "active" || stored.binding.threadId !== threadId || isCurrentOwner) return false;
459
+ return true;
460
+ });
461
+ },
462
+ async prepareSessionGenerationReclaim(identity) {
463
+ const key = bindingStoreKey(identity);
464
+ const raw = state.lookup(key);
465
+ const current = readStoredCodexAppServerBinding(raw);
466
+ if (raw !== void 0 && !current) throw new Error(`Invalid Codex app-server binding row: ${key}`);
467
+ if (!current) return {
468
+ kind: "resolved",
469
+ result: true
470
+ };
471
+ const currentSessionId = current.sessionId;
472
+ if (!currentSessionId) return {
473
+ kind: "resolved",
474
+ result: current.state !== "cleared" || current.retired !== true
475
+ };
476
+ if (currentSessionId === identity.sessionId) return current.state === "cleared" && current.retired === true ? {
477
+ kind: "verify",
478
+ expectedPreviousSessionId: currentSessionId
479
+ } : {
480
+ kind: "resolved",
481
+ result: true
482
+ };
483
+ return {
484
+ kind: "verify",
485
+ expectedPreviousSessionId: currentSessionId
486
+ };
487
+ },
488
+ async mutate(identity, mutation) {
489
+ return await runBindingMutation(async () => {
490
+ const key = bindingStoreKey(identity);
491
+ const retainLegacyClear = mutation.kind === "clear" && key.startsWith("conversation:legacy-");
492
+ return await transactKey(key, (current, leaseToken) => {
493
+ const ownsGeneration = ownsStoredSessionGeneration(identity, current);
494
+ const ownedLease = current?.lease && current.lease.token === leaseToken ? { lease: current.lease } : {};
495
+ if (mutation.kind === "reclaim-generation") {
496
+ if (identity.kind !== "session" || !identity.sessionKey?.trim()) return { result: false };
497
+ if (!current) return { result: true };
498
+ if (ownsGeneration) {
499
+ if (current.state === "cleared" && current.retired === true && current.sessionId === mutation.expectedPreviousSessionId) return {
500
+ result: true,
501
+ next: {
502
+ version: 1,
503
+ state: "cleared",
504
+ sessionId: identity.sessionId,
505
+ ...ownedLease
506
+ }
507
+ };
508
+ return { result: current.state !== "cleared" || current.retired !== true };
509
+ }
510
+ if (current.sessionId !== mutation.expectedPreviousSessionId) return { result: false };
511
+ if (current.state === "active" && current.binding.connectionScope === "supervision") return { result: false };
512
+ return {
513
+ result: true,
514
+ next: {
515
+ version: 1,
516
+ state: "cleared",
517
+ sessionId: identity.sessionId,
518
+ ...ownedLease
519
+ }
520
+ };
521
+ }
522
+ const storedActive = current?.state === "active" ? current : void 0;
523
+ const active = ownsGeneration ? storedActive : void 0;
524
+ const retiredGeneration = current?.state === "cleared" && current.retired === true && ownsGeneration;
525
+ const preservesSupervisionOwner = mutation.kind === "set" && active?.binding.connectionScope === "supervision" && isSameSupervisionOwner(active.binding, mutation.binding);
526
+ const clearsPendingSupervisionOwner = mutation.kind === "clear" && active?.binding.connectionScope === "supervision" && matchesPendingSupervisionClear(active.binding, mutation.threadId, mutation.expectedPendingSupervisionBranch);
527
+ const replacesExpectedOrdinaryOwner = mutation.kind === "replace-thread" && active?.binding.threadId === mutation.expectedThreadId && active.binding.connectionScope !== "supervision" && mutation.binding.connectionScope !== "supervision" && mutation.binding.threadId !== mutation.expectedThreadId;
528
+ if (mutation.kind === "set" && (mutation.if?.kind === "absent" && storedActive || current !== void 0 && !ownsGeneration || retiredGeneration || active?.binding.connectionScope === "supervision" && !preservesSupervisionOwner) || mutation.kind === "patch" && active?.binding.threadId !== mutation.threadId || mutation.kind === "replace-thread" && !replacesExpectedOrdinaryOwner || (mutation.kind === "patch-pending-supervision-branch" || mutation.kind === "commit-pending-supervision-branch") && !matchesPendingSupervisionBranch(active?.binding, mutation.expected) || mutation.kind === "clear" && (mutation.threadId !== void 0 && active?.binding.threadId !== mutation.threadId || !ownsGeneration || active?.binding.connectionScope === "supervision" && !clearsPendingSupervisionOwner)) return { result: false };
529
+ if (mutation.kind === "clear" && retiredGeneration) return { result: true };
530
+ if (mutation.kind === "clear") return {
531
+ result: true,
532
+ next: {
533
+ version: 1,
534
+ state: "cleared",
535
+ ...storedSessionGeneration(identity, current),
536
+ ...ownedLease
537
+ }
538
+ };
539
+ let binding;
540
+ if (mutation.kind === "set" || mutation.kind === "replace-thread") binding = validateBindingForWrite(mutation.binding);
541
+ else if (mutation.kind === "patch-pending-supervision-branch") binding = validateBindingForWrite({
542
+ ...active.binding,
543
+ pendingSupervisionBranch: mutation.pending
544
+ });
545
+ else if (mutation.kind === "commit-pending-supervision-branch") binding = validateBindingForWrite({
546
+ ...active.binding,
547
+ ...mutation.patch,
548
+ threadId: mutation.threadId,
549
+ pendingSupervisionBranch: void 0
550
+ });
551
+ else binding = validateBindingForWrite({
552
+ ...active.binding,
553
+ ...mutation.patch,
554
+ threadId: mutation.threadId
555
+ });
556
+ return {
557
+ result: true,
558
+ next: {
559
+ version: 1,
560
+ state: "active",
561
+ binding,
562
+ ...storedSessionGeneration(identity, current),
563
+ ...ownedLease
564
+ }
565
+ };
566
+ }, mutation.kind === "clear" && !retainLegacyClear && !leaseContext.getStore()?.has(key) ? 1 : void 0);
567
+ });
568
+ },
569
+ async adoptSessionGeneration(identity, expectedPreviousSessionId) {
570
+ return await runBindingMutation(async () => {
571
+ const key = bindingStoreKey(identity);
572
+ const expectedSessionId = expectedPreviousSessionId.trim();
573
+ const targetSessionId = identity.sessionId.trim();
574
+ if (!expectedSessionId) throw new Error("Codex session generation adoption requires the previous session id");
575
+ return await transactKey(key, (current) => {
576
+ if (current?.state !== "active") return { result: "absent" };
577
+ if (current.sessionId === targetSessionId) return { result: "current" };
578
+ if (current.sessionId !== expectedSessionId) return { result: "conflict" };
579
+ return {
580
+ result: "adopted",
581
+ next: {
582
+ ...current,
583
+ sessionId: targetSessionId
584
+ }
585
+ };
586
+ });
587
+ });
588
+ },
589
+ async resetSessionGeneration(identity) {
590
+ return await runBindingMutation(async () => {
591
+ const key = bindingStoreKey(identity);
592
+ return await transactKey(key, (current, leaseToken) => {
593
+ if (!current) return { result: "absent" };
594
+ if (!ownsStoredSessionGeneration(identity, current)) return { result: "conflict" };
595
+ if (current.state === "cleared" && current.retired === true) return { result: "conflict" };
596
+ return {
597
+ result: "applied",
598
+ next: {
599
+ version: 1,
600
+ state: "cleared",
601
+ ...storedSessionGeneration(identity, current),
602
+ ...current.lease && current.lease.token === leaseToken ? { lease: current.lease } : {}
603
+ }
604
+ };
605
+ }, leaseContext.getStore()?.has(key) ? void 0 : 1);
606
+ });
607
+ },
608
+ async retireSessionGeneration(identity) {
609
+ return await runBindingMutation(async () => {
610
+ const key = bindingStoreKey(identity);
611
+ return await transactKey(key, (current, leaseToken) => {
612
+ if (!current) return { result: "absent" };
613
+ if (!ownsStoredSessionGeneration(identity, current)) return { result: "conflict" };
614
+ if (current.state === "cleared" && current.retired === true) return { result: "applied" };
615
+ return {
616
+ result: "applied",
617
+ next: {
618
+ version: 1,
619
+ state: "cleared",
620
+ retired: true,
621
+ ...storedSessionGeneration(identity, current),
622
+ ...current.lease && current.lease.token === leaseToken ? { lease: current.lease } : {}
623
+ }
624
+ };
625
+ }, identity.sessionKey?.trim() ? void 0 : PHYSICAL_SESSION_RETIRE_TTL_MS);
626
+ });
627
+ },
628
+ async withThreadArchiveFence(run) {
629
+ pendingArchives += 1;
630
+ const operation = archiveTail.then(async () => {
631
+ await waitForBindingMutations();
632
+ return await archiveContext.run(true, run);
633
+ });
634
+ archiveTail = operation.then(() => void 0, () => void 0);
635
+ try {
636
+ return await operation;
637
+ } finally {
638
+ pendingArchives -= 1;
639
+ }
640
+ },
641
+ async withLease(identity, run) {
642
+ const key = bindingStoreKey(identity);
643
+ const owned = leaseContext.getStore();
644
+ const existingOwner = owned?.get(key);
645
+ if (existingOwner) {
646
+ const failureBeforeRun = existingOwner.failure;
647
+ if (failureBeforeRun) throw failureBeforeRun;
648
+ const result = await run();
649
+ const failureAfterRun = existingOwner.failure;
650
+ if (failureAfterRun) throw failureAfterRun;
651
+ return result;
652
+ }
653
+ const token = randomUUID();
654
+ if (!await transactKey(key, (current) => {
655
+ if (current?.state === "cleared" && current.retired === true && ownsStoredSessionGeneration(identity, current)) return { result: false };
656
+ const lease = {
657
+ token,
658
+ expiresAt: Date.now() + BINDING_LEASE_STALE_MS
659
+ };
660
+ if (current?.state === "active") return {
661
+ result: true,
662
+ next: {
663
+ ...current,
664
+ ...preservedSessionGeneration(identity, current),
665
+ lease
666
+ }
667
+ };
668
+ if (current?.state === "cleared" && current.retired === true) return {
669
+ result: true,
670
+ next: {
671
+ ...current,
672
+ lease
673
+ }
674
+ };
675
+ return {
676
+ result: true,
677
+ next: {
678
+ version: 1,
679
+ state: "cleared",
680
+ ...preservedSessionGeneration(identity, current),
681
+ lease
682
+ }
683
+ };
684
+ })) throw new Error(`Codex binding generation was retired: ${key}`);
685
+ const owner = { token };
686
+ const nested = new Map(owned);
687
+ nested.set(key, owner);
688
+ const heartbeat = setInterval(() => renewLease(key, owner), BINDING_LEASE_RENEW_INTERVAL_MS);
689
+ heartbeat.unref();
690
+ try {
691
+ const result = await leaseContext.run(nested, run);
692
+ if (owner.failure) throw owner.failure;
693
+ return result;
694
+ } finally {
695
+ clearInterval(heartbeat);
696
+ try {
697
+ const removeOwnedLease = (raw, matches) => {
698
+ const current = readStoredCodexAppServerBinding(raw);
699
+ if (!current || !matches(current) || current.lease?.token !== token) return;
700
+ const { lease: _lease, ...released } = current;
701
+ return released;
702
+ };
703
+ if (!update(key, (raw) => removeOwnedLease(raw, (current) => current.state === "active"))) {
704
+ if (!update(key, (raw) => removeOwnedLease(raw, (current) => current.state === "cleared" && current.retired === true), key.startsWith("session:") ? { ttlMs: PHYSICAL_SESSION_RETIRE_TTL_MS } : void 0)) update(key, (raw) => removeOwnedLease(raw, (current) => current.state === "cleared"), { ttlMs: 1 });
705
+ }
706
+ } catch (error) {
707
+ embeddedAgentLog.warn("failed to release codex app-server binding lease", {
708
+ key,
709
+ error
710
+ });
711
+ }
712
+ }
713
+ }
714
+ };
715
+ }
716
+ function matchesPendingSupervisionBranch(binding, expected) {
717
+ const pending = binding?.pendingSupervisionBranch;
718
+ if (!pending || binding?.threadId !== expected.sourceThreadId) return false;
719
+ if (pending.sourceThreadId !== expected.sourceThreadId || pending.connectionFingerprint !== expected.connectionFingerprint || pending.lastTurnId !== expected.lastTurnId) return false;
720
+ const currentCleanup = pending.cleanupThreadIds ?? [];
721
+ const expectedCleanup = expected.cleanupThreadIds ?? [];
722
+ return currentCleanup.length === expectedCleanup.length && currentCleanup.every((threadId, index) => threadId === expectedCleanup[index]);
723
+ }
724
+ function isSameSupervisionOwner(current, replacement) {
725
+ return replacement.connectionScope === "supervision" && replacement.threadId === current.threadId && replacement.supervisionSourceThreadId === current.supervisionSourceThreadId;
726
+ }
727
+ function matchesPendingSupervisionClear(binding, threadId, expected) {
728
+ if (!expected) return false;
729
+ const sourceThreadId = expected.sourceThreadId;
730
+ return threadId === sourceThreadId && binding.supervisionSourceThreadId === sourceThreadId && matchesPendingSupervisionBranch(binding, expected);
731
+ }
732
+ /** Stable plugin-state key for one current binding owner. */
733
+ function bindingStoreKey(identity) {
734
+ if (identity.kind === "session") {
735
+ const rawAgentId = identity.agentId.trim();
736
+ const sessionId = identity.sessionId.trim();
737
+ if (!rawAgentId) throw new Error("Codex app-server binding requires an agent id");
738
+ if (!sessionId) throw new Error("Codex app-server binding requires a session id");
739
+ const agentId = resolveSessionAgentIds$1({ agentId: rawAgentId }).sessionAgentId;
740
+ const sessionKey = identity.sessionKey?.trim();
741
+ if (sessionKey) return `session-key:${agentId}:${createHash("sha256").update(sessionKey).digest("base64url")}`;
742
+ return `session:${agentId}:${sessionId}`;
743
+ }
744
+ const bindingId = identity.bindingId.trim();
745
+ if (!bindingId) throw new Error("Codex app-server conversation binding requires a binding id");
746
+ return `conversation:${bindingId}`;
747
+ }
748
+ function readStoredCodexAppServerBinding(value) {
749
+ const result = storedBindingSchema.safeParse(value);
750
+ return result.success ? stripUndefinedValue(result.data) : void 0;
751
+ }
752
+ function storedSessionGeneration(identity, current) {
753
+ if (identity.kind === "session") return { sessionId: identity.sessionId };
754
+ return current?.sessionId ? { sessionId: current.sessionId } : {};
755
+ }
756
+ function preservedSessionGeneration(identity, current) {
757
+ if (current?.sessionId) return { sessionId: current.sessionId };
758
+ return storedSessionGeneration(identity, current);
759
+ }
760
+ function ownsStoredSessionGeneration(identity, current) {
761
+ return identity.kind !== "session" || !current?.sessionId || current.sessionId === identity.sessionId;
762
+ }
763
+ function validateBindingForWrite(binding) {
764
+ const validated = readCodexAppServerThreadBinding(binding);
765
+ if (!validated) throw new Error("Invalid Codex app-server thread binding");
766
+ return stripUndefinedBinding(validated);
767
+ }
768
+ /** Parses stored or shipped sidecar data into the current domain value. */
769
+ function readCodexAppServerThreadBinding(value) {
770
+ const result = threadBindingSchema.safeParse(value);
771
+ if (!result.success) return;
772
+ return result.data;
773
+ }
774
+ function stripUndefinedBinding(binding) {
775
+ return stripUndefinedValue(binding);
776
+ }
777
+ function stripUndefinedValue(value) {
778
+ if (Array.isArray(value)) return value.map(stripUndefinedValue);
779
+ if (!value || typeof value !== "object") return value;
780
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== void 0).map(([key, entry]) => [key, stripUndefinedValue(entry)]));
781
+ }
782
+ function readTimestamp(value) {
783
+ return optionalTimestampSchema.parse(value);
784
+ }
785
+ function readPluginAppPolicyContext(value, bindingSchemaVersion) {
786
+ const record = asOptionalRecord(value);
787
+ if (!record || typeof record.fingerprint !== "string") return;
788
+ const apps = asOptionalRecord(record.apps);
789
+ if (!apps) return;
790
+ const parsedApps = {};
791
+ for (const [appId, rawEntry] of Object.entries(apps)) {
792
+ const entry = asOptionalRecord(rawEntry);
793
+ if (!entry) return;
794
+ const destructiveApprovalMode = readDestructiveApprovalMode(entry.destructiveApprovalMode, bindingSchemaVersion);
795
+ const mcpServerNamesValid = Array.isArray(entry.mcpServerNames) && entry.mcpServerNames.every((serverName) => typeof serverName === "string");
796
+ if (entry.source === "account") {
797
+ if ("appId" in entry || typeof entry.appName !== "string" || typeof entry.allowDestructiveActions !== "boolean" || entry.allowOpenWorld !== void 0 && typeof entry.allowOpenWorld !== "boolean" || destructiveApprovalMode === "invalid" || !mcpServerNamesValid) return;
798
+ parsedApps[appId] = {
799
+ source: "account",
800
+ appName: entry.appName,
801
+ allowDestructiveActions: entry.allowDestructiveActions,
802
+ ...typeof entry.allowOpenWorld === "boolean" ? { allowOpenWorld: entry.allowOpenWorld } : {},
803
+ ...destructiveApprovalMode ? { destructiveApprovalMode } : {},
804
+ mcpServerNames: entry.mcpServerNames
805
+ };
806
+ continue;
807
+ }
808
+ if ("appId" in entry || entry.source !== void 0 && entry.source !== "plugin" || typeof entry.configKey !== "string" || typeof entry.marketplaceName !== "string" || !CODEX_PLUGIN_MARKETPLACE_NAME_PATTERN.test(entry.marketplaceName) || typeof entry.pluginName !== "string" || typeof entry.allowDestructiveActions !== "boolean" || entry.allowOpenWorld !== void 0 && typeof entry.allowOpenWorld !== "boolean" || destructiveApprovalMode === "invalid" || !mcpServerNamesValid) return;
809
+ parsedApps[appId] = {
810
+ configKey: entry.configKey,
811
+ marketplaceName: entry.marketplaceName,
812
+ pluginName: entry.pluginName,
813
+ allowDestructiveActions: entry.allowDestructiveActions,
814
+ ...typeof entry.allowOpenWorld === "boolean" ? { allowOpenWorld: entry.allowOpenWorld } : {},
815
+ ...destructiveApprovalMode ? { destructiveApprovalMode } : {},
816
+ mcpServerNames: entry.mcpServerNames
817
+ };
818
+ }
819
+ const parsedPluginAppIds = {};
820
+ if (record.pluginAppIds !== void 0 && (!record.pluginAppIds || typeof record.pluginAppIds !== "object" || Array.isArray(record.pluginAppIds))) return;
821
+ if (record.pluginAppIds && typeof record.pluginAppIds === "object") for (const [configKey, appIds] of Object.entries(record.pluginAppIds)) {
822
+ if (!Array.isArray(appIds) || appIds.some((appId) => typeof appId !== "string")) return;
823
+ parsedPluginAppIds[configKey] = appIds;
824
+ }
825
+ return {
826
+ fingerprint: record.fingerprint,
827
+ apps: parsedApps,
828
+ pluginAppIds: parsedPluginAppIds
829
+ };
830
+ }
831
+ function readDestructiveApprovalMode(value, bindingSchemaVersion) {
832
+ if (value === void 0) return;
833
+ if (value === "allow" || value === "deny") return value;
834
+ if (value === "auto") return bindingSchemaVersion === 1 ? "allow" : "auto";
835
+ if (value === "ask" && bindingSchemaVersion === 2) return "ask";
836
+ if (value === "on-request" && bindingSchemaVersion === 1) return "auto";
837
+ return "invalid";
838
+ }
839
+ function sleep(ms) {
840
+ return new Promise((resolve) => {
841
+ setTimeout(resolve, ms);
842
+ });
843
+ }
844
+ /** Returns true when an auth profile uses native Codex/OpenAI app-server auth. */
845
+ function isCodexAppServerNativeAuthProfile(lookup) {
846
+ const authProfileId = lookup.authProfileId?.trim();
847
+ if (!authProfileId) return false;
848
+ try {
849
+ const credential = (lookup.authProfileStore ?? ensureAuthProfileStore(lookup.agentDir?.trim() || resolveDefaultAgentDir(lookup.config ?? {}), {
850
+ allowKeychainPrompt: false,
851
+ config: lookup.config,
852
+ externalCliProviderIds: [CODEX_APP_SERVER_NATIVE_AUTH_PROVIDER],
853
+ externalCliProfileIds: [authProfileId]
854
+ })).profiles[authProfileId];
855
+ if (!credential || credential.type === "api_key") return false;
856
+ const provider = credential.provider?.trim();
857
+ return Boolean(provider && resolveProviderIdForAuth(provider, { config: lookup.config }) === CODEX_APP_SERVER_NATIVE_AUTH_PROVIDER);
858
+ } catch (error) {
859
+ embeddedAgentLog.debug("failed to resolve codex app-server auth profile provider", {
860
+ authProfileId,
861
+ error
862
+ });
863
+ return false;
864
+ }
865
+ }
866
+ /** Hides redundant OpenAI provider attribution for native Codex auth bindings. */
867
+ function normalizeCodexAppServerBindingModelProvider(params) {
868
+ const modelProvider = params.modelProvider?.trim();
869
+ if (!modelProvider) return;
870
+ if (isCodexAppServerNativeAuthProfile(params) && modelProvider.toLowerCase() === PUBLIC_OPENAI_MODEL_PROVIDER) return;
871
+ return modelProvider;
872
+ }
873
+ //#endregion
874
+ export { hashCodexAppServerBindingFingerprint as a, reclaimCurrentCodexSessionGeneration as c, sessionBindingIdentity as d, session_binding_exports as f, createCodexSessionGenerationSupersededError as i, resolveCodexRunSessionBindingAuthority as l, assertCodexBindingMayBeReplaced as n, isCodexAppServerNativeAuthProfile as o, bindingStoreKey as r, normalizeCodexAppServerBindingModelProvider as s, CODEX_APP_SERVER_BINDING_GUARDED_REQUEST_TIMEOUT_MS as t, scopeCodexRunBindingStore as u };