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

CodexDriver.ts

395 lines15.1 KB

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