@openclaw/codex 2026.6.11 → 2026.7.1-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 (42) hide show
  1. package/dist/{app-server-policy-BPTiVNsW.js → app-server-policy-C968Kgin.js} +5 -5
  2. package/dist/{attempt-notifications-BYnndyFl.js → attempt-notifications-BGsEIIDI.js} +29 -40
  3. package/dist/{command-handlers-DEPTJYk0.js → command-handlers-Dv-pzAmg.js} +278 -237
  4. package/dist/command-rpc-eLM_mtC7.js +784 -0
  5. package/dist/compact-4mVBriKT.js +603 -0
  6. package/dist/{computer-use-ClrJwoFp.js → computer-use-Bmaz333N.js} +3 -3
  7. package/dist/{config-CszD0vP3.js → config-CYEDnLJ2.js} +44 -18
  8. package/dist/conversation-binding-data-BHRpYbX3.js +121 -0
  9. package/dist/doctor-contract-api.js +590 -22
  10. package/dist/harness.js +29 -10
  11. package/dist/index.js +1134 -35
  12. package/dist/{media-understanding-provider-ZUQHN7gT.js → media-understanding-provider-BHOu9-Gg.js} +13 -8
  13. package/dist/media-understanding-provider.js +1 -1
  14. package/dist/{models-CAmfBWRl.js → models-DDmO1zwd.js} +2 -2
  15. package/dist/notification-correlation-Bo7KB3ks.js +35 -0
  16. package/dist/{plugin-app-cache-key-C9ILt7bl.js → plugin-app-cache-key-BrhVdeEf.js} +13 -5
  17. package/dist/{protocol-dh-ETiNd.js → protocol-2POPqAY4.js} +2 -1
  18. package/dist/{protocol-validators-B19q5BIX.js → protocol-validators-dZQ-UTOa.js} +205 -56
  19. package/dist/provider-capabilities-DzI8fgEu.js +6172 -0
  20. package/dist/provider-catalog.js +4 -2
  21. package/dist/{provider-B-OHpbD3.js → provider-zjPfx5Fs.js} +94 -23
  22. package/dist/provider.js +2 -2
  23. package/dist/{request-Dcd452Nk.js → request-BcJyl8KL.js} +2 -2
  24. package/dist/{run-attempt-CXxtFC9d.js → run-attempt-DNSNk_G8.js} +1250 -2992
  25. package/dist/{sandbox-guard-3tnjhjFb.js → sandbox-guard-DA2TQfZW.js} +5 -3
  26. package/dist/session-binding-C1ZXdP-x.js +627 -0
  27. package/dist/session-binding-meta-B7aEMU7g.js +6 -0
  28. package/dist/shared-client-4ICy3U6d.js +1853 -0
  29. package/dist/{side-question-C-DhgJOd.js → side-question-CMOpEhvY.js} +134 -142
  30. package/dist/{thread-lifecycle-DtT3-ehU.js → thread-lifecycle-qWE88Dn2.js} +803 -481
  31. package/dist/{web-search-provider.runtime-CkwxrXQj.js → web-search-provider.runtime-BSlriav6.js} +3 -3
  32. package/npm-shrinkwrap.json +34 -34
  33. package/openclaw.plugin.json +23 -3
  34. package/package.json +9 -6
  35. package/dist/client-CLrtWgrD.js +0 -729
  36. package/dist/client-factory-Bm6HsGob.js +0 -18
  37. package/dist/compact-aQJ0ZKhe.js +0 -278
  38. package/dist/conversation-binding-t0XMLz-j.js +0 -1557
  39. package/dist/provider-capabilities-D7hnTO76.js +0 -3201
  40. package/dist/rate-limit-cache-C7qmZ0Jh.js +0 -26
  41. package/dist/session-binding-HOuPt-E0.js +0 -338
  42. package/dist/shared-client-Dtx5i7Ez.js +0 -1013
@@ -130,11 +130,13 @@ function readRuntimeSessionEntryBestEffort(params) {
130
130
  }
131
131
  //#endregion
132
132
  //#region extensions/codex/src/app-server/sandbox-guard.ts
133
- const DIRECT_METHOD_POLICIES = new Map([
133
+ const DIRECT_METHOD_POLICIES = /* @__PURE__ */ new Map([
134
134
  ["account/rateLimits/read", "allowed-control-plane"],
135
135
  ["account/read", "allowed-control-plane"],
136
136
  ["app/list", "allowed-control-plane"],
137
137
  ["config/mcpServer/reload", "allowed-control-plane"],
138
+ ["config/read", "allowed-control-plane"],
139
+ ["config/value/write", "allowed-control-plane"],
138
140
  ["environment/add", "allowed-control-plane"],
139
141
  ["experimentalFeature/enablement/set", "allowed-control-plane"],
140
142
  ["feedback/upload", "allowed-control-plane"],
@@ -151,7 +153,7 @@ const DIRECT_METHOD_POLICIES = new Map([
151
153
  ["thread/inject_items", "allowed-control-plane"],
152
154
  ["thread/list", "allowed-control-plane"],
153
155
  ["thread/metadata/update", "allowed-control-plane"],
154
- ["thread/name/update", "allowed-control-plane"],
156
+ ["thread/name/set", "allowed-control-plane"],
155
157
  ["thread/read", "allowed-control-plane"],
156
158
  ["thread/rollback", "allowed-control-plane"],
157
159
  ["thread/start", "requires-openclaw-environment"],
@@ -182,7 +184,7 @@ const BLOCKED_DIRECT_METHOD_PREFIXES = [
182
184
  "fs/",
183
185
  "windowsSandbox/"
184
186
  ];
185
- const NODE_EXEC_BLOCKED_CONTROL_PLANE_METHODS = new Set(["config/mcpServer/reload"]);
187
+ const NODE_EXEC_BLOCKED_CONTROL_PLANE_METHODS = /* @__PURE__ */ new Set(["config/mcpServer/reload"]);
186
188
  /** Returns a block message when a direct app-server method would bypass OpenClaw execution policy. */
187
189
  function resolveCodexAppServerDirectSandboxBypassBlock(params) {
188
190
  const policy = resolveDirectMethodPolicy(params.method);
@@ -0,0 +1,627 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.js";
2
+ import { l as normalizeCodexServiceTier, t as CODEX_PLUGINS_MARKETPLACE_NAME } from "./config-CYEDnLJ2.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 { 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
+ if (resolveSessionStoreEntry({
209
+ store: loadSessionStore(resolveStorePath(params.config?.session?.store, { agentId: params.identity.agentId }), {
210
+ skipCache: true,
211
+ hydrateSkillPromptRefs: false
212
+ }),
213
+ sessionKey
214
+ }).existing?.sessionId !== params.identity.sessionId) return false;
215
+ } catch {
216
+ return false;
217
+ }
218
+ return await params.bindingStore.mutate(params.identity, {
219
+ kind: "reclaim-generation",
220
+ expectedPreviousSessionId: plan.expectedPreviousSessionId
221
+ });
222
+ }
223
+ /** Creates the single binding facade owned by the Codex plugin runtime. */
224
+ function createCodexAppServerBindingStore(state) {
225
+ const update = state.update?.bind(state);
226
+ if (!update) throw new Error("Codex app-server bindings require atomic plugin-state updates");
227
+ const leaseContext = new AsyncLocalStorage();
228
+ const renewLease = (key, owner) => {
229
+ if (owner.failure) return;
230
+ try {
231
+ let renewed = false;
232
+ const stored = update(key, (raw) => {
233
+ const current = readStoredCodexAppServerBinding(raw);
234
+ if (raw !== void 0 && !current) throw new Error(`Invalid Codex app-server binding row: ${key}`);
235
+ const lease = current?.lease;
236
+ const now = Date.now();
237
+ if (!lease || lease.token !== owner.token || lease.expiresAt <= now) return;
238
+ renewed = true;
239
+ return {
240
+ ...current,
241
+ lease: {
242
+ token: owner.token,
243
+ expiresAt: now + BINDING_LEASE_STALE_MS
244
+ }
245
+ };
246
+ });
247
+ if (!renewed || !stored) owner.failure = bindingLeaseLostError(key);
248
+ } catch (error) {
249
+ owner.failure = bindingLeaseLostError(key, error);
250
+ }
251
+ };
252
+ const transactKey = async (key, apply, ttlMs) => {
253
+ const deadline = Date.now() + BINDING_LEASE_WAIT_MS;
254
+ while (true) {
255
+ let busy = false;
256
+ let leaseLost = false;
257
+ let result;
258
+ const ownedLease = leaseContext.getStore()?.get(key);
259
+ if (ownedLease?.failure) throw ownedLease.failure;
260
+ const ownedToken = ownedLease?.token;
261
+ update(key, (raw) => {
262
+ const current = readStoredCodexAppServerBinding(raw);
263
+ if (raw !== void 0 && !current) throw new Error(`Invalid Codex app-server binding row: ${key}`);
264
+ const activeLease = current?.lease;
265
+ const now = Date.now();
266
+ if (ownedToken && (!activeLease || activeLease.token !== ownedToken || activeLease.expiresAt <= now)) {
267
+ leaseLost = true;
268
+ return;
269
+ }
270
+ if (activeLease && activeLease.token !== ownedToken && activeLease.expiresAt > now) {
271
+ busy = true;
272
+ return;
273
+ }
274
+ const applied = apply(current, ownedToken);
275
+ result = applied.result;
276
+ return applied.next;
277
+ }, ttlMs == null ? void 0 : { ttlMs });
278
+ if (leaseLost) {
279
+ const failure = bindingLeaseLostError(key);
280
+ if (ownedLease) ownedLease.failure = failure;
281
+ throw failure;
282
+ }
283
+ if (!busy) return result;
284
+ if (Date.now() >= deadline) throw new Error(`Timed out waiting for Codex binding lease: ${key}`);
285
+ await sleep(BINDING_LEASE_RETRY_INTERVAL_MS);
286
+ }
287
+ };
288
+ return {
289
+ async read(identity) {
290
+ const key = bindingStoreKey(identity);
291
+ const raw = state.lookup(key);
292
+ const stored = readStoredCodexAppServerBinding(raw);
293
+ if (raw !== void 0 && !stored) throw new Error(`Invalid Codex app-server binding row: ${key}`);
294
+ return stored?.state === "active" && ownsStoredSessionGeneration(identity, stored) ? stored.binding : void 0;
295
+ },
296
+ async prepareSessionGenerationReclaim(identity) {
297
+ const key = bindingStoreKey(identity);
298
+ const raw = state.lookup(key);
299
+ const current = readStoredCodexAppServerBinding(raw);
300
+ if (raw !== void 0 && !current) throw new Error(`Invalid Codex app-server binding row: ${key}`);
301
+ if (!current) return {
302
+ kind: "resolved",
303
+ result: true
304
+ };
305
+ const currentSessionId = current.sessionId;
306
+ if (!currentSessionId || currentSessionId === identity.sessionId) return {
307
+ kind: "resolved",
308
+ result: current.state !== "cleared" || current.retired !== true
309
+ };
310
+ return {
311
+ kind: "verify",
312
+ expectedPreviousSessionId: currentSessionId
313
+ };
314
+ },
315
+ async mutate(identity, mutation) {
316
+ const key = bindingStoreKey(identity);
317
+ const retainLegacyClear = mutation.kind === "clear" && key.startsWith("conversation:legacy-");
318
+ return await transactKey(key, (current, leaseToken) => {
319
+ const ownsGeneration = ownsStoredSessionGeneration(identity, current);
320
+ const ownedLease = current?.lease && current.lease.token === leaseToken ? { lease: current.lease } : {};
321
+ if (mutation.kind === "reclaim-generation") {
322
+ if (identity.kind !== "session" || !identity.sessionKey?.trim()) return { result: false };
323
+ if (!current) return { result: true };
324
+ if (ownsGeneration) return { result: current.state !== "cleared" || current.retired !== true };
325
+ if (current.sessionId !== mutation.expectedPreviousSessionId) return { result: false };
326
+ return {
327
+ result: true,
328
+ next: {
329
+ version: 1,
330
+ state: "cleared",
331
+ sessionId: identity.sessionId,
332
+ ...ownedLease
333
+ }
334
+ };
335
+ }
336
+ const storedActive = current?.state === "active" ? current : void 0;
337
+ const active = ownsGeneration ? storedActive : void 0;
338
+ const retiredGeneration = current?.state === "cleared" && current.retired === true && ownsGeneration;
339
+ 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 };
340
+ if (mutation.kind === "clear" && retiredGeneration) return { result: true };
341
+ if (mutation.kind === "clear") return {
342
+ result: true,
343
+ next: {
344
+ version: 1,
345
+ state: "cleared",
346
+ ...storedSessionGeneration(identity, current),
347
+ ...ownedLease
348
+ }
349
+ };
350
+ let binding;
351
+ if (mutation.kind === "set") binding = validateBindingForWrite(mutation.binding);
352
+ else binding = validateBindingForWrite({
353
+ ...active.binding,
354
+ ...mutation.patch,
355
+ threadId: mutation.threadId
356
+ });
357
+ return {
358
+ result: true,
359
+ next: {
360
+ version: 1,
361
+ state: "active",
362
+ binding,
363
+ ...storedSessionGeneration(identity, current),
364
+ ...ownedLease
365
+ }
366
+ };
367
+ }, mutation.kind === "clear" && !retainLegacyClear && !leaseContext.getStore()?.has(key) ? 1 : void 0);
368
+ },
369
+ async adoptSessionGeneration(identity, expectedPreviousSessionId) {
370
+ const key = bindingStoreKey(identity);
371
+ const expectedSessionId = expectedPreviousSessionId.trim();
372
+ const targetSessionId = identity.sessionId.trim();
373
+ if (!expectedSessionId) throw new Error("Codex session generation adoption requires the previous session id");
374
+ return await transactKey(key, (current) => {
375
+ if (current?.state !== "active") return { result: "absent" };
376
+ if (current.sessionId === targetSessionId) return { result: "current" };
377
+ if (current.sessionId !== expectedSessionId) return { result: "conflict" };
378
+ return {
379
+ result: "adopted",
380
+ next: {
381
+ ...current,
382
+ sessionId: targetSessionId
383
+ }
384
+ };
385
+ });
386
+ },
387
+ async retireSessionGeneration(identity) {
388
+ const key = bindingStoreKey(identity);
389
+ return await transactKey(key, (current, leaseToken) => {
390
+ if (!current) return { result: "absent" };
391
+ if (!ownsStoredSessionGeneration(identity, current)) return { result: "conflict" };
392
+ if (current.state === "cleared" && current.retired === true) return { result: "applied" };
393
+ return {
394
+ result: "applied",
395
+ next: {
396
+ version: 1,
397
+ state: "cleared",
398
+ retired: true,
399
+ ...storedSessionGeneration(identity, current),
400
+ ...current.lease && current.lease.token === leaseToken ? { lease: current.lease } : {}
401
+ }
402
+ };
403
+ }, identity.sessionKey?.trim() ? void 0 : PHYSICAL_SESSION_RETIRE_TTL_MS);
404
+ },
405
+ async withLease(identity, run) {
406
+ const key = bindingStoreKey(identity);
407
+ const owned = leaseContext.getStore();
408
+ const existingOwner = owned?.get(key);
409
+ if (existingOwner) {
410
+ const failureBeforeRun = existingOwner.failure;
411
+ if (failureBeforeRun) throw failureBeforeRun;
412
+ const result = await run();
413
+ const failureAfterRun = existingOwner.failure;
414
+ if (failureAfterRun) throw failureAfterRun;
415
+ return result;
416
+ }
417
+ const token = randomUUID();
418
+ if (!await transactKey(key, (current) => {
419
+ if (current?.state === "cleared" && current.retired === true && ownsStoredSessionGeneration(identity, current)) return { result: false };
420
+ const lease = {
421
+ token,
422
+ expiresAt: Date.now() + BINDING_LEASE_STALE_MS
423
+ };
424
+ if (current?.state === "active") return {
425
+ result: true,
426
+ next: {
427
+ ...current,
428
+ ...preservedSessionGeneration(identity, current),
429
+ lease
430
+ }
431
+ };
432
+ if (current?.state === "cleared" && current.retired === true) return {
433
+ result: true,
434
+ next: {
435
+ ...current,
436
+ lease
437
+ }
438
+ };
439
+ return {
440
+ result: true,
441
+ next: {
442
+ version: 1,
443
+ state: "cleared",
444
+ ...preservedSessionGeneration(identity, current),
445
+ lease
446
+ }
447
+ };
448
+ })) throw new Error(`Codex binding generation was retired: ${key}`);
449
+ const owner = { token };
450
+ const nested = new Map(owned);
451
+ nested.set(key, owner);
452
+ const heartbeat = setInterval(() => renewLease(key, owner), BINDING_LEASE_RENEW_INTERVAL_MS);
453
+ heartbeat.unref();
454
+ try {
455
+ const result = await leaseContext.run(nested, run);
456
+ if (owner.failure) throw owner.failure;
457
+ return result;
458
+ } finally {
459
+ clearInterval(heartbeat);
460
+ try {
461
+ const removeOwnedLease = (raw, matches) => {
462
+ const current = readStoredCodexAppServerBinding(raw);
463
+ if (!current || !matches(current) || current.lease?.token !== token) return;
464
+ const { lease: _lease, ...released } = current;
465
+ return released;
466
+ };
467
+ if (!update(key, (raw) => removeOwnedLease(raw, (current) => current.state === "active"))) {
468
+ 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 });
469
+ }
470
+ } catch (error) {
471
+ embeddedAgentLog.warn("failed to release codex app-server binding lease", {
472
+ key,
473
+ error
474
+ });
475
+ }
476
+ }
477
+ }
478
+ };
479
+ }
480
+ /** Stable plugin-state key for one current binding owner. */
481
+ function bindingStoreKey(identity) {
482
+ if (identity.kind === "session") {
483
+ const rawAgentId = identity.agentId.trim();
484
+ const sessionId = identity.sessionId.trim();
485
+ if (!rawAgentId) throw new Error("Codex app-server binding requires an agent id");
486
+ if (!sessionId) throw new Error("Codex app-server binding requires a session id");
487
+ const agentId = resolveSessionAgentIds({ agentId: rawAgentId }).sessionAgentId;
488
+ const sessionKey = identity.sessionKey?.trim();
489
+ if (sessionKey) return `session-key:${agentId}:${createHash("sha256").update(sessionKey).digest("base64url")}`;
490
+ return `session:${agentId}:${sessionId}`;
491
+ }
492
+ const bindingId = identity.bindingId.trim();
493
+ if (!bindingId) throw new Error("Codex app-server conversation binding requires a binding id");
494
+ return `conversation:${bindingId}`;
495
+ }
496
+ function readStoredCodexAppServerBinding(value) {
497
+ const result = storedBindingSchema.safeParse(value);
498
+ return result.success ? stripUndefinedValue(result.data) : void 0;
499
+ }
500
+ function storedSessionGeneration(identity, current) {
501
+ if (identity.kind === "session") return { sessionId: identity.sessionId };
502
+ return current?.sessionId ? { sessionId: current.sessionId } : {};
503
+ }
504
+ function preservedSessionGeneration(identity, current) {
505
+ if (current?.sessionId) return { sessionId: current.sessionId };
506
+ return storedSessionGeneration(identity, current);
507
+ }
508
+ function ownsStoredSessionGeneration(identity, current) {
509
+ return identity.kind !== "session" || !current?.sessionId || current.sessionId === identity.sessionId;
510
+ }
511
+ function validateBindingForWrite(binding) {
512
+ const validated = readCodexAppServerThreadBinding(binding);
513
+ if (!validated) throw new Error("Invalid Codex app-server thread binding");
514
+ return stripUndefinedBinding(validated);
515
+ }
516
+ /** Parses stored or shipped sidecar data into the current domain value. */
517
+ function readCodexAppServerThreadBinding(value) {
518
+ const result = threadBindingSchema.safeParse(value);
519
+ if (!result.success) return;
520
+ return result.data;
521
+ }
522
+ function stripUndefinedBinding(binding) {
523
+ return stripUndefinedValue(binding);
524
+ }
525
+ function stripUndefinedValue(value) {
526
+ if (Array.isArray(value)) return value.map(stripUndefinedValue);
527
+ if (!value || typeof value !== "object") return value;
528
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== void 0).map(([key, entry]) => [key, stripUndefinedValue(entry)]));
529
+ }
530
+ function asRecord(value) {
531
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
532
+ }
533
+ function readTimestamp(value) {
534
+ return optionalTimestampSchema.parse(value);
535
+ }
536
+ function readPluginAppPolicyContext(value, bindingSchemaVersion) {
537
+ const record = asRecord(value);
538
+ if (!record || typeof record.fingerprint !== "string") return;
539
+ const apps = asRecord(record.apps);
540
+ if (!apps) return;
541
+ const parsedApps = {};
542
+ for (const [appId, rawEntry] of Object.entries(apps)) {
543
+ const entry = asRecord(rawEntry);
544
+ if (!entry) return;
545
+ const destructiveApprovalMode = readDestructiveApprovalMode(entry.destructiveApprovalMode, bindingSchemaVersion);
546
+ const mcpServerNamesValid = Array.isArray(entry.mcpServerNames) && entry.mcpServerNames.every((serverName) => typeof serverName === "string");
547
+ if (entry.source === "account") {
548
+ if ("appId" in entry || typeof entry.appName !== "string" || typeof entry.allowDestructiveActions !== "boolean" || destructiveApprovalMode === "invalid" || !mcpServerNamesValid) return;
549
+ parsedApps[appId] = {
550
+ source: "account",
551
+ appName: entry.appName,
552
+ allowDestructiveActions: entry.allowDestructiveActions,
553
+ ...destructiveApprovalMode ? { destructiveApprovalMode } : {},
554
+ mcpServerNames: entry.mcpServerNames
555
+ };
556
+ continue;
557
+ }
558
+ 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;
559
+ parsedApps[appId] = {
560
+ configKey: entry.configKey,
561
+ marketplaceName: entry.marketplaceName,
562
+ pluginName: entry.pluginName,
563
+ allowDestructiveActions: entry.allowDestructiveActions,
564
+ ...destructiveApprovalMode ? { destructiveApprovalMode } : {},
565
+ mcpServerNames: entry.mcpServerNames
566
+ };
567
+ }
568
+ const parsedPluginAppIds = {};
569
+ if (record.pluginAppIds !== void 0 && (!record.pluginAppIds || typeof record.pluginAppIds !== "object" || Array.isArray(record.pluginAppIds))) return;
570
+ if (record.pluginAppIds && typeof record.pluginAppIds === "object") for (const [configKey, appIds] of Object.entries(record.pluginAppIds)) {
571
+ if (!Array.isArray(appIds) || appIds.some((appId) => typeof appId !== "string")) return;
572
+ parsedPluginAppIds[configKey] = appIds;
573
+ }
574
+ return {
575
+ fingerprint: record.fingerprint,
576
+ apps: parsedApps,
577
+ pluginAppIds: parsedPluginAppIds
578
+ };
579
+ }
580
+ function readDestructiveApprovalMode(value, bindingSchemaVersion) {
581
+ if (value === void 0) return;
582
+ if (value === "allow" || value === "deny") return value;
583
+ if (value === "auto") return bindingSchemaVersion === 1 ? "allow" : "auto";
584
+ if (value === "ask" && bindingSchemaVersion === 2) return "ask";
585
+ if (value === "on-request" && bindingSchemaVersion === 1) return "auto";
586
+ return "invalid";
587
+ }
588
+ function sleep(ms) {
589
+ return new Promise((resolve) => {
590
+ setTimeout(resolve, ms);
591
+ });
592
+ }
593
+ /** Returns true when an auth profile uses native Codex/OpenAI app-server auth. */
594
+ function isCodexAppServerNativeAuthProfile(lookup) {
595
+ const authProfileId = lookup.authProfileId?.trim();
596
+ if (!authProfileId) return false;
597
+ try {
598
+ const credential = (lookup.authProfileStore ?? ensureAuthProfileStore(lookup.agentDir?.trim() || resolveDefaultAgentDir(lookup.config ?? {}), {
599
+ allowKeychainPrompt: false,
600
+ config: lookup.config,
601
+ externalCliProviderIds: [CODEX_APP_SERVER_NATIVE_AUTH_PROVIDER],
602
+ externalCliProfileIds: [authProfileId]
603
+ })).profiles[authProfileId];
604
+ if (!credential || credential.type === "api_key") return false;
605
+ const provider = credential.provider?.trim();
606
+ return Boolean(provider && resolveProviderIdForAuth(provider, { config: lookup.config }) === CODEX_APP_SERVER_NATIVE_AUTH_PROVIDER);
607
+ } catch (error) {
608
+ embeddedAgentLog.debug("failed to resolve codex app-server auth profile provider", {
609
+ authProfileId,
610
+ error
611
+ });
612
+ return false;
613
+ }
614
+ }
615
+ /** Hides redundant OpenAI provider attribution for native Codex auth bindings. */
616
+ function normalizeCodexAppServerBindingModelProvider(params) {
617
+ const modelProvider = params.modelProvider?.trim();
618
+ if (!modelProvider) return;
619
+ if (isCodexAppServerNativeAuthProfile(params) && modelProvider.toLowerCase() === PUBLIC_OPENAI_MODEL_PROVIDER) return;
620
+ return modelProvider;
621
+ }
622
+ /** Restores the sole provider intentionally omitted from canonical binding rows. */
623
+ function resolveCodexAppServerBindingModelProvider(params) {
624
+ return params.modelProvider?.trim() || (isCodexAppServerNativeAuthProfile(params) ? PUBLIC_OPENAI_MODEL_PROVIDER : void 0);
625
+ }
626
+ //#endregion
627
+ 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 };
@@ -0,0 +1,6 @@
1
+ //#region extensions/codex/src/app-server/session-binding-meta.ts
2
+ /** Process-stable plugin-state metadata for Codex app-server bindings. */
3
+ const CODEX_APP_SERVER_BINDING_NAMESPACE = "app-server-thread-bindings";
4
+ const CODEX_APP_SERVER_BINDING_MAX_ENTRIES = 5e4;
5
+ //#endregion
6
+ export { CODEX_APP_SERVER_BINDING_NAMESPACE as n, CODEX_APP_SERVER_BINDING_MAX_ENTRIES as t };