Open History to see the last commit
1import {
2 ProviderDriverKind,
3 ProviderSetupError,
4 TextGenerationError,
5 type CodexSettings,
6} from "@t3tools/contracts";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Path from "effect/Path";
10import * as Stream from "effect/Stream";
11import * as Option from "effect/Option";
12import { ChildProcessSpawner } from "effect/process";
13import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
14import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
15import { chatGptModels } from "../CodexChatGptModels.ts";
16import { makeCodexManagedRuntime } from "../CodexManagedRuntime.ts";
17import { ProviderDriverError } from "../Errors.ts";
18import { createCodexAdapterV2 } from "../../orchestration-v2/Adapters/CodexAdapterV2.ts";
19import {
20 checkCodexProviderStatus,
21 makePendingCodexProvider,
22 probeCodexSkillsForCwd,
23} from "../CodexProvider.ts";
24import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
25import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
26import {
27 type ProviderDriverCreateInput,
28 type ProviderInstance,
29} from "@t3tools/provider-core/server/driver";
30import { codexContinuationIdentity } from "./CodexHomeLayout.ts";
31import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity";
32import { HttpClient } from "effect/http";
33const DRIVER = ProviderDriverKind.make("codex");
34
35export const makeManagedCodexProvider = Effect.fn("makeManagedCodexProvider")(function* (
36 input: ProviderDriverCreateInput<CodexSettings>,
37) {
38 const { instanceId, enabled, displayName, accentColor, config } = input;
39 const http = yield* HttpClient.HttpClient;
40 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
41 const fileSystem = yield* FileSystem.FileSystem;
42 const path = yield* Path.Path;
43 const host = yield* ProviderHost.ProviderHost;
44 const runtime = yield* makeCodexManagedRuntime({
45 instanceId,
46 enabled,
47 config,
48 environment: yield* mergeProviderInstanceEnvironment(input.environment),
49 });
50 const continuationIdentity = codexContinuationIdentity(runtime.homeLayout);
51 const stamp = withInstanceIdentity({
52 instanceId,
53 driverKind: DRIVER,
54 displayName,
55 accentColor,
56 continuationGroupKey: continuationIdentity.continuationKey,
57 });
58 const setup = { canAuthenticate: true, canInstall: true };
59 const runtimePaths = {
60 homePath: runtime.homeLayout.sharedHomePath,
61 shadowHomePath: runtime.homeLayout.mode === "authOverlay" ? runtime.homePath : null,
62 };
63 const pending = makePendingCodexProvider({ ...config, enabled, customModels: [] }).pipe(
64 Effect.map((draft) =>
65 stamp({
66 ...draft,
67 models: [],
68 setup,
69 runtimePaths,
70 }),
71 ),
72 );
73 const check = Effect.gen(function* () {
74 const base = yield* pending;
75 if (!enabled) return base;
76 const executable = yield* runtime.installation.resolve().pipe(Effect.option);
77 if (Option.isNone(executable))
78 return {
79 ...base,
80 installed: false,
81 models: [],
82 message: "Set up Codex to get started.",
83 auth: { status: "unauthenticated" as const },
84 };
85 const saved = yield* runtime.auth.read.pipe(Effect.orElseSucceed(() => Option.none()));
86 if (Option.isSome(saved) && !saved.value.scopes.includes("chatgpt.tokens.use.direct"))
87 return {
88 ...base,
89 installed: true,
90 version: executable.value.version,
91 models: [],
92 message:
93 "Signed in with ChatGPT, but token sharing is disabled. Sign in again and enable token sharing, or use another provider.",
94 auth: {
95 status: "unauthenticated" as const,
96 label: "ChatGPT",
97 ...(saved.value.email?.trim() ? { email: saved.value.email.trim() } : {}),
98 },
99 };
100 if (Option.isNone(saved))
101 return {
102 ...base,
103 installed: true,
104 version: executable.value.version,
105 models: [],
106 message: "Sign in with ChatGPT to use Codex.",
107 auth: { status: "unauthenticated" as const },
108 };
109 const usageLimits = {
110 checkedAt: base.checkedAt,
111 windows: [],
112 unavailable: {
113 reason: "unsupported" as const,
114 message:
115 "ChatGPT tracks subscription usage across connected apps. Open Usage settings with the account you connected to Codex.",
116 },
117 externalUsage: { label: "ChatGPT usage", url: "https://chatgpt.com/#settings/Usage" },
118 };
119 const managedAuth = {
120 subscriptionSharing: true,
121 profileId: saved.value.clientId,
122 status: "authenticated" as const,
123 type: "chatgpt",
124 label: "ChatGPT",
125 ...(saved.value.email?.trim() ? { email: saved.value.email.trim() } : {}),
126 };
127 return yield* runtime.auth.controller.withAccess!(runtime.resolve).pipe(
128 Effect.flatMap((effective) =>
129 Effect.gen(function* () {
130 const draft = yield* checkCodexProviderStatus(
131 effective.config,
132 undefined,
133 effective.environment,
134 managedAuth,
135 );
136 const credentials = yield* runtime.auth.access;
137 // Another server can replace the saved profile while the native probe runs.
138 // Never send that account's token with the launch profile's catalog labels.
139 if (
140 (yield* runtime.auth.profileKey(credentials)) !== effective.revision ||
141 (yield* runtime.auth.profileKey(saved.value)) !== effective.revision
142 )
143 return yield* new ProviderSetupError({
144 instanceId,
145 operation: "models",
146 detail: "The ChatGPT connection changed while checking Codex. Retry.",
147 });
148 const models = yield* chatGptModels(credentials.accessToken, draft.models).pipe(
149 Effect.provideService(HttpClient.HttpClient, http),
150 );
151 return { ...draft, models };
152 }),
153 ),
154 Effect.map((draft) =>
155 stamp({
156 ...draft,
157 auth: managedAuth,
158 version: draft.version ?? executable.value.version,
159 usageLimits,
160 models: draft.models.map((model) => ({
161 ...model,
162 ...(model.capabilities
163 ? {
164 capabilities: {
165 ...model.capabilities,
166 optionDescriptors: (model.capabilities.optionDescriptors ?? []).filter(
167 (option) => option.id !== "serviceTier",
168 ),
169 },
170 }
171 : {}),
172 })),
173 setup,
174 runtimePaths,
175 ...(draft.slashCommands
176 ? {
177 slashCommands: draft.slashCommands.filter((command) => command.name !== "feedback"),
178 }
179 : {}),
180 }),
181 ),
182 Effect.catch(() =>
183 runtime.auth.read.pipe(
184 Effect.orElseSucceed(() => Option.none()),
185 Effect.map((current) => ({
186 ...base,
187 installed: true,
188 version: executable.value.version,
189 models: [],
190 auth: {
191 status:
192 Option.isSome(current) && current.value.scopes.includes("chatgpt.tokens.use.direct")
193 ? ("authenticated" as const)
194 : ("unauthenticated" as const),
195 label: "ChatGPT",
196 ...(Option.isSome(current) &&
197 current.value.scopes.includes("chatgpt.tokens.use.direct")
198 ? { subscriptionSharing: true, profileId: current.value.clientId }
199 : {}),
200 ...(Option.isSome(current) && current.value.email?.trim()
201 ? { email: current.value.email.trim() }
202 : {}),
203 },
204 ...(Option.isSome(current) && current.value.scopes.includes("chatgpt.tokens.use.direct")
205 ? { usageLimits }
206 : {}),
207 message: "Could not check Codex right now. Retry, or reconnect in provider settings.",
208 })),
209 ),
210 ),
211 Effect.scoped,
212 );
213 }).pipe(
214 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
215 Effect.provideService(FileSystem.FileSystem, fileSystem),
216 Effect.provideService(Path.Path, path),
217 );
218 const snapshot = yield* makeManagedServerProvider({
219 resolveMaintenance: () => Effect.succeed({ provider: DRIVER, packageName: null, update: null }),
220 getSettings: host.settings.get,
221 streamSettings: host.settings.changes,
222 haveSettingsChanged: () => false,
223 initialSnapshot: () => pending,
224 checkProvider: check,
225 }).pipe(
226 Effect.mapError(
227 (cause) =>
228 new ProviderDriverError({
229 driver: DRIVER,
230 instanceId,
231 detail: "Could not prepare managed Codex.",
232 cause,
233 }),
234 ),
235 );
236 yield* runtime.auth.controller.subscribe("managed-codex-snapshot").pipe(
237 Stream.filter((state) => ["idle", "succeeded", "failed", "cancelled"].includes(state.phase)),
238 // Sign-out interrupts in-flight probes; keep listening for its subsequent idle refresh.
239 Stream.runForEach(() => snapshot.refresh.pipe(Effect.ignoreCause({ log: true }))),
240 Effect.forkScoped,
241 );
242 const resolveRuntime = runtime.auth.controller.withAccess!(runtime.resolve);
243 // Launch settings bind the refresh command to the signed-in profile. The registry
244 // already wraps openSession in withAccess, so resolve without re-entering it.
245 const models = snapshot.getSnapshot.pipe(Effect.map((value) => value.models));
246 const orchestrationAdapter = yield* createCodexAdapterV2(input, {
247 onUsageLimits: (update) => snapshot.applyUsageLimits(update),
248 models,
249 resolveRuntime: runtime.resolve,
250 }).pipe(
251 Effect.mapError(
252 (cause) =>
253 new ProviderDriverError({
254 driver: DRIVER,
255 instanceId,
256 detail: "Failed to build Codex orchestration adapter.",
257 cause,
258 }),
259 ),
260 );
261 const nativeGeneration = yield* makeCodexTextGeneration(
262 config,
263 undefined,
264 models,
265 resolveRuntime,
266 );
267 const protect = <A>(operation: string, effect: Effect.Effect<A, TextGenerationError>) =>
268 runtime.auth.controller.withAccess!(effect).pipe(
269 Effect.scoped,
270 Effect.mapError(
271 (cause) =>
272 new TextGenerationError({
273 operation,
274 detail: "detail" in cause ? cause.detail : "Codex text generation failed.",
275 }),
276 ),
277 );
278 const textGeneration: ProviderInstance["textGeneration"] = {
279 generateCommitMessage: (value) =>
280 protect("generateCommitMessage", nativeGeneration.generateCommitMessage(value)),
281 generatePrContent: (value) =>
282 protect("generatePrContent", nativeGeneration.generatePrContent(value)),
283 generateBranchName: (value) =>
284 protect("generateBranchName", nativeGeneration.generateBranchName(value)),
285 generateThreadTitle: (value) =>
286 protect("generateThreadTitle", nativeGeneration.generateThreadTitle(value)),
287 generateReviewGuide: (value) =>
288 protect("generateReviewGuide", nativeGeneration.generateReviewGuide(value)),
289 generateTranscriptionPostProcessing: (value) =>
290 protect(
291 "generateTranscriptionPostProcessing",
292 nativeGeneration.generateTranscriptionPostProcessing(value),
293 ),
294 };
295 return {
296 instanceId,
297 driverKind: DRIVER,
298 continuationIdentity,
299 displayName,
300 accentColor,
301 enabled,
302 snapshot,
303 orchestrationAdapter,
304 textGeneration,
305 auth: runtime.auth.controller,
306 snapshotForCwd: (cwd: string) =>
307 enabled
308 ? resolveRuntime.pipe(
309 Effect.matchEffect({
310 // Signed-out snapshots have an empty inventory; a signed-in runtime failure must fail the scan.
311 onFailure: (cause) =>
312 snapshot.getSnapshot.pipe(
313 Effect.filterOrFail(
314 (machine) => machine.auth.status === "unauthenticated",
315 () => cause,
316 ),
317 ),
318 onSuccess: (effective) =>
319 probeCodexSkillsForCwd({
320 binaryPath: effective.config.binaryPath,
321 homePath: effective.config.homePath,
322 launchArgs: effective.config.launchArgs,
323 cwd,
324 environment: effective.environment,
325 }).pipe(
326 Effect.flatMap((skills) =>
327 snapshot.getSnapshot.pipe(Effect.map((draft) => ({ ...draft, skills }))),
328 ),
329 ),
330 }),
331 Effect.scoped,
332 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
333 // Fail instead of returning machine inventory, which the registry would publish as workspace inventory.
334 Effect.mapError(
335 (cause) =>
336 new ProviderDriverError({
337 driver: DRIVER,
338 instanceId,
339 detail: `Failed to probe Codex skills for '${cwd}'`,
340 cause,
341 }),
342 ),
343 )
344 : snapshot.getSnapshot,
345 } satisfies ProviderInstance;
346});