Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CodexDriver.ts

385 lines14.8 KB

1import { CodexSettings, ProviderDriverKind } from "@t3tools/contracts";
2import * as Digest from "effect/crypto/Digest";
3import * as SecureRandom from "effect/crypto/SecureRandom";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Path from "effect/Path";
7import * as Schema from "effect/Schema";
8import { HttpClient } from "effect/http";
9import { ChildProcessSpawner } from "effect/process";
10​
11import type * as CodexUsageHistory from "../../usage/CodexUsageHistory.ts";
12import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
13import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
14import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
15import * as ServerConfig from "../../config.ts";
16import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
17import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
18import {
19 createCodexAdapterV2,
20 type CodexAdapterV2DriverEnv,
21} from "../../orchestration-v2/Adapters/CodexAdapterV2.ts";
22import { ProviderDriverError } from "../Errors.ts";
23import * as ResetCreditCoordinator from "../resetCreditCoordinator.ts";
24import {
25 checkCodexProviderStatus,
26 makePendingCodexProvider,
27 probeCodexSkillsForCwd,
28 withCodexAppServerClient,
29} from "../CodexProvider.ts";
30import { resolveCodexLaunchArgs } from "../codexLaunchArgs.ts";
31import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
32import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog";
33import { applyCodexModelCatalog } from "../codexModelCatalog.ts";
34import type { ProviderDriver, ProviderInstance } from "@t3tools/provider-core/server/driver";
35import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity";
36import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
37import {
38 enrichProviderSnapshotWithVersionAdvisory,
39 makeCachedProviderMaintenanceResolution,
40 makePackageManagedProviderMaintenanceResolver,
41 resolveProviderMaintenanceCapabilitiesEffect,
42} from "@t3tools/provider-core/server/maintenanceResolver";
43import {
44 haveProviderSnapshotSettingsChanged,
45 makeProviderSnapshotSettingsSource,
46 type ProviderSnapshotSettings,
47} from "@t3tools/provider-core/server/snapshotSettings";
48import {
49 codexContinuationIdentity,
50 materializeCodexShadowHome,
51 resolveCodexHomeLayout,
52} from "./CodexHomeLayout.ts";
53import { makeManagedCodexProvider } from "./CodexManagedProvider.ts";
54import { codexUsageReader } from "./codexUsage.ts";
55import * as CodexInstallation from "../CodexInstallation.ts";
56import * as CodexManagedTokenBroker from "../CodexManagedTokenBroker.ts";
57import * as ServerSecretStore from "../../auth/ServerSecretStore.ts";
58import * as ServerEnvironment from "../../environment/ServerEnvironment.ts";
59import * as HostProcess from "@t3tools/shared/HostProcess";
60const decodeCodexSettings = Schema.decodeSync(CodexSettings);
61​
62const DRIVER_KIND = ProviderDriverKind.make("codex");
63const CODEX_STANDALONE_HOME_PATTERN = /^(.*)\/packages\/standalone\//is;
64​
65function codexStandaloneHome(commandPath: string): string | null {
66 // Slash replacement preserves indices; Unicode lowercasing can change the path length.
67 const match = CODEX_STANDALONE_HOME_PATTERN.exec(commandPath.replaceAll("\\", "/"));
68 if (!match) {
69 return null;
70 }
71 const home = match[1]!;
72 // Keep root separators: `C:` is drive-relative, and an empty home is not `/`.
73 const isRoot = home === "" || /^[a-z]:$/i.test(home);
74 return commandPath.slice(0, home.length + (isRoot ? 1 : 0));
76​
77// Standalone updates locate their install through CODEX_HOME. Account and auth-overlay
78// homes can share an executable, so only the updater uses the executable's owning home.
79function makeCodexMaintenanceResolver(sharedHomePath: string) {
80 return makePackageManagedProviderMaintenanceResolver({
81 provider: DRIVER_KIND,
82 npmPackageName: "@openai/codex",
83 nativeUpdate: {
84 args: ["update"],
85 isCommandPath: (commandPath) => codexStandaloneHome(commandPath) !== null,
86 requiresCommandPath: true,
87 env: (context) => ({
88 CODEX_HOME:
89 codexStandaloneHome(context.realCommandPath) ??
90 codexStandaloneHome(context.resolvedCommandPath) ??
91 sharedHomePath,
92 }),
93 },
94 });
96​
97export type CodexDriverEnv =
98 | CodexAdapterV2DriverEnv
99 | ProviderHost.ProviderHost
100 | ChildProcessSpawner.ChildProcessSpawner
101 | ResetCreditCoordinator.ResetCreditCoordinator
102 | Digest.Digest
103 | SecureRandom.SecureRandom
104 | FileSystem.FileSystem
105 | HttpClient.HttpClient
106 | ProviderLatestVersions.ProviderLatestVersions
107 | ModelCatalog.ModelCatalog
108 | Path.Path
109 | ProviderEventLoggers.ProviderEventLoggers
110 | ServerConfig.ServerConfig
111 | ServerSecretStore.ServerSecretStore
112 | ServerEnvironment.ServerEnvironmentIdentity
113 | CodexInstallation.CodexInstallation
114 | CodexManagedTokenBroker.CodexManagedTokenBroker;
115​
116export const CodexDriver: ProviderDriver<
117 CodexSettings,
118 CodexDriverEnv,
119 Path.Path | CodexUsageHistory.CodexUsageHistory
120> = {
121 driverKind: DRIVER_KIND,
122 metadata: {
123 displayName: "Codex",
124 supportsMultipleInstances: true,
125 },
126 configSchema: CodexSettings,
127 defaultConfig: (): CodexSettings => decodeCodexSettings({}),
128 usage: codexUsageReader,
129 create: Effect.fn("CodexDriver.create")(function* ({
130 instanceId,
131 displayName,
132 accentColor,
133 environment,
134 enabled,
135 config,
136 }) {
137 if (config.setupMode === "managed")
138 return yield* makeManagedCodexProvider({
139 instanceId,
140 displayName,
141 accentColor,
142 environment,
143 enabled,
144 config,
145 });
146 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
147 const resetCreditCoordinator = yield* ResetCreditCoordinator.ResetCreditCoordinator;
148 const fileSystem = yield* FileSystem.FileSystem;
149 const pathService = yield* Path.Path;
150 const httpClient = yield* HttpClient.HttpClient;
151 const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
152 const installation = yield* CodexInstallation.CodexInstallation;
153 const modelCatalog = yield* ModelCatalog.ModelCatalog;
154 const currentCatalog = modelCatalog.current(DRIVER_KIND);
155 const processEnv = yield* mergeProviderInstanceEnvironment(
156 environment,
157 yield* HostProcess.Environment,
158 );
159 const environmentHome = processEnv.CODEX_HOME;
160 const homeLayout = yield* resolveCodexHomeLayout(
161 !config.homePath.trim() && !config.shadowHomePath.trim() && environmentHome?.trim()
162 ? { ...config, homePath: environmentHome }
163 : config,
164 );
165 const continuationIdentity = codexContinuationIdentity(homeLayout);
166 const stampIdentity = withInstanceIdentity({
167 instanceId,
168 driverKind: DRIVER_KIND,
169 displayName,
170 accentColor,
171 continuationGroupKey: continuationIdentity.continuationKey,
172 });
173 yield* materializeCodexShadowHome(homeLayout).pipe(
174 Effect.mapError(
175 (cause) =>
176 new ProviderDriverError({
177 driver: DRIVER_KIND,
178 instanceId,
179 detail: cause.message,
180 cause,
181 }),
182 ),
183 );
184 const effectiveConfig = {
185 ...config,
186 enabled,
187 binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),
188 homePath: homeLayout.effectiveHomePath ?? "",
189 } satisfies CodexSettings;
190 const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
191 resolveProviderMaintenanceCapabilitiesEffect(
192 makeCodexMaintenanceResolver(homeLayout.sharedHomePath),
193 {
194 binaryPath: effectiveConfig.binaryPath,
195 env: processEnv,
196 },
197 ).pipe(
198 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
199 Effect.provideService(FileSystem.FileSystem, fileSystem),
200 Effect.provideService(Path.Path, pathService),
201 ),
202 );
203​
204 const orchestrationAdapter = yield* createCodexAdapterV2(
205 {
206 instanceId,
207 displayName,
208 accentColor,
209 environment,
210 enabled,
211 config,
212 },
213 {
214 onUsageLimits: (update) => snapshot.applyUsageLimits(update),
215 compatibility: installation.compatibility,
216 },
217 ).pipe(
218 Effect.mapError(
219 (cause) =>
220 new ProviderDriverError({
221 driver: DRIVER_KIND,
222 instanceId,
223 detail: "Failed to build Codex orchestration adapter.",
224 cause,
225 }),
226 ),
227 );
228​
229 // Kick the TTL-gated manifest refresh in the background and classify with the in-memory
230 // manifest, so a slow or hung fetch never delays the provider check.
231 const checkProvider = modelCatalog.refreshInBackground.pipe(
232 Effect.andThen(
233 Effect.zipWith(
234 checkCodexProviderStatus(effectiveConfig, undefined, processEnv),
235 currentCatalog,
236 (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)),
237 { concurrent: true },
238 ),
239 ),
240 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
241 Effect.provideService(FileSystem.FileSystem, fileSystem),
242 Effect.provideService(Path.Path, pathService),
243 );
244 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
245 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CodexSettings>>({
246 resolveMaintenance,
247 getSettings: snapshotSettings.getSettings,
248 streamSettings: snapshotSettings.streamSettings,
249 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
250 initialSnapshot: (settings) =>
251 Effect.zipWith(
252 makePendingCodexProvider(settings.provider),
253 currentCatalog,
254 (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)),
255 ),
256 checkProvider,
257 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
258 resolveMaintenance().pipe(
259 Effect.flatMap((maintenanceCapabilities) =>
260 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
261 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
262 }),
263 ),
264 Effect.provideService(HttpClient.HttpClient, httpClient),
265 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
266 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
267 ),
268 }).pipe(
269 Effect.mapError(
270 (cause) =>
271 new ProviderDriverError({
272 driver: DRIVER_KIND,
273 instanceId,
274 detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,
275 cause,
276 }),
277 ),
278 );
279 const textGeneration = yield* makeCodexTextGeneration(
280 effectiveConfig,
281 processEnv,
282 snapshot.getSnapshot.pipe(Effect.map((value) => value.models)),
283 );
284 const snapshotForCwd = (cwd: string) =>
285 !effectiveConfig.enabled
286 ? snapshot.getSnapshot
287 : Effect.all([
288 snapshot.getSnapshot,
289 probeCodexSkillsForCwd({
290 binaryPath: effectiveConfig.binaryPath,
291 homePath: effectiveConfig.homePath,
292 launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),
293 cwd,
294 environment: processEnv,
295 }).pipe(
296 Effect.scoped,
297 Effect.timeout("20 seconds"),
298 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
299 ),
300 ]).pipe(
301 Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })),
302 Effect.mapError(
303 (cause) =>
304 new ProviderDriverError({
305 driver: DRIVER_KIND,
306 instanceId,
307 detail: `Failed to probe Codex skills for '${cwd}'`,
308 cause,
309 }),
310 ),
311 );
312​
313 // Redemption spends account credit; serialize by the auth.json directory, keep one idempotency key
314 // until the outcome, and bound the wait so a hung app-server cannot hold the account lock.
315 // Auth overlays use effectiveHomePath; the continuation key would conflate them with shared homes.
316 const accountKey = homeLayout.effectiveHomePath ?? homeLayout.sharedHomePath;
317 const consumeResetCredit: NonNullable<ProviderInstance["consumeResetCredit"]> = () =>
318 resetCreditCoordinator
319 .redeem(accountKey, (idempotencyKey) =>
320 Effect.gen(function* () {
321 const { client } = yield* withCodexAppServerClient({
322 binaryPath: effectiveConfig.binaryPath,
323 homePath: effectiveConfig.homePath,
324 launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),
325 cwd: process.cwd(),
326 environment: processEnv,
327 });
328 const response = yield* client.request("account/rateLimitResetCredit/consume", {
329 idempotencyKey,
330 });
331 return response.outcome;
332 }).pipe(Effect.scoped, Effect.timeout("20 seconds")),
333 )
334 .pipe(
335 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
336 Effect.mapError(
337 (cause) =>
338 new ProviderDriverError({
339 driver: DRIVER_KIND,
340 instanceId,
341 detail: "Codex could not redeem the reset credit.",
342 cause,
343 }),
344 ),
345 // The windows just changed; re-probe so the snapshot says so. A
346 // failed probe republishes the pre-redemption limits rather than
347 // marking them failed, so "confirmed" means `checkedAt` moved past
348 // what was published before the redemption started.
349 Effect.tap((outcome) =>
350 Effect.gen(function* () {
351 const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt;
352 const refreshed = yield* snapshot.refresh;
353 const after = refreshed.usageLimits?.checkedAt;
354 if (
355 outcome === "reset" &&
356 (after === undefined ||
357 after === before ||
358 refreshed.usageLimits?.unavailable?.reason === "probeFailed")
359 ) {
360 return yield* new ProviderDriverError({
361 driver: DRIVER_KIND,
362 instanceId,
363 detail:
364 "The reset was applied, but Codex could not confirm the new limits. Refresh to check.",
365 });
366 }
367 }),
368 ),
369 );
370​
371 return {
372 instanceId,
373 driverKind: DRIVER_KIND,
374 continuationIdentity,
375 displayName,
376 accentColor,
377 enabled,
378 snapshot,
379 snapshotForCwd,
380 consumeResetCredit,
381 orchestrationAdapter,
382 textGeneration,
383 } satisfies ProviderInstance;
384 }),
385};