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

CodexDriver.ts

357 lines14.7 KB

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