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

CodexDriver.ts

375 lines14.5 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(environment);
154 const homeLayout = yield* resolveCodexHomeLayout(config);
155 const continuationIdentity = codexContinuationIdentity(homeLayout);
156 const stampIdentity = withInstanceIdentity({
157 instanceId,
158 driverKind: DRIVER_KIND,
159 displayName,
160 accentColor,
161 continuationGroupKey: continuationIdentity.continuationKey,
162 });
163 yield* materializeCodexShadowHome(homeLayout).pipe(
164 Effect.mapError(
165 (cause) =>
166 new ProviderDriverError({
167 driver: DRIVER_KIND,
168 instanceId,
169 detail: cause.message,
170 cause,
171 }),
172 ),
173 );
174 const effectiveConfig = {
175 ...config,
176 enabled,
177 binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),
178 homePath: homeLayout.effectiveHomePath ?? "",
179 } satisfies CodexSettings;
180 const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
181 resolveProviderMaintenanceCapabilitiesEffect(
182 makeCodexMaintenanceResolver(homeLayout.sharedHomePath),
183 {
184 binaryPath: effectiveConfig.binaryPath,
185 env: processEnv,
186 },
187 ).pipe(
188 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
189 Effect.provideService(FileSystem.FileSystem, fileSystem),
190 Effect.provideService(Path.Path, pathService),
191 ),
192 );
193​
194 const orchestrationAdapter = yield* createCodexAdapterV2(
195 {
196 instanceId,
197 displayName,
198 accentColor,
199 environment,
200 enabled,
201 config,
202 },
203 {
204 onUsageLimits: (update) => snapshot.applyUsageLimits(update),
205 compatibility: installation.compatibility,
206 },
207 ).pipe(
208 Effect.mapError(
209 (cause) =>
210 new ProviderDriverError({
211 driver: DRIVER_KIND,
212 instanceId,
213 detail: "Failed to build Codex orchestration adapter.",
214 cause,
215 }),
216 ),
217 );
218​
219 // Kick the TTL-gated manifest refresh in the background and classify with the in-memory
220 // manifest, so a slow or hung fetch never delays the provider check.
221 const checkProvider = modelCatalog.refreshInBackground.pipe(
222 Effect.andThen(
223 Effect.zipWith(
224 checkCodexProviderStatus(effectiveConfig, undefined, processEnv),
225 currentCatalog,
226 (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)),
227 { concurrent: true },
228 ),
229 ),
230 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
231 Effect.provideService(FileSystem.FileSystem, fileSystem),
232 Effect.provideService(Path.Path, pathService),
233 );
234 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
235 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CodexSettings>>({
236 resolveMaintenance,
237 getSettings: snapshotSettings.getSettings,
238 streamSettings: snapshotSettings.streamSettings,
239 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
240 initialSnapshot: (settings) =>
241 Effect.zipWith(
242 makePendingCodexProvider(settings.provider),
243 currentCatalog,
244 (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)),
245 ),
246 checkProvider,
247 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
248 resolveMaintenance().pipe(
249 Effect.flatMap((maintenanceCapabilities) =>
250 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
251 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
252 }),
253 ),
254 Effect.provideService(HttpClient.HttpClient, httpClient),
255 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
256 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
257 ),
258 }).pipe(
259 Effect.mapError(
260 (cause) =>
261 new ProviderDriverError({
262 driver: DRIVER_KIND,
263 instanceId,
264 detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,
265 cause,
266 }),
267 ),
268 );
269 const textGeneration = yield* makeCodexTextGeneration(
270 effectiveConfig,
271 processEnv,
272 snapshot.getSnapshot.pipe(Effect.map((value) => value.models)),
273 );
274 const snapshotForCwd = (cwd: string) =>
275 !effectiveConfig.enabled
276 ? snapshot.getSnapshot
277 : Effect.all([
278 snapshot.getSnapshot,
279 probeCodexSkillsForCwd({
280 binaryPath: effectiveConfig.binaryPath,
281 homePath: effectiveConfig.homePath,
282 launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),
283 cwd,
284 environment: processEnv,
285 }).pipe(
286 Effect.scoped,
287 Effect.timeout("20 seconds"),
288 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
289 ),
290 ]).pipe(
291 Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })),
292 Effect.mapError(
293 (cause) =>
294 new ProviderDriverError({
295 driver: DRIVER_KIND,
296 instanceId,
297 detail: `Failed to probe Codex skills for '${cwd}'`,
298 cause,
299 }),
300 ),
301 );
302​
303 // Redemption spends account credit; serialize by the auth.json directory, keep one idempotency key
304 // until the outcome, and bound the wait so a hung app-server cannot hold the account lock.
305 // Auth overlays use effectiveHomePath; the continuation key would conflate them with shared homes.
306 const accountKey = homeLayout.effectiveHomePath ?? homeLayout.sharedHomePath;
307 const consumeResetCredit: NonNullable<ProviderInstance["consumeResetCredit"]> = () =>
308 resetCreditCoordinator
309 .redeem(accountKey, (idempotencyKey) =>
310 Effect.gen(function* () {
311 const { client } = yield* withCodexAppServerClient({
312 binaryPath: effectiveConfig.binaryPath,
313 homePath: effectiveConfig.homePath,
314 launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),
315 cwd: process.cwd(),
316 environment: processEnv,
317 });
318 const response = yield* client.request("account/rateLimitResetCredit/consume", {
319 idempotencyKey,
320 });
321 return response.outcome;
322 }).pipe(Effect.scoped, Effect.timeout("20 seconds")),
323 )
324 .pipe(
325 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
326 Effect.mapError(
327 (cause) =>
328 new ProviderDriverError({
329 driver: DRIVER_KIND,
330 instanceId,
331 detail: "Codex could not redeem the reset credit.",
332 cause,
333 }),
334 ),
335 // The windows just changed; re-probe so the snapshot says so. A
336 // failed probe republishes the pre-redemption limits rather than
337 // marking them failed, so "confirmed" means `checkedAt` moved past
338 // what was published before the redemption started.
339 Effect.tap((outcome) =>
340 Effect.gen(function* () {
341 const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt;
342 const refreshed = yield* snapshot.refresh;
343 const after = refreshed.usageLimits?.checkedAt;
344 if (
345 outcome === "reset" &&
346 (after === undefined ||
347 after === before ||
348 refreshed.usageLimits?.unavailable?.reason === "probeFailed")
349 ) {
350 return yield* new ProviderDriverError({
351 driver: DRIVER_KIND,
352 instanceId,
353 detail:
354 "The reset was applied, but Codex could not confirm the new limits. Refresh to check.",
355 });
356 }
357 }),
358 ),
359 );
360​
361 return {
362 instanceId,
363 driverKind: DRIVER_KIND,
364 continuationIdentity,
365 displayName,
366 accentColor,
367 enabled,
368 snapshot,
369 snapshotForCwd,
370 consumeResetCredit,
371 orchestrationAdapter,
372 textGeneration,
373 } satisfies ProviderInstance;
374 }),
375};