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