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

CodexManagedProvider.ts

280 lines10.4 KB

1import { ProviderDriverKind, TextGenerationError, type CodexSettings } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Stream from "effect/Stream";
4import * as Option from "effect/Option";
5import { ChildProcessSpawner } from "effect/unstable/process";
6import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
7import { ServerSettingsService } from "../../serverSettings.ts";
8import { chatGptModels } from "../CodexChatGptModels.ts";
9import { makeCodexManagedRuntime } from "../CodexManagedRuntime.ts";
10import { ProviderDriverError } from "../Errors.ts";
11import { makeCodexAdapter } from "../Layers/CodexAdapter.ts";
12import {
13 checkCodexProviderStatus,
14 makePendingCodexProvider,
15 probeCodexSkillsForCwd,
16} from "../Layers/CodexProvider.ts";
17import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
18import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
19import { type ProviderDriverCreateInput, type ProviderInstance } from "../ProviderDriver.ts";
20import { codexContinuationIdentity } from "./CodexHomeLayout.ts";
21import { withInstanceIdentity } from "./instanceIdentity.ts";
22import { HttpClient } from "effect/unstable/http";
23const DRIVER = ProviderDriverKind.make("codex");
24​
25export const makeManagedCodexProvider = Effect.fn("makeManagedCodexProvider")(function* (
26 input: ProviderDriverCreateInput<CodexSettings>,
27) {
28 const { instanceId, enabled, displayName, accentColor, config } = input;
29 const http = yield* HttpClient.HttpClient;
30 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
31 const settings = yield* ServerSettingsService;
32 const runtime = yield* makeCodexManagedRuntime({
33 instanceId,
34 enabled,
35 config,
36 environment: mergeProviderInstanceEnvironment(input.environment),
37 });
38 const continuationIdentity = codexContinuationIdentity(runtime.homeLayout);
39 const stamp = withInstanceIdentity({
40 instanceId,
41 driverKind: DRIVER,
42 displayName,
43 accentColor,
44 continuationGroupKey: continuationIdentity.continuationKey,
45 });
46 const setup = { canAuthenticate: true, canInstall: true };
47 const runtimePaths = {
48 homePath: runtime.homeLayout.sharedHomePath,
49 shadowHomePath: runtime.homeLayout.mode === "authOverlay" ? runtime.homePath : null,
50 };
51 const pending = makePendingCodexProvider({ ...config, customModels: [] }).pipe(
52 Effect.map((draft) =>
53 stamp({
54 ...draft,
55 models: [],
56 setup,
57 runtimePaths,
58 }),
59 ),
60 );
61 const check = Effect.gen(function* () {
62 const base = yield* pending;
63 if (!enabled) return base;
64 const executable = yield* runtime.installation.resolve().pipe(Effect.option);
65 if (Option.isNone(executable))
66 return {
67 ...base,
68 installed: false,
69 models: [],
70 message: "Set up Codex to get started.",
71 auth: { status: "unauthenticated" as const },
72 };
73 const saved = yield* runtime.auth.read.pipe(Effect.orElseSucceed(() => Option.none()));
74 if (Option.isSome(saved) && !saved.value.scopes.includes("chatgpt.tokens.use.direct"))
75 return {
76 ...base,
77 installed: true,
78 version: executable.value.version,
79 models: [],
80 message:
81 "Signed in with ChatGPT, but token sharing is disabled. Sign in again and enable token sharing, or use another provider.",
82 auth: {
83 status: "unauthenticated" as const,
84 label: "ChatGPT",
85 ...(saved.value.email?.trim() ? { email: saved.value.email.trim() } : {}),
86 },
87 };
88 if (Option.isNone(saved))
89 return {
90 ...base,
91 installed: true,
92 version: executable.value.version,
93 models: [],
94 message: "Sign in with ChatGPT to use Codex.",
95 auth: { status: "unauthenticated" as const },
96 };
97 const usageLimits = {
98 checkedAt: base.checkedAt,
99 windows: [],
100 unavailable: {
101 reason: "unsupported" as const,
102 message:
103 "ChatGPT tracks subscription usage across connected apps. Open Usage settings with the account you connected to Codex.",
104 },
105 externalUsage: { label: "ChatGPT usage", url: "https://chatgpt.com/#settings/Usage" },
106 };
107 const managedAuth = {
108 subscriptionSharing: true,
109 profileId: saved.value.clientId,
110 status: "authenticated" as const,
111 type: "chatgpt",
112 label: "ChatGPT",
113 ...(saved.value.email?.trim() ? { email: saved.value.email.trim() } : {}),
114 };
115 return yield* runtime.auth.controller.withAccess!(runtime.resolve).pipe(
116 Effect.flatMap((effective) =>
117 Effect.gen(function* () {
118 const draft = yield* checkCodexProviderStatus(
119 effective.config,
120 undefined,
121 effective.environment,
122 managedAuth,
123 );
124 const models = yield* chatGptModels(
125 effective.environment.ACCESS_TOKEN!,
126 draft.models,
127 ).pipe(Effect.provideService(HttpClient.HttpClient, http));
128 return { ...draft, models };
129 }),
130 ),
131 Effect.map((draft) =>
132 stamp({
133 ...draft,
134 auth: managedAuth,
135 version: draft.version ?? executable.value.version,
136 usageLimits,
137 models: draft.models.map((model) => ({
138 ...model,
139 ...(model.capabilities
140 ? {
141 capabilities: {
142 ...model.capabilities,
143 optionDescriptors: (model.capabilities.optionDescriptors ?? []).filter(
144 (option) => option.id !== "serviceTier",
145 ),
146 },
147 }
148 : {}),
149 })),
150 setup,
151 runtimePaths,
152 ...(draft.slashCommands
153 ? {
154 slashCommands: draft.slashCommands.filter((command) => command.name !== "feedback"),
155 }
156 : {}),
157 }),
158 ),
159 Effect.catch(() =>
160 runtime.auth.read.pipe(
161 Effect.orElseSucceed(() => Option.none()),
162 Effect.map((current) => ({
163 ...base,
164 installed: true,
165 version: executable.value.version,
166 models: [],
167 auth: {
168 status:
169 Option.isSome(current) && current.value.scopes.includes("chatgpt.tokens.use.direct")
170 ? ("authenticated" as const)
171 : ("unauthenticated" as const),
172 label: "ChatGPT",
173 ...(Option.isSome(current) &&
174 current.value.scopes.includes("chatgpt.tokens.use.direct")
175 ? { subscriptionSharing: true, profileId: current.value.clientId }
176 : {}),
177 ...(Option.isSome(current) && current.value.email?.trim()
178 ? { email: current.value.email.trim() }
179 : {}),
180 },
181 ...(Option.isSome(current) && current.value.scopes.includes("chatgpt.tokens.use.direct")
182 ? { usageLimits }
183 : {}),
184 message: "Could not check Codex right now. Retry, or reconnect in provider settings.",
185 })),
186 ),
187 ),
188 Effect.scoped,
189 );
190 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner));
191 const snapshot = yield* makeManagedServerProvider({
192 resolveMaintenance: () => Effect.succeed({ provider: DRIVER, packageName: null, update: null }),
193 getSettings: settings.getSettings,
194 streamSettings: settings.streamChanges,
195 haveSettingsChanged: () => false,
196 initialSnapshot: () => pending,
197 checkProvider: check,
198 }).pipe(
199 Effect.mapError(
200 (cause) =>
201 new ProviderDriverError({
202 driver: DRIVER,
203 instanceId,
204 detail: "Could not prepare managed Codex.",
205 cause,
206 }),
207 ),
208 );
209 yield* runtime.auth.controller.subscribe("managed-codex-snapshot").pipe(
210 // Disconnect also publishes idle when a saved account has no active sign-in flow.
211 Stream.filter((state) => ["idle", "succeeded", "failed", "cancelled"].includes(state.phase)),
212 Stream.runForEach(() => snapshot.refresh.pipe(Effect.asVoid)),
213 Effect.forkScoped,
214 );
215 const resolveRuntime = runtime.auth.controller.withAccess!(runtime.resolve);
216 const adapter = yield* makeCodexAdapter(config, {
217 instanceId,
218 resolveRuntime,
219 onManagedConnectionRevoked: runtime.auth.revoke.pipe(Effect.ignore),
220 });
221 const nativeGeneration = yield* makeCodexTextGeneration(
222 config,
223 undefined,
224 snapshot.getSnapshot.pipe(Effect.map((value) => value.models)),
225 resolveRuntime,
226 );
227 const protect = <A>(operation: string, effect: Effect.Effect<A, TextGenerationError>) =>
228 runtime.auth.controller.withAccess!(effect).pipe(
229 Effect.scoped,
230 Effect.mapError(
231 (cause) =>
232 new TextGenerationError({
233 operation,
234 detail: "detail" in cause ? cause.detail : "Codex text generation failed.",
235 }),
236 ),
237 );
238 const textGeneration: ProviderInstance["textGeneration"] = {
239 generateCommitMessage: (value) =>
240 protect("generateCommitMessage", nativeGeneration.generateCommitMessage(value)),
241 generatePrContent: (value) =>
242 protect("generatePrContent", nativeGeneration.generatePrContent(value)),
243 generateBranchName: (value) =>
244 protect("generateBranchName", nativeGeneration.generateBranchName(value)),
245 generateThreadTitle: (value) =>
246 protect("generateThreadTitle", nativeGeneration.generateThreadTitle(value)),
247 };
248 return {
249 instanceId,
250 driverKind: DRIVER,
251 continuationIdentity,
252 displayName,
253 accentColor,
254 enabled,
255 snapshot,
256 adapter,
257 textGeneration,
258 auth: runtime.auth.controller,
259 snapshotForCwd: (cwd: string) =>
260 enabled
261 ? resolveRuntime.pipe(
262 Effect.flatMap((effective) =>
263 probeCodexSkillsForCwd({
264 binaryPath: effective.config.binaryPath,
265 homePath: effective.config.homePath,
266 launchArgs: effective.config.launchArgs,
267 cwd,
268 environment: effective.environment,
269 }),
270 ),
271 Effect.flatMap((skills) =>
272 snapshot.getSnapshot.pipe(Effect.map((draft) => ({ ...draft, skills }))),
273 ),
274 Effect.scoped,
275 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
276 Effect.catch(() => snapshot.getSnapshot),
277 )
278 : snapshot.getSnapshot,
279 } satisfies ProviderInstance;
280});