@openclaw/codex 2026.7.2-beta.5 → 2026.7.33

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 (66) hide show
  1. package/README.md +3 -27
  2. package/dist/{command-formatters-ico4ZFnk.js → .setup/app-server-policy-C_qTMEMy.mjs} +51 -9
  3. package/dist/{attempt-notifications-CMR2_fmR.js → .setup/attempt-notifications-F8krwWL4.mjs} +6 -3
  4. package/dist/{command-handlers-CRmnwI2N.js → .setup/command-handlers-DSRFfor4.mjs} +1156 -1319
  5. package/dist/.setup/command-rpc-BvYsfQ7G.mjs +786 -0
  6. package/dist/{compact-dEN49UH6.js → .setup/compact-BNgh7I4t.mjs} +10 -40
  7. package/dist/.setup/computer-use-C3QkmSO3.mjs +377 -0
  8. package/dist/.setup/config-CYEDnLJ2.mjs +1138 -0
  9. package/dist/{conversation-binding-data-BHRpYbX3.js → .setup/conversation-binding-data-CrRxtDBu.mjs} +1 -1
  10. package/dist/{bounded-turn-FEbUXoYT.js → .setup/media-understanding-provider-EbJCyDqe.mjs} +193 -92
  11. package/dist/{models-BA01NEez.js → .setup/models-C_aZk03A.mjs} +11 -6
  12. package/dist/.setup/notification-correlation-iYs4WieS.mjs +35 -0
  13. package/dist/.setup/plugin-app-cache-key-DR8jV9oS.mjs +99 -0
  14. package/dist/.setup/protocol-2POPqAY4.mjs +13 -0
  15. package/dist/{protocol-validators-Dm4eXZmt.js → .setup/protocol-validators-dZQ-UTOa.mjs} +111 -334
  16. package/dist/{rate-limits-S_PXs0ul.js → .setup/provider-DGxDs6g8.mjs} +269 -13
  17. package/dist/{dynamic-tools-LIt9ojep.js → .setup/provider-capabilities-DS2N_zc1.mjs} +5465 -3399
  18. package/dist/.setup/request-DFR0JyoV.mjs +36 -0
  19. package/dist/.setup/run-attempt-C7xEKFVB.mjs +8180 -0
  20. package/dist/{sandbox-guard-D1Wky__S.js → .setup/sandbox-guard-DA2TQfZW.mjs} +1 -10
  21. package/dist/.setup/session-binding-DuihlMJc.mjs +628 -0
  22. package/dist/.setup/shared-client-B2KmLPRw.mjs +1854 -0
  23. package/dist/{side-question-CO12sHxo.js → .setup/side-question-Cv6JXWCS.mjs} +84 -159
  24. package/dist/{thread-lifecycle-DRg_FdzC.js → .setup/thread-lifecycle-u6CZdOOH.mjs} +1159 -1799
  25. package/dist/{web-search-provider.runtime-CaQMYDbp.js → .setup/web-search-provider.runtime-Ce2zOHxW.mjs} +3 -3
  26. package/dist/doctor-contract-api.js +122 -88
  27. package/dist/harness.js +20 -85
  28. package/dist/index.js +381 -1537
  29. package/dist/media-understanding-provider.js +1 -173
  30. package/dist/prompt-overlay.js +15 -0
  31. package/dist/provider-catalog.js +79 -0
  32. package/dist/provider-discovery.js +34 -0
  33. package/dist/provider.js +2 -0
  34. package/dist/web-search-contract-api.js +1 -1
  35. package/openclaw.plugin.json +178 -221
  36. package/package.json +8 -10
  37. package/dist/app-server-policy-BmDgseo_.js +0 -49
  38. package/dist/attempt-client-cleanup-Ia52yRWc.js +0 -127
  39. package/dist/auth-binding-B4FfbcCg.js +0 -62
  40. package/dist/capabilities-BHRSI6Cn.js +0 -36
  41. package/dist/cli-metadata.js +0 -20
  42. package/dist/computer-use-BjGylO-E.js +0 -695
  43. package/dist/conversation-control-DE7d9DOj.js +0 -287
  44. package/dist/event-projector-assistant-message-DTgnPPVF.js +0 -101
  45. package/dist/event-projector-usage-tvgb1NCX.js +0 -69
  46. package/dist/incognito-session-ET_ufDH-.js +0 -2
  47. package/dist/notification-correlation-Bj_Ak_jI.js +0 -67
  48. package/dist/plugin-app-cache-key-DSXX-rXO.js +0 -315
  49. package/dist/realtime-voice-api-BPcA1uN9.js +0 -494
  50. package/dist/realtime-voice-api.js +0 -2
  51. package/dist/request-CXpPennK.js +0 -157
  52. package/dist/run-attempt-C5GTPJOE.js +0 -11935
  53. package/dist/runtime-artifact-C2ITXdhM.js +0 -488
  54. package/dist/session-binding-DlVQ-Pxs.js +0 -2161
  55. package/dist/session-catalog-CP2oCcEb.js +0 -2444
  56. package/dist/session-cli-CqZ0Fp2a.js +0 -175
  57. package/dist/session-upstream-marker-QE-m5QFG.js +0 -82
  58. package/dist/settled-turn-finalizer-CA_2QXIE.js +0 -303
  59. package/dist/shared-client-BVKE40c-.js +0 -2952
  60. package/dist/transcript-mirror-uKA-A4tB.js +0 -550
  61. package/dist/transport-stdio-DXgGZ7Ib.js +0 -88
  62. package/dist/upstream-session-fork-_Vrz4WJr.js +0 -320
  63. package/dist/usage-UpVbdX5G.js +0 -25
  64. /package/dist/{rolldown-runtime-8H4AJuhK.js → .setup/rolldown-runtime-8H4AJuhK.mjs} +0 -0
  65. /package/dist/{session-binding-meta-B7aEMU7g.js → .setup/session-binding-meta-B7aEMU7g.mjs} +0 -0
  66. /package/dist/{web-search-provider.shared-BrZmlqyR.js → .setup/web-search-provider.shared-BrZmlqyR.mjs} +0 -0
@@ -6,15 +6,6 @@ const VALID_AGENT_ID_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/i;
6
6
  const INVALID_AGENT_ID_CHARS_PATTERN = /[^a-z0-9_-]+/g;
7
7
  const LEADING_DASH_PATTERN = /^-+/;
8
8
  const TRAILING_DASH_PATTERN = /-+$/;
9
- /** Projects node execution ownership into the runtime tool factory options. */
10
- function resolveCodexNodeExecToolOverrides(policy) {
11
- if (policy.effectiveExecHost !== "node") return;
12
- const node = policy.node?.trim();
13
- return {
14
- host: "node",
15
- ...node ? { node } : {}
16
- };
17
- }
18
9
  /** Resolves node/gateway/sandbox execution ownership from overrides, session, agent, and config. */
19
10
  function resolveCodexNativeExecutionPolicy(params) {
20
11
  const config = params.config ?? {};
@@ -276,4 +267,4 @@ function resolveCodexNativeNodeExecBlock(params) {
276
267
  });
277
268
  }
278
269
  //#endregion
279
- export { resolveCodexNodeExecToolOverrides as a, resolveCodexNativeExecutionPolicy as i, resolveCodexNativeExecutionBlock as n, resolveCodexNativeSandboxBlock as r, resolveCodexAppServerDirectSandboxBypassBlock as t };
270
+ export { resolveCodexNativeExecutionPolicy as i, resolveCodexNativeExecutionBlock as n, resolveCodexNativeSandboxBlock as r, resolveCodexAppServerDirectSandboxBypassBlock as t };
@@ -0,0 +1,628 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
2
+ import { l as normalizeCodexServiceTier, t as CODEX_PLUGINS_MARKETPLACE_NAME } from "./config-CYEDnLJ2.mjs";
3
+ import { n as CODEX_APP_SERVER_BINDING_NAMESPACE, t as CODEX_APP_SERVER_BINDING_MAX_ENTRIES } from "./session-binding-meta-B7aEMU7g.mjs";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+ import { ensureAuthProfileStore, resolveDefaultAgentDir, resolveProviderIdForAuth, resolveSessionAgentIds } from "openclaw/plugin-sdk/agent-runtime";
6
+ import { z } from "zod";
7
+ import { embeddedAgentLog } from "openclaw/plugin-sdk/agent-harness-runtime";
8
+ import { AsyncLocalStorage } from "node:async_hooks";
9
+ import { loadSessionStore, resolveSessionStoreEntry, resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime";
10
+ //#region extensions/codex/src/app-server/session-binding.ts
11
+ /** SQLite-backed Codex app-server thread bindings. */
12
+ var session_binding_exports = /* @__PURE__ */ __exportAll({
13
+ CODEX_APP_SERVER_BINDING_GUARDED_REQUEST_TIMEOUT_MS: () => CODEX_APP_SERVER_BINDING_GUARDED_REQUEST_TIMEOUT_MS,
14
+ CODEX_APP_SERVER_BINDING_MAX_ENTRIES: () => CODEX_APP_SERVER_BINDING_MAX_ENTRIES,
15
+ CODEX_APP_SERVER_BINDING_NAMESPACE: () => CODEX_APP_SERVER_BINDING_NAMESPACE,
16
+ bindingStoreKey: () => bindingStoreKey,
17
+ createCodexAppServerBindingStore: () => createCodexAppServerBindingStore,
18
+ createStoredCodexAppServerBinding: () => createStoredCodexAppServerBinding,
19
+ hashCodexAppServerBindingFingerprint: () => hashCodexAppServerBindingFingerprint,
20
+ isCodexAppServerNativeAuthProfile: () => isCodexAppServerNativeAuthProfile,
21
+ normalizeCodexAppServerBindingModelProvider: () => normalizeCodexAppServerBindingModelProvider,
22
+ normalizeStoredCodexAppServerBindingFingerprints: () => normalizeStoredCodexAppServerBindingFingerprints,
23
+ readCodexAppServerThreadBinding: () => readCodexAppServerThreadBinding,
24
+ readStoredCodexAppServerBinding: () => readStoredCodexAppServerBinding,
25
+ reclaimCurrentCodexSessionGeneration: () => reclaimCurrentCodexSessionGeneration,
26
+ resolveCodexAppServerBindingModelProvider: () => resolveCodexAppServerBindingModelProvider,
27
+ sessionBindingIdentity: () => sessionBindingIdentity
28
+ });
29
+ const CODEX_APP_SERVER_NATIVE_AUTH_PROVIDER = "openai";
30
+ const PUBLIC_OPENAI_MODEL_PROVIDER = "openai";
31
+ const BINDING_LEASE_RETRY_INTERVAL_MS = 1e3;
32
+ const BOUNDED_BINDING_FINGERPRINT_PATTERN = /^sha256:[a-f0-9]{64}$/i;
33
+ const CODEX_APP_SERVER_BINDING_GUARDED_REQUEST_TIMEOUT_MS = 6e4;
34
+ const BINDING_LEASE_STALE_MS = 65e3;
35
+ const BINDING_LEASE_WAIT_MS = 7e4;
36
+ const BINDING_LEASE_RENEW_INTERVAL_MS = Math.floor(BINDING_LEASE_STALE_MS / 3);
37
+ const PHYSICAL_SESSION_RETIRE_TTL_MS = BINDING_LEASE_WAIT_MS;
38
+ /** Resolves the same agent scope OpenClaw uses for transcript/session ownership. */
39
+ function sessionBindingIdentity(params) {
40
+ const { sessionAgentId } = resolveSessionAgentIds(params);
41
+ const sessionKey = params.sessionKey?.trim();
42
+ return {
43
+ kind: "session",
44
+ agentId: sessionAgentId,
45
+ sessionId: params.sessionId,
46
+ ...sessionKey ? { sessionKey } : {}
47
+ };
48
+ }
49
+ const optionalStringSchema = z.string().optional().catch(void 0);
50
+ const optionalBooleanSchema = z.boolean().optional().catch(void 0);
51
+ const optionalNonBlankStringSchema = z.string().refine((value) => Boolean(value.trim())).optional().catch(void 0);
52
+ const optionalTimestampSchema = z.string().refine((value) => Number.isFinite(Date.parse(value))).optional().catch(void 0);
53
+ const contextEngineProjectionSchema = z.object({
54
+ schemaVersion: z.literal(1),
55
+ mode: z.literal("thread_bootstrap"),
56
+ epoch: z.string().refine((value) => Boolean(value.trim())),
57
+ fingerprint: optionalStringSchema
58
+ }).strict();
59
+ const contextEngineSchema = z.object({
60
+ schemaVersion: z.literal(1),
61
+ engineId: z.string(),
62
+ policyFingerprint: z.string(),
63
+ projection: contextEngineProjectionSchema.optional().catch(void 0)
64
+ }).strict();
65
+ const destructiveApprovalModeSchema = z.enum([
66
+ "allow",
67
+ "deny",
68
+ "auto",
69
+ "ask"
70
+ ]).optional().catch(void 0);
71
+ const accountAppPolicyEntrySchema = z.object({
72
+ source: z.literal("account"),
73
+ appName: z.string(),
74
+ allowDestructiveActions: z.boolean(),
75
+ destructiveApprovalMode: destructiveApprovalModeSchema,
76
+ mcpServerNames: z.array(z.string())
77
+ }).strict();
78
+ const pluginAppPolicyEntrySchema = z.object({
79
+ source: z.literal("plugin").optional(),
80
+ configKey: z.string(),
81
+ marketplaceName: z.literal(CODEX_PLUGINS_MARKETPLACE_NAME),
82
+ pluginName: z.string(),
83
+ allowDestructiveActions: z.boolean(),
84
+ destructiveApprovalMode: destructiveApprovalModeSchema,
85
+ mcpServerNames: z.array(z.string())
86
+ }).strict();
87
+ const pluginAppPolicyContextSchema = z.object({
88
+ fingerprint: z.string(),
89
+ apps: z.record(z.string(), z.union([accountAppPolicyEntrySchema, pluginAppPolicyEntrySchema])),
90
+ pluginAppIds: z.record(z.string(), z.array(z.string())).default({})
91
+ }).strict();
92
+ const threadBindingSchema = z.object({
93
+ threadId: z.string().refine((value) => Boolean(value.trim())),
94
+ cwd: z.string(),
95
+ authProfileId: optionalStringSchema,
96
+ model: optionalStringSchema,
97
+ modelProvider: z.string().transform((value) => value.trim()).pipe(z.string().min(1)).optional().catch(void 0),
98
+ approvalPolicy: z.preprocess((value) => value === "on-failure" ? "on-request" : value, z.enum([
99
+ "never",
100
+ "on-request",
101
+ "untrusted"
102
+ ]).optional()).catch(void 0),
103
+ sandbox: z.enum([
104
+ "read-only",
105
+ "workspace-write",
106
+ "danger-full-access"
107
+ ]).optional().catch(void 0),
108
+ serviceTier: z.preprocess(normalizeCodexServiceTier, z.custom((value) => typeof value === "string").optional()).optional().catch(void 0),
109
+ networkProxyProfileName: optionalStringSchema,
110
+ networkProxyConfigFingerprint: optionalStringSchema,
111
+ dynamicToolsFingerprint: optionalStringSchema,
112
+ dynamicToolsContainDeferred: optionalBooleanSchema,
113
+ webSearchThreadConfigFingerprint: optionalStringSchema,
114
+ userMcpServersFingerprint: optionalStringSchema,
115
+ mcpServersFingerprint: optionalStringSchema,
116
+ nativeHookRelayGeneration: optionalNonBlankStringSchema,
117
+ appServerRuntimeFingerprint: optionalStringSchema,
118
+ pluginAppsFingerprint: optionalStringSchema,
119
+ pluginAppsInputFingerprint: optionalStringSchema,
120
+ pluginAppPolicyContext: pluginAppPolicyContextSchema.optional().catch(void 0),
121
+ contextEngine: contextEngineSchema.optional().catch(void 0),
122
+ environmentSelectionFingerprint: optionalStringSchema,
123
+ conversationStartId: optionalStringSchema,
124
+ conversationSourceTransferComplete: z.literal(true).optional().catch(void 0),
125
+ historyCoveredThrough: optionalTimestampSchema
126
+ });
127
+ const bindingLeaseSchema = z.object({
128
+ token: z.string().refine((value) => Boolean(value.trim())),
129
+ expiresAt: z.number().finite()
130
+ });
131
+ const storedSessionIdSchema = z.string().transform((value) => value.trim()).pipe(z.string().min(1)).optional().catch(void 0);
132
+ const storedBindingSchema = z.discriminatedUnion("state", [z.object({
133
+ version: z.literal(1),
134
+ state: z.literal("active"),
135
+ binding: threadBindingSchema,
136
+ sessionId: storedSessionIdSchema,
137
+ lease: bindingLeaseSchema.optional().catch(void 0)
138
+ }), z.object({
139
+ version: z.literal(1),
140
+ state: z.literal("cleared"),
141
+ sessionId: storedSessionIdSchema,
142
+ lease: bindingLeaseSchema.optional().catch(void 0),
143
+ retired: z.literal(true).optional().catch(void 0)
144
+ })]);
145
+ function hashCodexAppServerBindingFingerprint(canonical) {
146
+ return `sha256:${createHash("sha256").update(canonical).digest("hex")}`;
147
+ }
148
+ function normalizeLegacyBindingFingerprint(value) {
149
+ if (typeof value !== "string" || value === "" || value === "[]" || BOUNDED_BINDING_FINGERPRINT_PATTERN.test(value)) return value;
150
+ return hashCodexAppServerBindingFingerprint(value);
151
+ }
152
+ function normalizeLegacyBindingFingerprints(record) {
153
+ let normalized = record;
154
+ for (const key of ["dynamicToolsFingerprint", "userMcpServersFingerprint"]) {
155
+ const value = record[key];
156
+ const next = normalizeLegacyBindingFingerprint(value);
157
+ if (next === value) continue;
158
+ if (normalized === record) normalized = { ...record };
159
+ normalized[key] = next;
160
+ }
161
+ return normalized;
162
+ }
163
+ function normalizeStoredCodexAppServerBindingFingerprints(value) {
164
+ const stored = readStoredCodexAppServerBinding(value);
165
+ if (!stored || stored.state !== "active") return stored;
166
+ const binding = normalizeLegacyBindingFingerprints(stored.binding);
167
+ return binding === stored.binding ? stored : readStoredCodexAppServerBinding({
168
+ ...stored,
169
+ binding
170
+ });
171
+ }
172
+ /** Encodes a migrated sidecar binding as one canonical plugin-state row. */
173
+ function createStoredCodexAppServerBinding(value, options = {}) {
174
+ const rawRecord = asRecord(value);
175
+ if (!rawRecord) return;
176
+ const record = normalizeLegacyBindingFingerprints(rawRecord);
177
+ if (record.schemaVersion !== 1 && record.schemaVersion !== 2) return;
178
+ const pluginAppPolicyContext = readPluginAppPolicyContext(record.pluginAppPolicyContext, record.schemaVersion);
179
+ const historyCoveredThrough = readTimestamp(record.historyCoveredThrough) ?? readTimestamp(record.updatedAt) ?? readTimestamp(record.createdAt) ?? readTimestamp(options.now) ?? (/* @__PURE__ */ new Date()).toISOString();
180
+ const authProfileId = typeof record.authProfileId === "string" ? record.authProfileId : void 0;
181
+ const binding = readCodexAppServerThreadBinding({
182
+ ...record,
183
+ modelProvider: normalizeCodexAppServerBindingModelProvider({
184
+ ...options.lookup,
185
+ authProfileId,
186
+ modelProvider: typeof record.modelProvider === "string" ? record.modelProvider : void 0
187
+ }),
188
+ cwd: typeof record.cwd === "string" ? record.cwd : "",
189
+ pluginAppPolicyContext,
190
+ historyCoveredThrough
191
+ });
192
+ return binding ? {
193
+ version: 1,
194
+ state: "active",
195
+ binding: stripUndefinedBinding(binding)
196
+ } : void 0;
197
+ }
198
+ function bindingLeaseLostError(key, cause) {
199
+ return new Error(`Lost Codex binding lease: ${key}`, cause === void 0 ? void 0 : { cause });
200
+ }
201
+ /** Lets the authoritative OpenClaw session generation claim a stale stable binding row. */
202
+ async function reclaimCurrentCodexSessionGeneration(params) {
203
+ const sessionKey = params.identity.sessionKey?.trim();
204
+ if (!sessionKey) return true;
205
+ const plan = await params.bindingStore.prepareSessionGenerationReclaim(params.identity);
206
+ if (plan.kind === "resolved") return plan.result;
207
+ try {
208
+ const storePath = resolveStorePath(params.config?.session?.store, { agentId: params.identity.agentId });
209
+ if (resolveSessionStoreEntry({
210
+ store: loadSessionStore(storePath, {
211
+ skipCache: true,
212
+ hydrateSkillPromptRefs: false
213
+ }),
214
+ sessionKey
215
+ }).existing?.sessionId !== params.identity.sessionId) return false;
216
+ } catch {
217
+ return false;
218
+ }
219
+ return await params.bindingStore.mutate(params.identity, {
220
+ kind: "reclaim-generation",
221
+ expectedPreviousSessionId: plan.expectedPreviousSessionId
222
+ });
223
+ }
224
+ /** Creates the single binding facade owned by the Codex plugin runtime. */
225
+ function createCodexAppServerBindingStore(state) {
226
+ const update = state.update?.bind(state);
227
+ if (!update) throw new Error("Codex app-server bindings require atomic plugin-state updates");
228
+ const leaseContext = new AsyncLocalStorage();
229
+ const renewLease = (key, owner) => {
230
+ if (owner.failure) return;
231
+ try {
232
+ let renewed = false;
233
+ const stored = update(key, (raw) => {
234
+ const current = readStoredCodexAppServerBinding(raw);
235
+ if (raw !== void 0 && !current) throw new Error(`Invalid Codex app-server binding row: ${key}`);
236
+ const lease = current?.lease;
237
+ const now = Date.now();
238
+ if (!lease || lease.token !== owner.token || lease.expiresAt <= now) return;
239
+ renewed = true;
240
+ return {
241
+ ...current,
242
+ lease: {
243
+ token: owner.token,
244
+ expiresAt: now + BINDING_LEASE_STALE_MS
245
+ }
246
+ };
247
+ });
248
+ if (!renewed || !stored) owner.failure = bindingLeaseLostError(key);
249
+ } catch (error) {
250
+ owner.failure = bindingLeaseLostError(key, error);
251
+ }
252
+ };
253
+ const transactKey = async (key, apply, ttlMs) => {
254
+ const deadline = Date.now() + BINDING_LEASE_WAIT_MS;
255
+ while (true) {
256
+ let busy = false;
257
+ let leaseLost = false;
258
+ let result;
259
+ const ownedLease = leaseContext.getStore()?.get(key);
260
+ if (ownedLease?.failure) throw ownedLease.failure;
261
+ const ownedToken = ownedLease?.token;
262
+ update(key, (raw) => {
263
+ const current = readStoredCodexAppServerBinding(raw);
264
+ if (raw !== void 0 && !current) throw new Error(`Invalid Codex app-server binding row: ${key}`);
265
+ const activeLease = current?.lease;
266
+ const now = Date.now();
267
+ if (ownedToken && (!activeLease || activeLease.token !== ownedToken || activeLease.expiresAt <= now)) {
268
+ leaseLost = true;
269
+ return;
270
+ }
271
+ if (activeLease && activeLease.token !== ownedToken && activeLease.expiresAt > now) {
272
+ busy = true;
273
+ return;
274
+ }
275
+ const applied = apply(current, ownedToken);
276
+ result = applied.result;
277
+ return applied.next;
278
+ }, ttlMs == null ? void 0 : { ttlMs });
279
+ if (leaseLost) {
280
+ const failure = bindingLeaseLostError(key);
281
+ if (ownedLease) ownedLease.failure = failure;
282
+ throw failure;
283
+ }
284
+ if (!busy) return result;
285
+ if (Date.now() >= deadline) throw new Error(`Timed out waiting for Codex binding lease: ${key}`);
286
+ await sleep(BINDING_LEASE_RETRY_INTERVAL_MS);
287
+ }
288
+ };
289
+ return {
290
+ async read(identity) {
291
+ const key = bindingStoreKey(identity);
292
+ const raw = state.lookup(key);
293
+ const stored = readStoredCodexAppServerBinding(raw);
294
+ if (raw !== void 0 && !stored) throw new Error(`Invalid Codex app-server binding row: ${key}`);
295
+ return stored?.state === "active" && ownsStoredSessionGeneration(identity, stored) ? stored.binding : void 0;
296
+ },
297
+ async prepareSessionGenerationReclaim(identity) {
298
+ const key = bindingStoreKey(identity);
299
+ const raw = state.lookup(key);
300
+ const current = readStoredCodexAppServerBinding(raw);
301
+ if (raw !== void 0 && !current) throw new Error(`Invalid Codex app-server binding row: ${key}`);
302
+ if (!current) return {
303
+ kind: "resolved",
304
+ result: true
305
+ };
306
+ const currentSessionId = current.sessionId;
307
+ if (!currentSessionId || currentSessionId === identity.sessionId) return {
308
+ kind: "resolved",
309
+ result: current.state !== "cleared" || current.retired !== true
310
+ };
311
+ return {
312
+ kind: "verify",
313
+ expectedPreviousSessionId: currentSessionId
314
+ };
315
+ },
316
+ async mutate(identity, mutation) {
317
+ const key = bindingStoreKey(identity);
318
+ const retainLegacyClear = mutation.kind === "clear" && key.startsWith("conversation:legacy-");
319
+ return await transactKey(key, (current, leaseToken) => {
320
+ const ownsGeneration = ownsStoredSessionGeneration(identity, current);
321
+ const ownedLease = current?.lease && current.lease.token === leaseToken ? { lease: current.lease } : {};
322
+ if (mutation.kind === "reclaim-generation") {
323
+ if (identity.kind !== "session" || !identity.sessionKey?.trim()) return { result: false };
324
+ if (!current) return { result: true };
325
+ if (ownsGeneration) return { result: current.state !== "cleared" || current.retired !== true };
326
+ if (current.sessionId !== mutation.expectedPreviousSessionId) return { result: false };
327
+ return {
328
+ result: true,
329
+ next: {
330
+ version: 1,
331
+ state: "cleared",
332
+ sessionId: identity.sessionId,
333
+ ...ownedLease
334
+ }
335
+ };
336
+ }
337
+ const storedActive = current?.state === "active" ? current : void 0;
338
+ const active = ownsGeneration ? storedActive : void 0;
339
+ const retiredGeneration = current?.state === "cleared" && current.retired === true && ownsGeneration;
340
+ if (mutation.kind === "set" && (mutation.if?.kind === "absent" && storedActive || current !== void 0 && !ownsGeneration || retiredGeneration) || mutation.kind === "patch" && active?.binding.threadId !== mutation.threadId || mutation.kind === "clear" && (mutation.threadId !== void 0 && active?.binding.threadId !== mutation.threadId || !ownsGeneration)) return { result: false };
341
+ if (mutation.kind === "clear" && retiredGeneration) return { result: true };
342
+ if (mutation.kind === "clear") return {
343
+ result: true,
344
+ next: {
345
+ version: 1,
346
+ state: "cleared",
347
+ ...storedSessionGeneration(identity, current),
348
+ ...ownedLease
349
+ }
350
+ };
351
+ let binding;
352
+ if (mutation.kind === "set") binding = validateBindingForWrite(mutation.binding);
353
+ else binding = validateBindingForWrite({
354
+ ...active.binding,
355
+ ...mutation.patch,
356
+ threadId: mutation.threadId
357
+ });
358
+ return {
359
+ result: true,
360
+ next: {
361
+ version: 1,
362
+ state: "active",
363
+ binding,
364
+ ...storedSessionGeneration(identity, current),
365
+ ...ownedLease
366
+ }
367
+ };
368
+ }, mutation.kind === "clear" && !retainLegacyClear && !leaseContext.getStore()?.has(key) ? 1 : void 0);
369
+ },
370
+ async adoptSessionGeneration(identity, expectedPreviousSessionId) {
371
+ const key = bindingStoreKey(identity);
372
+ const expectedSessionId = expectedPreviousSessionId.trim();
373
+ const targetSessionId = identity.sessionId.trim();
374
+ if (!expectedSessionId) throw new Error("Codex session generation adoption requires the previous session id");
375
+ return await transactKey(key, (current) => {
376
+ if (current?.state !== "active") return { result: "absent" };
377
+ if (current.sessionId === targetSessionId) return { result: "current" };
378
+ if (current.sessionId !== expectedSessionId) return { result: "conflict" };
379
+ return {
380
+ result: "adopted",
381
+ next: {
382
+ ...current,
383
+ sessionId: targetSessionId
384
+ }
385
+ };
386
+ });
387
+ },
388
+ async retireSessionGeneration(identity) {
389
+ const key = bindingStoreKey(identity);
390
+ return await transactKey(key, (current, leaseToken) => {
391
+ if (!current) return { result: "absent" };
392
+ if (!ownsStoredSessionGeneration(identity, current)) return { result: "conflict" };
393
+ if (current.state === "cleared" && current.retired === true) return { result: "applied" };
394
+ return {
395
+ result: "applied",
396
+ next: {
397
+ version: 1,
398
+ state: "cleared",
399
+ retired: true,
400
+ ...storedSessionGeneration(identity, current),
401
+ ...current.lease && current.lease.token === leaseToken ? { lease: current.lease } : {}
402
+ }
403
+ };
404
+ }, identity.sessionKey?.trim() ? void 0 : PHYSICAL_SESSION_RETIRE_TTL_MS);
405
+ },
406
+ async withLease(identity, run) {
407
+ const key = bindingStoreKey(identity);
408
+ const owned = leaseContext.getStore();
409
+ const existingOwner = owned?.get(key);
410
+ if (existingOwner) {
411
+ const failureBeforeRun = existingOwner.failure;
412
+ if (failureBeforeRun) throw failureBeforeRun;
413
+ const result = await run();
414
+ const failureAfterRun = existingOwner.failure;
415
+ if (failureAfterRun) throw failureAfterRun;
416
+ return result;
417
+ }
418
+ const token = randomUUID();
419
+ if (!await transactKey(key, (current) => {
420
+ if (current?.state === "cleared" && current.retired === true && ownsStoredSessionGeneration(identity, current)) return { result: false };
421
+ const lease = {
422
+ token,
423
+ expiresAt: Date.now() + BINDING_LEASE_STALE_MS
424
+ };
425
+ if (current?.state === "active") return {
426
+ result: true,
427
+ next: {
428
+ ...current,
429
+ ...preservedSessionGeneration(identity, current),
430
+ lease
431
+ }
432
+ };
433
+ if (current?.state === "cleared" && current.retired === true) return {
434
+ result: true,
435
+ next: {
436
+ ...current,
437
+ lease
438
+ }
439
+ };
440
+ return {
441
+ result: true,
442
+ next: {
443
+ version: 1,
444
+ state: "cleared",
445
+ ...preservedSessionGeneration(identity, current),
446
+ lease
447
+ }
448
+ };
449
+ })) throw new Error(`Codex binding generation was retired: ${key}`);
450
+ const owner = { token };
451
+ const nested = new Map(owned);
452
+ nested.set(key, owner);
453
+ const heartbeat = setInterval(() => renewLease(key, owner), BINDING_LEASE_RENEW_INTERVAL_MS);
454
+ heartbeat.unref();
455
+ try {
456
+ const result = await leaseContext.run(nested, run);
457
+ if (owner.failure) throw owner.failure;
458
+ return result;
459
+ } finally {
460
+ clearInterval(heartbeat);
461
+ try {
462
+ const removeOwnedLease = (raw, matches) => {
463
+ const current = readStoredCodexAppServerBinding(raw);
464
+ if (!current || !matches(current) || current.lease?.token !== token) return;
465
+ const { lease: _lease, ...released } = current;
466
+ return released;
467
+ };
468
+ if (!update(key, (raw) => removeOwnedLease(raw, (current) => current.state === "active"))) {
469
+ 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 });
470
+ }
471
+ } catch (error) {
472
+ embeddedAgentLog.warn("failed to release codex app-server binding lease", {
473
+ key,
474
+ error
475
+ });
476
+ }
477
+ }
478
+ }
479
+ };
480
+ }
481
+ /** Stable plugin-state key for one current binding owner. */
482
+ function bindingStoreKey(identity) {
483
+ if (identity.kind === "session") {
484
+ const rawAgentId = identity.agentId.trim();
485
+ const sessionId = identity.sessionId.trim();
486
+ if (!rawAgentId) throw new Error("Codex app-server binding requires an agent id");
487
+ if (!sessionId) throw new Error("Codex app-server binding requires a session id");
488
+ const agentId = resolveSessionAgentIds({ agentId: rawAgentId }).sessionAgentId;
489
+ const sessionKey = identity.sessionKey?.trim();
490
+ if (sessionKey) return `session-key:${agentId}:${createHash("sha256").update(sessionKey).digest("base64url")}`;
491
+ return `session:${agentId}:${sessionId}`;
492
+ }
493
+ const bindingId = identity.bindingId.trim();
494
+ if (!bindingId) throw new Error("Codex app-server conversation binding requires a binding id");
495
+ return `conversation:${bindingId}`;
496
+ }
497
+ function readStoredCodexAppServerBinding(value) {
498
+ const result = storedBindingSchema.safeParse(value);
499
+ return result.success ? stripUndefinedValue(result.data) : void 0;
500
+ }
501
+ function storedSessionGeneration(identity, current) {
502
+ if (identity.kind === "session") return { sessionId: identity.sessionId };
503
+ return current?.sessionId ? { sessionId: current.sessionId } : {};
504
+ }
505
+ function preservedSessionGeneration(identity, current) {
506
+ if (current?.sessionId) return { sessionId: current.sessionId };
507
+ return storedSessionGeneration(identity, current);
508
+ }
509
+ function ownsStoredSessionGeneration(identity, current) {
510
+ return identity.kind !== "session" || !current?.sessionId || current.sessionId === identity.sessionId;
511
+ }
512
+ function validateBindingForWrite(binding) {
513
+ const validated = readCodexAppServerThreadBinding(binding);
514
+ if (!validated) throw new Error("Invalid Codex app-server thread binding");
515
+ return stripUndefinedBinding(validated);
516
+ }
517
+ /** Parses stored or shipped sidecar data into the current domain value. */
518
+ function readCodexAppServerThreadBinding(value) {
519
+ const result = threadBindingSchema.safeParse(value);
520
+ if (!result.success) return;
521
+ return result.data;
522
+ }
523
+ function stripUndefinedBinding(binding) {
524
+ return stripUndefinedValue(binding);
525
+ }
526
+ function stripUndefinedValue(value) {
527
+ if (Array.isArray(value)) return value.map(stripUndefinedValue);
528
+ if (!value || typeof value !== "object") return value;
529
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== void 0).map(([key, entry]) => [key, stripUndefinedValue(entry)]));
530
+ }
531
+ function asRecord(value) {
532
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
533
+ }
534
+ function readTimestamp(value) {
535
+ return optionalTimestampSchema.parse(value);
536
+ }
537
+ function readPluginAppPolicyContext(value, bindingSchemaVersion) {
538
+ const record = asRecord(value);
539
+ if (!record || typeof record.fingerprint !== "string") return;
540
+ const apps = asRecord(record.apps);
541
+ if (!apps) return;
542
+ const parsedApps = {};
543
+ for (const [appId, rawEntry] of Object.entries(apps)) {
544
+ const entry = asRecord(rawEntry);
545
+ if (!entry) return;
546
+ const destructiveApprovalMode = readDestructiveApprovalMode(entry.destructiveApprovalMode, bindingSchemaVersion);
547
+ const mcpServerNamesValid = Array.isArray(entry.mcpServerNames) && entry.mcpServerNames.every((serverName) => typeof serverName === "string");
548
+ if (entry.source === "account") {
549
+ if ("appId" in entry || typeof entry.appName !== "string" || typeof entry.allowDestructiveActions !== "boolean" || destructiveApprovalMode === "invalid" || !mcpServerNamesValid) return;
550
+ parsedApps[appId] = {
551
+ source: "account",
552
+ appName: entry.appName,
553
+ allowDestructiveActions: entry.allowDestructiveActions,
554
+ ...destructiveApprovalMode ? { destructiveApprovalMode } : {},
555
+ mcpServerNames: entry.mcpServerNames
556
+ };
557
+ continue;
558
+ }
559
+ if ("appId" in entry || entry.source !== void 0 && entry.source !== "plugin" || typeof entry.configKey !== "string" || entry.marketplaceName !== "openai-curated" || typeof entry.pluginName !== "string" || typeof entry.allowDestructiveActions !== "boolean" || destructiveApprovalMode === "invalid" || !mcpServerNamesValid) return;
560
+ parsedApps[appId] = {
561
+ configKey: entry.configKey,
562
+ marketplaceName: entry.marketplaceName,
563
+ pluginName: entry.pluginName,
564
+ allowDestructiveActions: entry.allowDestructiveActions,
565
+ ...destructiveApprovalMode ? { destructiveApprovalMode } : {},
566
+ mcpServerNames: entry.mcpServerNames
567
+ };
568
+ }
569
+ const parsedPluginAppIds = {};
570
+ if (record.pluginAppIds !== void 0 && (!record.pluginAppIds || typeof record.pluginAppIds !== "object" || Array.isArray(record.pluginAppIds))) return;
571
+ if (record.pluginAppIds && typeof record.pluginAppIds === "object") for (const [configKey, appIds] of Object.entries(record.pluginAppIds)) {
572
+ if (!Array.isArray(appIds) || appIds.some((appId) => typeof appId !== "string")) return;
573
+ parsedPluginAppIds[configKey] = appIds;
574
+ }
575
+ return {
576
+ fingerprint: record.fingerprint,
577
+ apps: parsedApps,
578
+ pluginAppIds: parsedPluginAppIds
579
+ };
580
+ }
581
+ function readDestructiveApprovalMode(value, bindingSchemaVersion) {
582
+ if (value === void 0) return;
583
+ if (value === "allow" || value === "deny") return value;
584
+ if (value === "auto") return bindingSchemaVersion === 1 ? "allow" : "auto";
585
+ if (value === "ask" && bindingSchemaVersion === 2) return "ask";
586
+ if (value === "on-request" && bindingSchemaVersion === 1) return "auto";
587
+ return "invalid";
588
+ }
589
+ function sleep(ms) {
590
+ return new Promise((resolve) => {
591
+ setTimeout(resolve, ms);
592
+ });
593
+ }
594
+ /** Returns true when an auth profile uses native Codex/OpenAI app-server auth. */
595
+ function isCodexAppServerNativeAuthProfile(lookup) {
596
+ const authProfileId = lookup.authProfileId?.trim();
597
+ if (!authProfileId) return false;
598
+ try {
599
+ const credential = (lookup.authProfileStore ?? ensureAuthProfileStore(lookup.agentDir?.trim() || resolveDefaultAgentDir(lookup.config ?? {}), {
600
+ allowKeychainPrompt: false,
601
+ config: lookup.config,
602
+ externalCliProviderIds: [CODEX_APP_SERVER_NATIVE_AUTH_PROVIDER],
603
+ externalCliProfileIds: [authProfileId]
604
+ })).profiles[authProfileId];
605
+ if (!credential || credential.type === "api_key") return false;
606
+ const provider = credential.provider?.trim();
607
+ return Boolean(provider && resolveProviderIdForAuth(provider, { config: lookup.config }) === CODEX_APP_SERVER_NATIVE_AUTH_PROVIDER);
608
+ } catch (error) {
609
+ embeddedAgentLog.debug("failed to resolve codex app-server auth profile provider", {
610
+ authProfileId,
611
+ error
612
+ });
613
+ return false;
614
+ }
615
+ }
616
+ /** Hides redundant OpenAI provider attribution for native Codex auth bindings. */
617
+ function normalizeCodexAppServerBindingModelProvider(params) {
618
+ const modelProvider = params.modelProvider?.trim();
619
+ if (!modelProvider) return;
620
+ if (isCodexAppServerNativeAuthProfile(params) && modelProvider.toLowerCase() === PUBLIC_OPENAI_MODEL_PROVIDER) return;
621
+ return modelProvider;
622
+ }
623
+ /** Restores the sole provider intentionally omitted from canonical binding rows. */
624
+ function resolveCodexAppServerBindingModelProvider(params) {
625
+ return params.modelProvider?.trim() || (isCodexAppServerNativeAuthProfile(params) ? PUBLIC_OPENAI_MODEL_PROVIDER : void 0);
626
+ }
627
+ //#endregion
628
+ export { normalizeCodexAppServerBindingModelProvider as a, session_binding_exports as c, isCodexAppServerNativeAuthProfile as i, bindingStoreKey as n, reclaimCurrentCodexSessionGeneration as o, hashCodexAppServerBindingFingerprint as r, sessionBindingIdentity as s, CODEX_APP_SERVER_BINDING_GUARDED_REQUEST_TIMEOUT_MS as t };