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

CodexDriver.ts

383 lines14.7 KB

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