| 1 | import type { SharedAccountAccess, SharedAccountError } from "@t3tools/contracts"; |
| 2 | import type * as CodexClient from "effect-codex-app-server/client"; |
| 3 | import * as CodexErrors from "effect-codex-app-server/errors"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | |
| 6 | export const authenticateSharedCodex = Effect.fn("authenticateSharedCodex")(function* ( |
| 7 | client: CodexClient.CodexAppServerClient["Service"], |
| 8 | access: (force: boolean) => Effect.Effect<SharedAccountAccess, SharedAccountError>, |
| 9 | ) { |
| 10 | const read = (force: boolean) => |
| 11 | access(force).pipe( |
| 12 | Effect.mapError((cause) => |
| 13 | CodexErrors.CodexAppServerRequestError.internalError(cause.message, undefined, { cause }), |
| 14 | ), |
| 15 | Effect.flatMap((credentials) => |
| 16 | credentials.driver === "codex" |
| 17 | ? Effect.succeed({ |
| 18 | accessToken: credentials.accessToken, |
| 19 | chatgptAccountId: credentials.accountId, |
| 20 | chatgptPlanType: null, |
| 21 | }) |
| 22 | : CodexErrors.CodexAppServerRequestError.internalError( |
| 23 | "This shared account is not a Codex account.", |
| 24 | ), |
| 25 | ), |
| 26 | ); |
| 27 | |
| 28 | yield* client.handleServerRequest("account/chatgptAuthTokens/refresh", () => read(true)); |
| 29 | yield* client.request("account/login/start", { |
| 30 | type: "chatgptAuthTokens", |
| 31 | ...(yield* read(false)), |
| 32 | }); |
| 33 | }); |