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

CodexDriver.ts

357 lines13.8 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 { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
11import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
12import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
13import * as ServerConfig from "../../config.ts";
14import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
15import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
16import {
17 createCodexAdapterV2,
18 type CodexAdapterV2DriverEnv,
19} from "../../orchestration-v2/Adapters/CodexAdapterV2.ts";
20import { ProviderDriverError } from "../Errors.ts";
21import * as ResetCreditCoordinator from "../resetCreditCoordinator.ts";
22import {
23 checkCodexProviderStatus,
24 makePendingCodexProvider,
25 probeCodexSkillsForCwd,
26 withCodexAppServerClient,
27} from "../CodexProvider.ts";
28import { resolveCodexLaunchArgs } from "../codexLaunchArgs.ts";
29import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
30import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog";
31import { applyCodexModelCatalog } from "../codexModelCatalog.ts";
32import type { ProviderDriver, ProviderInstance } from "@t3tools/provider-core/server/driver";
33import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity";
34import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
35import {
36 enrichProviderSnapshotWithVersionAdvisory,
37 makeCachedProviderMaintenanceResolution,
38 makePackageManagedProviderMaintenanceResolver,
39 normalizeCommandPath,
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 ServerSecretStore from "../../auth/ServerSecretStore.ts";
56import * as ServerEnvironment from "../../environment/ServerEnvironment.ts";
57import * as HostProcess from "@t3tools/shared/HostProcess";
58const decodeCodexSettings = Schema.decodeSync(CodexSettings);
59​
60const DRIVER_KIND = ProviderDriverKind.make("codex");
61function isCodexStandaloneCommandPath(commandPath: string): boolean {
62 return normalizeCommandPath(commandPath).includes("/packages/standalone/");
64​
65/**
66 * `codex update` replaces the standalone tree under `CODEX_HOME`. That tree
67 * lives in the shared home even when an auth-overlay shadow home is in use
68 * (the overlay only carries auth and a few local entries), so the updater
69 * runs against `sharedHomePath` rather than the instance's effective home.
70 */
71function makeCodexMaintenanceResolver(sharedHomePath: string) {
72 return makePackageManagedProviderMaintenanceResolver({
73 provider: DRIVER_KIND,
74 npmPackageName: "@openai/codex",
75 nativeUpdate: {
76 args: ["update"],
77 isCommandPath: isCodexStandaloneCommandPath,
78 env: { CODEX_HOME: sharedHomePath },
79 },
80 });
82​
83export type CodexDriverEnv =
84 | CodexAdapterV2DriverEnv
85 | ProviderHost.ProviderHost
86 | ChildProcessSpawner.ChildProcessSpawner
87 | ResetCreditCoordinator.ResetCreditCoordinator
88 | Crypto.Crypto
89 | FileSystem.FileSystem
90 | HttpClient.HttpClient
91 | ProviderLatestVersions.ProviderLatestVersions
92 | ModelCatalog.ModelCatalog
93 | Path.Path
94 | ProviderEventLoggers.ProviderEventLoggers
95 | ServerConfig.ServerConfig
96 | ServerSecretStore.ServerSecretStore
97 | ServerEnvironment.ServerEnvironmentIdentity
98 | CodexInstallation.CodexInstallation;
99​
100export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv, Path.Path> = {
101 driverKind: DRIVER_KIND,
102 metadata: {
103 displayName: "Codex",
104 supportsMultipleInstances: true,
105 },
106 configSchema: CodexSettings,
107 defaultConfig: (): CodexSettings => decodeCodexSettings({}),
108 usage: codexUsageReader,
109 create: Effect.fn("CodexDriver.create")(function* ({
110 instanceId,
111 displayName,
112 accentColor,
113 environment,
114 enabled,
115 config,
116 }) {
117 if (config.setupMode === "managed")
118 return yield* makeManagedCodexProvider({
119 instanceId,
120 displayName,
121 accentColor,
122 environment,
123 enabled,
124 config,
125 });
126 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
127 const resetCreditCoordinator = yield* ResetCreditCoordinator.ResetCreditCoordinator;
128 const fileSystem = yield* FileSystem.FileSystem;
129 const pathService = yield* Path.Path;
130 const httpClient = yield* HttpClient.HttpClient;
131 const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
132 const modelCatalog = yield* ModelCatalog.ModelCatalog;
133 const currentCatalog = modelCatalog.current(DRIVER_KIND);
134 const processEnv = yield* mergeProviderInstanceEnvironment(environment);
135 const homeLayout = yield* resolveCodexHomeLayout(config);
136 const continuationIdentity = codexContinuationIdentity(homeLayout);
137 const stampIdentity = withInstanceIdentity({
138 instanceId,
139 driverKind: DRIVER_KIND,
140 displayName,
141 accentColor,
142 continuationGroupKey: continuationIdentity.continuationKey,
143 });
144 yield* materializeCodexShadowHome(homeLayout).pipe(
145 Effect.mapError(
146 (cause) =>
147 new ProviderDriverError({
148 driver: DRIVER_KIND,
149 instanceId,
150 detail: cause.message,
151 cause,
152 }),
153 ),
154 );
155 const effectiveConfig = {
156 ...config,
157 enabled,
158 binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),
159 homePath: homeLayout.effectiveHomePath ?? "",
160 } satisfies CodexSettings;
161 const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
162 resolveProviderMaintenanceCapabilitiesEffect(
163 makeCodexMaintenanceResolver(homeLayout.sharedHomePath),
164 {
165 binaryPath: effectiveConfig.binaryPath,
166 env: processEnv,
167 },
168 ).pipe(
169 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
170 Effect.provideService(FileSystem.FileSystem, fileSystem),
171 Effect.provideService(Path.Path, pathService),
172 ),
173 );
174​
175 const orchestrationAdapter = yield* createCodexAdapterV2(
176 {
177 instanceId,
178 displayName,
179 accentColor,
180 environment,
181 enabled,
182 config,
183 },
184 { onUsageLimits: (update) => snapshot.applyUsageLimits(update) },
185 ).pipe(
186 Effect.mapError(
187 (cause) =>
188 new ProviderDriverError({
189 driver: DRIVER_KIND,
190 instanceId,
191 detail: "Failed to build Codex orchestration adapter.",
192 cause,
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};