Open History to see the last commit
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";
9import * as Semaphore from "effect/Semaphore";
10
11import { ProviderSessionManagerV2 } from "../../orchestration-v2/ProviderSessionManager.ts";
12import { ProjectionStoreV2 } from "../../orchestration-v2/ProjectionStore.ts";
13import * as ProviderAuthService from "../Services/ProviderAuthService.ts";
14import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
15
16export const makeProviderAuthService = Effect.gen(function* () {
17 const registry = yield* ProviderInstanceRegistry;
18 const projections = yield* ProjectionStoreV2;
19 const providerSessions = yield* ProviderSessionManagerV2;
20 const credentialChanges = yield* Semaphore.make(1);
21
22 const getController = Effect.fn("ProviderAuthService.getController")(function* (
23 instanceId: ProviderInstanceId,
24 operation: string,
25 ) {
26 const instance = yield* registry.getInstance(instanceId);
27 if (!instance?.auth) {
28 return yield* new ProviderSetupError({
29 instanceId,
30 operation,
31 detail: instance
32 ? "This provider does not support sign-in in T3 Code."
33 : "This provider instance is no longer available.",
34 });
35 }
36 return instance.auth;
37 });
38
39 // Native sessions may still belong to the previous provider after the
40 // selected model changes. Read session bindings, not the selected model,
41 // when invalidating credentials for sign-in or sign-out.
42 const stopSessions = Effect.fn("ProviderAuthService.stopSessions")(function* (
43 instanceId: ProviderInstanceId,
44 binding: ProviderAuthService.ProviderAuthController["credentialBinding"],
45 ) {
46 const failure = (detail: string) =>
47 new ProviderSetupError({ instanceId, operation: "stopSessions", detail });
48 const affectedIds = new Set([
49 instanceId,
50 ...(binding === undefined
51 ? []
52 : (yield* registry.listInstances)
53 .filter(
54 (instance) =>
55 instance.auth?.credentialBinding?.key === binding.key &&
56 instance.auth.credentialBinding.owner === binding.owner,
57 )
58 .map((instance) => instance.instanceId)),
59 ]);
60 const threadIds = yield* projections
61 .getRecoveryThreadIds("runtime")
62 .pipe(
63 Effect.mapError(() => failure("Could not read the provider's active sessions. Try again.")),
64 );
65 const released = new Set<ProviderSessionId>();
66 yield* Effect.forEach(
67 threadIds,
68 (threadId) =>
69 projections.getThreadRecords(threadId, ["providerSessions"]).pipe(
70 Effect.flatMap((projection) =>
71 Effect.forEach(
72 projection.providerSessions.filter(
73 (session) =>
74 affectedIds.has(session.providerInstanceId) &&
75 session.status !== "stopped" &&
76 session.status !== "error" &&
77 !released.has(session.id),
78 ),
79 (session) =>
80 Effect.gen(function* () {
81 if (session.providerInstanceId !== instanceId) {
82 const current = yield* registry.getInstance(session.providerInstanceId);
83 if (
84 !binding ||
85 current?.auth?.credentialBinding?.key !== binding.key ||
86 current.auth.credentialBinding.owner !== binding.owner
87 )
88 return;
89 }
90 yield* providerSessions
91 .release({
92 providerSessionId: session.id,
93 reason: "manual_shutdown",
94 detail: "Provider sign-in changed.",
95 })
96 .pipe(Effect.tap(() => Effect.sync(() => released.add(session.id))));
97 }),
98 { discard: true },
99 ),
100 ),
101 Effect.mapError(() =>
102 failure("Could not stop all sessions for this provider. Try again."),
103 ),
104 ),
105 { discard: true },
106 );
107 if (binding) {
108 yield* Effect.forEach(
109 (yield* registry.listInstances).filter(
110 (instance) =>
111 instance.instanceId !== instanceId &&
112 affectedIds.has(instance.instanceId) &&
113 instance.auth?.credentialBinding?.key === binding.key &&
114 instance.auth.credentialBinding.owner === binding.owner,
115 ),
116 (instance) => instance.auth?.invalidate ?? Effect.void,
117 { discard: true },
118 );
119 }
120 });
121
122 const checkSharedBinding = Effect.fnUntraced(function* (
123 instanceId: ProviderInstanceId,
124 operation: "start" | "logout",
125 auth: ProviderAuthService.ProviderAuthController,
126 ) {
127 const binding = auth.credentialBinding;
128 if (!binding) return;
129 const instances = yield* registry.listInstances;
130 for (const instance of instances) {
131 if (
132 instance.instanceId !== instanceId &&
133 instance.auth?.credentialBinding?.key === binding.key &&
134 instance.auth.credentialBinding.owner === binding.owner &&
135 instance.auth.isChangingCredentials &&
136 (yield* instance.auth.isChangingCredentials)
137 ) {
138 return yield* new ProviderSetupError({
139 instanceId,
140 operation,
141 detail:
142 "Another provider instance is changing this shared sign-in. Finish or cancel it first.",
143 });
144 }
145 }
146 });
147
148 return ProviderAuthService.ProviderAuthService.of({
149 start: Effect.fn("ProviderAuthService.start")(function* (input, ownerSessionId) {
150 return yield* credentialChanges.withPermit(
151 Effect.gen(function* () {
152 const auth = yield* getController(input.instanceId, "start");
153 yield* checkSharedBinding(input.instanceId, "start", auth);
154 return yield* auth.start(
155 ownerSessionId,
156 stopSessions(input.instanceId, auth.credentialBinding),
157 input.methodId,
158 );
159 }),
160 );
161 }),
162 respond: Effect.fn("ProviderAuthService.respond")(function* (input, ownerSessionId) {
163 const auth = yield* getController(input.instanceId, "respond");
164 if (!auth.respond) {
165 return yield* new ProviderSetupError({
166 instanceId: input.instanceId,
167 operation: "respond",
168 detail: "This provider does not accept this sign-in interaction.",
169 });
170 }
171 return yield* auth.respond(ownerSessionId, input);
172 }),
173 complete: Effect.fn("ProviderAuthService.complete")(function* (input, ownerSessionId) {
174 const auth = yield* getController(input.instanceId, "complete");
175 return yield* auth.complete(ownerSessionId, input);
176 }),
177 cancel: Effect.fn("ProviderAuthService.cancel")(function* (input, ownerSessionId) {
178 const auth = yield* getController(input.instanceId, "cancel");
179 return yield* auth.cancel(ownerSessionId, input.flowId);
180 }),
181 logout: Effect.fn("ProviderAuthService.logout")(function* (input) {
182 return yield* credentialChanges.withPermit(
183 Effect.gen(function* () {
184 const auth = yield* getController(input.instanceId, "logout");
185 yield* checkSharedBinding(input.instanceId, "logout", auth);
186 return yield* auth.logout(stopSessions(input.instanceId, auth.credentialBinding));
187 }),
188 );
189 }),
190 subscribe: (input, ownerSessionId) =>
191 Effect.gen(function* () {
192 const changes = yield* registry.subscribeChanges;
193 const initial = yield* getController(input.instanceId, "subscribe");
194 return Stream.concat(
195 Stream.succeed(initial),
196 Stream.fromSubscription(changes).pipe(
197 Stream.mapEffect(() => getController(input.instanceId, "subscribe")),
198 ),
199 ).pipe(
200 Stream.changesWith((previous, next) => previous === next),
201 Stream.switchMap((auth) => auth.subscribe(ownerSessionId)),
202 );
203 }).pipe(Stream.unwrap),
204 tryHandlePromptCommand: Effect.fn("ProviderAuthService.tryHandlePromptCommand")(
205 function* (input) {
206 const instance = yield* registry.getInstance(input.instanceId);
207 if (!instance?.auth?.isLogoutPrompt?.(input.text, input.hasAttachments)) {
208 return false;
209 }
210 return yield* credentialChanges.withPermit(
211 Effect.gen(function* () {
212 const auth = yield* getController(input.instanceId, "logout");
213 if (!auth.isLogoutPrompt?.(input.text, input.hasAttachments)) return false;
214 yield* checkSharedBinding(input.instanceId, "logout", auth);
215 yield* auth.logout(stopSessions(input.instanceId, auth.credentialBinding));
216 return true;
217 }),
218 );
219 },
220 ),
221 });
222});
223
224export const ProviderAuthServiceLive = Layer.effect(
225 ProviderAuthService.ProviderAuthService,
226 makeProviderAuthService,
227);