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

CodexManagedProvider.ts

344 lines13.0 KB

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 closes the scope of an in-flight probe, which fails that refresh
239 // with an interrupt. Keep listening so the sign-out's own idle still refreshes.
240 Stream.runForEach(() => snapshot.refresh.pipe(Effect.ignoreCause({ log: true }))),
241 Effect.forkScoped,
242 );
243 const resolveRuntime = runtime.auth.controller.withAccess!(runtime.resolve);
244 // Launch settings bind the refresh command to the signed-in profile. The registry
245 // already wraps openSession in withAccess, so resolve without re-entering it.
246 const orchestrationAdapter = yield* createCodexAdapterV2(input, {
247 onUsageLimits: (update) => snapshot.applyUsageLimits(update),
248 resolveRuntime: runtime.resolve,
249 }).pipe(
250 Effect.mapError(
251 (cause) =>
252 new ProviderDriverError({
253 driver: DRIVER,
254 instanceId,
255 detail: "Failed to build Codex orchestration adapter.",
256 cause,
257 }),
258 ),
259 );
260 const nativeGeneration = yield* makeCodexTextGeneration(
261 config,
262 undefined,
263 snapshot.getSnapshot.pipe(Effect.map((value) => value.models)),
264 resolveRuntime,
265 );
266 const protect = <A>(operation: string, effect: Effect.Effect<A, TextGenerationError>) =>
267 runtime.auth.controller.withAccess!(effect).pipe(
268 Effect.scoped,
269 Effect.mapError(
270 (cause) =>
271 new TextGenerationError({
272 operation,
273 detail: "detail" in cause ? cause.detail : "Codex text generation failed.",
274 }),
275 ),
276 );
277 const textGeneration: ProviderInstance["textGeneration"] = {
278 generateCommitMessage: (value) =>
279 protect("generateCommitMessage", nativeGeneration.generateCommitMessage(value)),
280 generatePrContent: (value) =>
281 protect("generatePrContent", nativeGeneration.generatePrContent(value)),
282 generateBranchName: (value) =>
283 protect("generateBranchName", nativeGeneration.generateBranchName(value)),
284 generateThreadTitle: (value) =>
285 protect("generateThreadTitle", nativeGeneration.generateThreadTitle(value)),
286 generateReviewGuide: (value) =>
287 protect("generateReviewGuide", nativeGeneration.generateReviewGuide(value)),
288 };
289 return {
290 instanceId,
291 driverKind: DRIVER,
292 continuationIdentity,
293 displayName,
294 accentColor,
295 enabled,
296 snapshot,
297 orchestrationAdapter,
298 textGeneration,
299 auth: runtime.auth.controller,
300 snapshotForCwd: (cwd: string) =>
301 enabled
302 ? resolveRuntime.pipe(
303 Effect.matchEffect({
304 // Signed out or not set up, there is nothing to scan with and the
305 // machine snapshot's empty inventory says as much. Otherwise the
306 // runtime failed for a signed-in account (a token refresh or
307 // reconnect) or before the first check, and the scan failed.
308 onFailure: (cause) =>
309 snapshot.getSnapshot.pipe(
310 Effect.filterOrFail(
311 (machine) => machine.auth.status === "unauthenticated",
312 () => cause,
313 ),
314 ),
315 onSuccess: (effective) =>
316 probeCodexSkillsForCwd({
317 binaryPath: effective.config.binaryPath,
318 homePath: effective.config.homePath,
319 launchArgs: effective.config.launchArgs,
320 cwd,
321 environment: effective.environment,
322 }).pipe(
323 Effect.flatMap((skills) =>
324 snapshot.getSnapshot.pipe(Effect.map((draft) => ({ ...draft, skills }))),
325 ),
326 ),
327 }),
328 Effect.scoped,
329 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
330 // Fail rather than return the machine snapshot: the registry
331 // publishes any returned snapshot as this workspace's inventory.
332 Effect.mapError(
333 (cause) =>
334 new ProviderDriverError({
335 driver: DRIVER,
336 instanceId,
337 detail: `Failed to probe Codex skills for '${cwd}'`,
338 cause,
339 }),
340 ),
341 )
342 : snapshot.getSnapshot,
343 } satisfies ProviderInstance;
344});