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

CodexDriver.ts

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