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

CodexManagedProvider.ts

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