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

ProviderAuthService.ts

127 lines5.1 KB

1import {
2 ProviderSetupError,
3 type ProviderInstanceId,
4 type ProviderSessionId,
5} from "@t3tools/contracts";
6import * as Effect from "effect/Effect";
7import * as Layer from "effect/Layer";
8import * as Stream from "effect/Stream";
9​
10import { ProviderSessionManagerV2 } from "../../orchestration-v2/ProviderSessionManager.ts";
11import { ProjectionStoreV2 } from "../../orchestration-v2/ProjectionStore.ts";
12import { ProviderAuthService } from "../Services/ProviderAuthService.ts";
13import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
14​
15export const makeProviderAuthService = Effect.gen(function* () {
16 const registry = yield* ProviderInstanceRegistry;
17 const projections = yield* ProjectionStoreV2;
18 const providerSessions = yield* ProviderSessionManagerV2;
19​
20 const getController = Effect.fn("ProviderAuthService.getController")(function* (
21 instanceId: ProviderInstanceId,
22 operation: string,
23 ) {
24 const instance = yield* registry.getInstance(instanceId);
25 if (!instance?.auth) {
26 return yield* new ProviderSetupError({
27 instanceId,
28 operation,
29 detail: instance
30 ? "This provider does not support sign-in in T3 Code."
31 : "This provider instance is no longer available.",
32 });
33 }
34 return instance.auth;
35 });
36​
37 // Native sessions may still belong to the previous provider after the
38 // selected model changes. Read session bindings, not the selected model,
39 // when invalidating credentials for sign-in or sign-out.
40 const stopSessions = Effect.fn("ProviderAuthService.stopSessions")(function* (
41 instanceId: ProviderInstanceId,
42 ) {
43 const failure = (detail: string) =>
44 new ProviderSetupError({ instanceId, operation: "stopSessions", detail });
45 const threadIds = yield* projections
46 .getRecoveryThreadIds("runtime")
47 .pipe(
48 Effect.mapError(() => failure("Could not read the provider's active sessions. Try again.")),
49 );
50 const released = new Set<ProviderSessionId>();
51 yield* Effect.forEach(
52 threadIds,
53 (threadId) =>
54 projections.getThreadProjection(threadId).pipe(
55 Effect.flatMap((projection) =>
56 Effect.forEach(
57 projection.providerSessions.filter(
58 (session) =>
59 session.providerInstanceId === instanceId &&
60 session.status !== "stopped" &&
61 session.status !== "error" &&
62 !released.has(session.id),
63 ),
64 (session) =>
65 providerSessions
66 .release({
67 providerSessionId: session.id,
68 reason: "manual_shutdown",
69 detail: "Provider sign-in changed.",
70 })
71 .pipe(Effect.tap(() => Effect.sync(() => released.add(session.id)))),
72 { discard: true },
73 ),
74 ),
75 Effect.mapError(() =>
76 failure("Could not stop all sessions for this provider. Try again."),
77 ),
78 ),
79 { discard: true },
80 );
81 });
82​
83 return ProviderAuthService.of({
84 start: Effect.fn("ProviderAuthService.start")(function* (input, ownerSessionId) {
85 const auth = yield* getController(input.instanceId, "start");
86 return yield* auth.start(ownerSessionId, stopSessions(input.instanceId));
87 }),
88 complete: Effect.fn("ProviderAuthService.complete")(function* (input, ownerSessionId) {
89 const auth = yield* getController(input.instanceId, "complete");
90 return yield* auth.complete(ownerSessionId, input);
91 }),
92 cancel: Effect.fn("ProviderAuthService.cancel")(function* (input, ownerSessionId) {
93 const auth = yield* getController(input.instanceId, "cancel");
94 return yield* auth.cancel(ownerSessionId, input.flowId);
95 }),
96 logout: Effect.fn("ProviderAuthService.logout")(function* (input) {
97 const auth = yield* getController(input.instanceId, "logout");
98 return yield* auth.logout(stopSessions(input.instanceId));
99 }),
100 subscribe: (input, ownerSessionId) =>
101 Effect.gen(function* () {
102 const changes = yield* registry.subscribeChanges;
103 const initial = yield* getController(input.instanceId, "subscribe");
104 return Stream.concat(
105 Stream.succeed(initial),
106 Stream.fromSubscription(changes).pipe(
107 Stream.mapEffect(() => getController(input.instanceId, "subscribe")),
108 ),
109 ).pipe(
110 Stream.changesWith((previous, next) => previous === next),
111 Stream.switchMap((auth) => auth.subscribe(ownerSessionId)),
112 );
113 }).pipe(Stream.unwrap),
114 tryHandlePromptCommand: Effect.fn("ProviderAuthService.tryHandlePromptCommand")(
115 function* (input) {
116 const instance = yield* registry.getInstance(input.instanceId);
117 if (!instance?.auth?.isLogoutPrompt?.(input.text, input.hasAttachments)) {
118 return false;
119 }
120 yield* instance.auth.logout(stopSessions(input.instanceId));
121 return true;
122 },
123 ),
124 });
125});
126​
127export const ProviderAuthServiceLive = Layer.effect(ProviderAuthService, makeProviderAuthService);