Skip to content

Commit 1065e34

Browse files
committed
refactor(codex): extract thread lifecycle preflight
1 parent dffbd2b commit 1065e34

3 files changed

Lines changed: 178 additions & 133 deletions

File tree

‎extensions/codex/src/app-server/native-skill-isolation.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,11 @@ async function collectPersonalSkillRealPaths(
7979
const skillPaths = new Set<string>();
8080
let complete = true;
8181
const seenDirectories = new Set<string>();
82-
const queue = roots.map((root) => ({ ...root, depth: 0 }));
82+
const queue = roots.map((root) => ({
83+
dir: root.dir,
84+
onlyEscapedStateTargets: root.onlyEscapedStateTargets,
85+
depth: 0,
86+
}));
8387
let entryCount = 0;
8488
const recordSkillFile = async (filePath: string, onlyEscapedStateTargets: boolean) => {
8589
try {
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
import {
2+
embeddedAgentLog,
3+
formatErrorMessage,
4+
isHostScopedAgentToolActive,
5+
} from "openclaw/plugin-sdk/agent-harness-runtime";
6+
import { buildCodexUserMcpServersThreadConfigPatchForRuntime } from "openclaw/plugin-sdk/codex-mcp-projection";
7+
import { getCodexAppServerClientInstanceId } from "./client.js";
8+
import { isSystemAgentOnlyCodexDynamicToolAllowlist } from "./dynamic-tool-profile.js";
9+
import { resolveCodexNativeSkillIsolation } from "./native-skill-isolation.js";
10+
import { isCodexAppServerProfilerEnabled } from "./profiler-flag.js";
11+
import { flattenCodexDynamicToolFunctions } from "./protocol.js";
12+
import { hashCodexAppServerBindingFingerprint } from "./session-binding.js";
13+
import { buildContextEngineBinding } from "./thread-context-engine.js";
14+
import {
15+
codexLegacyDynamicToolsFingerprint as legacyFingerprintDynamicTools,
16+
fingerprintEnvironmentSelection,
17+
fingerprintJsonObject,
18+
fingerprintUserMcpServersConfigPatch,
19+
legacyFingerprintUserMcpServersConfigPatch,
20+
} from "./thread-fingerprints.js";
21+
import { createCodexThreadLifecycleTimingTracker } from "./thread-lifecycle-timing.js";
22+
import type { CodexStartOrResumeThreadParams } from "./thread-lifecycle-types.js";
23+
import {
24+
assertCodexRingZeroHasNoManagedHooks,
25+
buildCodexRingZeroThreadConfigPatch,
26+
CODEX_RING_ZERO_BASE_INSTRUCTIONS,
27+
readCodexInheritedMcpServerNames,
28+
} from "./thread-requests.js";
29+
import { resolveCodexWebSearchPlan } from "./web-search.js";
30+
31+
export async function prepareCodexThreadLifecyclePreflight(params: CodexStartOrResumeThreadParams) {
32+
// Thread lifecycle spans are useful when profiling startup churn, but normal
33+
// turns should not pay Date.now/span-array overhead while resuming threads.
34+
const lifecycleTiming = createCodexThreadLifecycleTimingTracker({
35+
...params.timing,
36+
enabled: params.timing?.enabled ?? isCodexAppServerProfilerEnabled(params.params.config),
37+
});
38+
const legacyDynamicToolsFingerprint = lifecycleTiming.measureSync(
39+
"legacy-dynamic-tools-fingerprint",
40+
() => legacyFingerprintDynamicTools(params.dynamicTools),
41+
);
42+
const dynamicToolsFingerprint = lifecycleTiming.measureSync("dynamic-tools-fingerprint", () =>
43+
hashCodexAppServerBindingFingerprint(legacyDynamicToolsFingerprint),
44+
);
45+
const dynamicToolsContainDeferred = flattenCodexDynamicToolFunctions(params.dynamicTools).some(
46+
(tool) => tool.deferLoading === true,
47+
);
48+
const webSearchPlan = lifecycleTiming.measureSync("web-search-plan", () =>
49+
resolveCodexWebSearchPlan({
50+
config: params.params.config,
51+
disableTools: params.params.disableTools,
52+
nativeToolSurfaceEnabled: params.nativeCodeModeEnabled,
53+
nativeProviderWebSearchSupport: params.nativeProviderWebSearchSupport,
54+
webSearchAllowed: params.webSearchAllowed,
55+
}),
56+
);
57+
const webSearchThreadConfigFingerprint = fingerprintJsonObject(webSearchPlan.threadConfig);
58+
const networkProxyConfigFingerprint = params.appServer.networkProxy?.configFingerprint;
59+
const contextEngineBinding = lifecycleTiming.measureSync("context-engine-binding", () =>
60+
buildContextEngineBinding(params.params, params.contextEngineProjection),
61+
);
62+
const userMcpServersConfigPatch =
63+
params.userMcpServersEnabled === false
64+
? undefined
65+
: await buildCodexUserMcpServersThreadConfigPatchForRuntime(params.params.config, {
66+
agentId: params.agentId ?? params.params.agentId,
67+
agentDir: params.params.agentDir,
68+
allowLiteralOAuthProjection: params.appServer.connectionClass !== "remote",
69+
onServerUnavailable: (serverName, error) =>
70+
embeddedAgentLog.warn("skipping unavailable MCP OAuth server", {
71+
serverName,
72+
error: formatErrorMessage(error),
73+
}),
74+
});
75+
const nativeSkillIsolation = await lifecycleTiming.measure("native-skill-isolation", () =>
76+
resolveCodexNativeSkillIsolation({
77+
client: params.client,
78+
codexHome: params.appServer.start.env?.CODEX_HOME,
79+
cwd: params.cwd,
80+
home: params.appServer.start.env?.HOME,
81+
signal: params.signal,
82+
userProfile: params.appServer.start.env?.USERPROFILE,
83+
}),
84+
);
85+
const nativeSkillIsolationFingerprint = nativeSkillIsolation
86+
? fingerprintJsonObject({
87+
version: 1,
88+
disabledUserSkillPaths: nativeSkillIsolation.disabledUserSkillPaths,
89+
})
90+
: undefined;
91+
const legacyUserMcpServersFingerprint =
92+
legacyFingerprintUserMcpServersConfigPatch(userMcpServersConfigPatch);
93+
const userMcpServersFingerprint = fingerprintUserMcpServersConfigPatch(userMcpServersConfigPatch);
94+
const environmentSelectionFingerprint = fingerprintEnvironmentSelection(
95+
params.environmentSelection,
96+
);
97+
const hostSystemAgentActive =
98+
params.hostSystemAgentActive ?? isHostScopedAgentToolActive("openclaw");
99+
const ringZeroActive =
100+
hostSystemAgentActive && isSystemAgentOnlyCodexDynamicToolAllowlist(params.params.toolsAllow);
101+
if (ringZeroActive && params.nativeCodeModeEnabled !== false) {
102+
throw new Error("Codex ring-zero requires native code mode to be disabled");
103+
}
104+
const ringZeroInheritedMcpServerNames = ringZeroActive
105+
? await lifecycleTiming.measure("ring-zero-mcp-config-read", () =>
106+
readCodexInheritedMcpServerNames(params.client, params.cwd, params.signal),
107+
)
108+
: [];
109+
if (ringZeroActive) {
110+
await lifecycleTiming.measure("ring-zero-config-requirements-read", () =>
111+
assertCodexRingZeroHasNoManagedHooks(params.client, params.signal),
112+
);
113+
}
114+
const ringZeroConfigFingerprint = ringZeroActive
115+
? fingerprintJsonObject({
116+
version: 1,
117+
baseInstructions: CODEX_RING_ZERO_BASE_INSTRUCTIONS,
118+
config: buildCodexRingZeroThreadConfigPatch(
119+
params.params,
120+
true,
121+
ringZeroInheritedMcpServerNames,
122+
)!,
123+
})
124+
: undefined;
125+
const ringZeroClientInstanceId = ringZeroActive
126+
? getCodexAppServerClientInstanceId(params.client)
127+
: undefined;
128+
return {
129+
contextEngineBinding,
130+
dynamicToolsContainDeferred,
131+
dynamicToolsFingerprint,
132+
environmentSelectionFingerprint,
133+
hostSystemAgentActive,
134+
legacyDynamicToolsFingerprint,
135+
legacyUserMcpServersFingerprint,
136+
lifecycleTiming,
137+
nativeSkillIsolation,
138+
nativeSkillIsolationFingerprint,
139+
networkProxyConfigFingerprint,
140+
ringZeroActive,
141+
ringZeroClientInstanceId,
142+
ringZeroConfigFingerprint,
143+
ringZeroInheritedMcpServerNames,
144+
userMcpServersConfigPatch,
145+
userMcpServersFingerprint,
146+
webSearchThreadConfigFingerprint,
147+
};
148+
}

‎extensions/codex/src/app-server/thread-lifecycle-run.ts‎

Lines changed: 25 additions & 132 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,17 @@
1-
import {
2-
embeddedAgentLog,
3-
formatErrorMessage,
4-
isHostScopedAgentToolActive,
5-
} from "openclaw/plugin-sdk/agent-harness-runtime";
6-
import { buildCodexUserMcpServersThreadConfigPatchForRuntime } from "openclaw/plugin-sdk/codex-mcp-projection";
1+
import { embeddedAgentLog } from "openclaw/plugin-sdk/agent-harness-runtime";
72
import { isIncognitoSessionKey } from "../incognito-session.js";
83
import { closeCodexStartupClientBestEffort } from "./attempt-client-cleanup.js";
9-
import {
10-
getCodexAppServerClientInstanceId,
11-
resolveCodexAppServerClientInstanceId,
12-
} from "./client.js";
13-
import { isSystemAgentOnlyCodexDynamicToolAllowlist } from "./dynamic-tool-profile.js";
14-
import {
15-
applyCodexNativeSkillIsolation,
16-
resolveCodexNativeSkillIsolation,
17-
} from "./native-skill-isolation.js";
4+
import { resolveCodexAppServerClientInstanceId } from "./client.js";
5+
import { applyCodexNativeSkillIsolation } from "./native-skill-isolation.js";
186
import { buildCodexAppServerConnectionFingerprint } from "./plugin-app-cache-key.js";
197
import {
208
isCodexPluginThreadBindingStale,
219
mergeCodexThreadConfigs,
2210
type CodexPluginThreadConfig,
2311
} from "./plugin-thread-config.js";
24-
import { isCodexAppServerProfilerEnabled } from "./profiler-flag.js";
25-
import { flattenCodexDynamicToolFunctions } from "./protocol.js";
2612
import {
2713
assertCodexBindingMayBeReplaced,
2814
createCodexSessionGenerationSupersededError,
29-
hashCodexAppServerBindingFingerprint,
3015
normalizeCodexAppServerBindingModelProvider,
3116
reclaimCurrentCodexSessionGeneration,
3217
sessionBindingIdentity,
@@ -40,23 +25,15 @@ import {
4025
shouldRotateCodexAppServerBindingForRuntime,
4126
shouldRotateCodexGpt56MultiAgentBinding,
4227
} from "./thread-binding-policy.js";
43-
import {
44-
buildContextEngineBinding,
45-
isContextEngineBindingCompatible,
46-
} from "./thread-context-engine.js";
28+
import { isContextEngineBindingCompatible } from "./thread-context-engine.js";
4729
import {
4830
areDynamicToolFingerprintsCompatible,
4931
areUserMcpServersFingerprintsCompatible,
50-
codexLegacyDynamicToolsFingerprint as legacyFingerprintDynamicTools,
51-
fingerprintEnvironmentSelection,
52-
fingerprintJsonObject,
53-
fingerprintUserMcpServersConfigPatch,
54-
legacyFingerprintUserMcpServersConfigPatch,
5532
shouldStartTransientNoToolThread,
5633
} from "./thread-fingerprints.js";
5734
import { CodexThreadBindingConflictError } from "./thread-lifecycle-errors.js";
5835
import { resumeExistingCodexThread, startFreshCodexThread } from "./thread-lifecycle-io.js";
59-
import { createCodexThreadLifecycleTimingTracker } from "./thread-lifecycle-timing.js";
36+
import { prepareCodexThreadLifecyclePreflight } from "./thread-lifecycle-preflight.js";
6037
import type {
6138
CodexAppServerThreadLifecycleBinding,
6239
CodexStartOrResumeThreadParams,
@@ -68,14 +45,7 @@ import {
6845
tryReuseCodexLiveThread,
6946
} from "./thread-lifecycle-warm.js";
7047
import { resolveCodexAppServerThreadModelSelection } from "./thread-model-selection.js";
71-
import {
72-
assertCodexRingZeroHasNoManagedHooks,
73-
buildCodexRingZeroThreadConfigPatch,
74-
CODEX_RING_ZERO_BASE_INSTRUCTIONS,
75-
readCodexInheritedMcpServerNames,
76-
} from "./thread-requests.js";
7748
import { materializePendingSupervisionBranch } from "./thread-supervision.js";
78-
import { resolveCodexWebSearchPlan } from "./web-search.js";
7949

8050
export async function startOrResumeThread(
8151
params: CodexStartOrResumeThreadParams,
@@ -89,103 +59,26 @@ export async function startOrResumeThread(
8959
config: params.params.config,
9060
});
9161
return await params.bindingStore.withLease(bindingIdentity, async () => {
92-
// Thread lifecycle spans are useful when profiling startup churn, but normal
93-
// turns should not pay Date.now/span-array overhead while resuming threads.
94-
const lifecycleTiming = createCodexThreadLifecycleTimingTracker({
95-
...params.timing,
96-
enabled: params.timing?.enabled ?? isCodexAppServerProfilerEnabled(params.params.config),
97-
});
98-
const legacyDynamicToolsFingerprint = lifecycleTiming.measureSync(
99-
"legacy-dynamic-tools-fingerprint",
100-
() => legacyFingerprintDynamicTools(params.dynamicTools),
101-
);
102-
const dynamicToolsFingerprint = lifecycleTiming.measureSync("dynamic-tools-fingerprint", () =>
103-
hashCodexAppServerBindingFingerprint(legacyDynamicToolsFingerprint),
104-
);
105-
const dynamicToolsContainDeferred = flattenCodexDynamicToolFunctions(params.dynamicTools).some(
106-
(tool) => tool.deferLoading === true,
107-
);
108-
const webSearchPlan = lifecycleTiming.measureSync("web-search-plan", () =>
109-
resolveCodexWebSearchPlan({
110-
config: params.params.config,
111-
disableTools: params.params.disableTools,
112-
nativeToolSurfaceEnabled: params.nativeCodeModeEnabled,
113-
nativeProviderWebSearchSupport: params.nativeProviderWebSearchSupport,
114-
webSearchAllowed: params.webSearchAllowed,
115-
}),
116-
);
117-
const webSearchThreadConfigFingerprint = fingerprintJsonObject(webSearchPlan.threadConfig);
118-
const networkProxyConfigFingerprint = params.appServer.networkProxy?.configFingerprint;
119-
const contextEngineBinding = lifecycleTiming.measureSync("context-engine-binding", () =>
120-
buildContextEngineBinding(params.params, params.contextEngineProjection),
121-
);
122-
const userMcpServersConfigPatch =
123-
params.userMcpServersEnabled === false
124-
? undefined
125-
: await buildCodexUserMcpServersThreadConfigPatchForRuntime(params.params.config, {
126-
agentId: params.agentId ?? params.params.agentId,
127-
agentDir: params.params.agentDir,
128-
allowLiteralOAuthProjection: params.appServer.connectionClass !== "remote",
129-
onServerUnavailable: (serverName, error) =>
130-
embeddedAgentLog.warn("skipping unavailable MCP OAuth server", {
131-
serverName,
132-
error: formatErrorMessage(error),
133-
}),
134-
});
135-
const nativeSkillIsolation = await lifecycleTiming.measure("native-skill-isolation", () =>
136-
resolveCodexNativeSkillIsolation({
137-
client: params.client,
138-
codexHome: params.appServer.start.env?.CODEX_HOME,
139-
cwd: params.cwd,
140-
home: params.appServer.start.env?.HOME,
141-
signal: params.signal,
142-
userProfile: params.appServer.start.env?.USERPROFILE,
143-
}),
144-
);
145-
const nativeSkillIsolationFingerprint = nativeSkillIsolation
146-
? fingerprintJsonObject({
147-
version: 1,
148-
disabledUserSkillPaths: nativeSkillIsolation.disabledUserSkillPaths,
149-
})
150-
: undefined;
151-
const legacyUserMcpServersFingerprint =
152-
legacyFingerprintUserMcpServersConfigPatch(userMcpServersConfigPatch);
153-
const userMcpServersFingerprint =
154-
fingerprintUserMcpServersConfigPatch(userMcpServersConfigPatch);
155-
const environmentSelectionFingerprint = fingerprintEnvironmentSelection(
156-
params.environmentSelection,
157-
);
158-
const hostSystemAgentActive =
159-
params.hostSystemAgentActive ?? isHostScopedAgentToolActive("openclaw");
160-
const ringZeroActive =
161-
hostSystemAgentActive && isSystemAgentOnlyCodexDynamicToolAllowlist(params.params.toolsAllow);
162-
if (ringZeroActive && params.nativeCodeModeEnabled !== false) {
163-
throw new Error("Codex ring-zero requires native code mode to be disabled");
164-
}
165-
const ringZeroInheritedMcpServerNames = ringZeroActive
166-
? await lifecycleTiming.measure("ring-zero-mcp-config-read", () =>
167-
readCodexInheritedMcpServerNames(params.client, params.cwd, params.signal),
168-
)
169-
: [];
170-
if (ringZeroActive) {
171-
await lifecycleTiming.measure("ring-zero-config-requirements-read", () =>
172-
assertCodexRingZeroHasNoManagedHooks(params.client, params.signal),
173-
);
174-
}
175-
const ringZeroConfigFingerprint = ringZeroActive
176-
? fingerprintJsonObject({
177-
version: 1,
178-
baseInstructions: CODEX_RING_ZERO_BASE_INSTRUCTIONS,
179-
config: buildCodexRingZeroThreadConfigPatch(
180-
params.params,
181-
true,
182-
ringZeroInheritedMcpServerNames,
183-
)!,
184-
})
185-
: undefined;
186-
const ringZeroClientInstanceId = ringZeroActive
187-
? getCodexAppServerClientInstanceId(params.client)
188-
: undefined;
62+
const {
63+
contextEngineBinding,
64+
dynamicToolsContainDeferred,
65+
dynamicToolsFingerprint,
66+
environmentSelectionFingerprint,
67+
hostSystemAgentActive,
68+
legacyDynamicToolsFingerprint,
69+
legacyUserMcpServersFingerprint,
70+
lifecycleTiming,
71+
nativeSkillIsolation,
72+
nativeSkillIsolationFingerprint,
73+
networkProxyConfigFingerprint,
74+
ringZeroActive,
75+
ringZeroClientInstanceId,
76+
ringZeroConfigFingerprint,
77+
ringZeroInheritedMcpServerNames,
78+
userMcpServersConfigPatch,
79+
userMcpServersFingerprint,
80+
webSearchThreadConfigFingerprint,
81+
} = await prepareCodexThreadLifecyclePreflight(params);
18982
let binding = await lifecycleTiming.measure("read-binding", () =>
19083
params.bindingStore.read(bindingIdentity),
19184
);

0 commit comments

Comments
 (0)