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

auth.ts

358 lines13.5 KB

1import {
2 ProviderSetupError,
3 type ProviderAuthMethod,
4 type ProviderInstanceId,
5} from "@t3tools/contracts";
6import type { AcpRegistrySettings } from "../settings.ts";
7import * as Crypto from "effect/Crypto";
8import * as Deferred from "effect/Deferred";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import * as Queue from "effect/Queue";
14import * as Scope from "effect/Scope";
15import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
16import type * as AcpSchema from "effect-acp/compat";
17​
18import * as PtyAdapter from "@t3tools/shared/PtyAdapter";
19import * as ProviderAuthFlow from "@t3tools/provider-core/server/providerAuthFlow";
20import { normalizeAcpRegistryAuthMethods, normalizeAcpRegistryWebUrl } from "./probe.ts";
21import * as AcpRegistrySupport from "./AcpRegistrySupport.ts";
22import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts";
23import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
24​
25type Runtime = Pick<
26 AcpSessionRuntime.AcpSessionRuntime["Service"],
27 "initialize" | "authenticate" | "start" | "handleElicitation" | "logout"
28>;
29​
30export const makeAcpRegistryAuth = Effect.fn("makeAcpRegistryAuth")(function* (options: {
31 readonly instanceId: ProviderInstanceId;
32 readonly settings: AcpRegistrySettings;
33 readonly cwd: string;
34 readonly environment: NodeJS.ProcessEnv;
35 readonly onChanged: (authenticated: boolean) => Effect.Effect<void>;
36 readonly makeRuntime?: (
37 spawn: AcpSessionRuntime.AcpSpawnInput,
38 ) => Effect.Effect<Runtime, ProviderSetupError, Scope.Scope>;
39}) {
40 const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog;
41 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
42 const crypto = yield* Crypto.Crypto;
43 const pty = yield* Effect.serviceOption(PtyAdapter.PtyAdapter);
44 const coordinator = yield* Effect.serviceOption(
45 AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
46 );
47 const agentKey =
48 options.settings.source === "local" ? `local:${options.instanceId}` : options.settings.agentId;
49 const failure = (operation: string, detail: string, cause?: unknown) =>
50 new ProviderSetupError({ instanceId: options.instanceId, operation, detail, cause });
51 const resolve = catalog
52 .resolve(options.settings, options.cwd, options.environment)
53 .pipe(
54 Effect.mapError((cause) =>
55 failure("start", "Could not prepare the selected ACP agent.", cause),
56 ),
57 );
58 const makeRuntime =
59 options.makeRuntime ??
60 ((spawn) =>
61 Effect.gen(function* () {
62 const context = yield* Layer.build(
63 AcpSessionRuntime.layer({
64 spawn,
65 cwd: options.cwd,
66 authenticateOnAuthRequired: false,
67 clientCapabilities: {
68 auth: { terminal: Option.isSome(pty) },
69 elicitation: { url: {} },
70 fs: { readTextFile: false, writeTextFile: false },
71 terminal: false,
72 },
73 clientInfo: { name: "t3-code-provider-auth", version: "0.0.0" },
74 }).pipe(
75 Layer.provide(
76 Layer.mergeAll(
77 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
78 Layer.succeed(Crypto.Crypto, crypto),
79 ),
80 ),
81 ),
82 );
83 return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
84 Effect.provide(context),
85 );
86 }).pipe(
87 Effect.mapError((cause) =>
88 failure("start", "Could not start the selected ACP agent.", cause),
89 ),
90 ));
91​
92 let knownMethods:
93 | { readonly version: string | null; readonly methods: ReadonlyArray<ProviderAuthMethod> }
94 | undefined;
95 const discoverMethods = Effect.scoped(
96 Effect.gen(function* () {
97 const inspected = yield* catalog
98 .inspect(options.settings, options.environment)
99 .pipe(
100 Effect.mapError((cause) =>
101 failure("methods", "Could not inspect the selected ACP agent.", cause),
102 ),
103 );
104 if (inspected.status !== "ready")
105 return yield* failure("methods", "Prepare this ACP agent before signing in.");
106 // Path overrides can change in place; cache discovery only for registry versions.
107 if (inspected.version !== null && knownMethods?.version === inspected.version)
108 return knownMethods.methods;
109 const resolved = yield* resolve;
110 const runtime = yield* makeRuntime(resolved.spawn);
111 const initialized = yield* runtime
112 .initialize()
113 .pipe(
114 Effect.mapError((cause) =>
115 failure("methods", "Could not discover this agent's sign-in methods.", cause),
116 ),
117 );
118 const advertised = normalizeAcpRegistryAuthMethods(initialized.authMethods)
119 .filter(
120 (method) => method.id.length <= 128 && (method.type !== "terminal" || Option.isSome(pty)),
121 )
122 .slice(0, 32)
123 .map((method) => ({
124 id: method.id,
125 name: method.name,
126 description: method.description,
127 type: method.type === "env_var" ? ("credentials" as const) : method.type,
128 }));
129 knownMethods = { version: inspected.version, methods: advertised };
130 return advertised;
131 }),
132 ).pipe(
133 Effect.timeoutOrElse({
134 duration: "30 seconds",
135 orElse: () =>
136 Effect.fail(failure("methods", "The ACP agent did not advertise sign-in methods in time.")),
137 }),
138 );
139​
140 const methods = Option.isSome(coordinator)
141 ? coordinator.value
142 .runBackgroundProbe(agentKey, discoverMethods)
143 .pipe(
144 Effect.flatMap((result) =>
145 Effect.fromOption(result, () =>
146 failure(
147 "methods",
148 "Sign-in discovery was interrupted by an active provider session. Try again.",
149 ),
150 ),
151 ),
152 )
153 : discoverMethods;
154​
155 const runTerminal = Effect.fnUntraced(function* (
156 resolved: AcpRegistrySupport.ResolvedAcpRegistryAgent,
157 method: Extract<AcpSchema.AuthMethod, { readonly type: "terminal" }>,
158 context: ProviderAuthFlow.ProviderAuthFlowContext,
159 ) {
160 if (Option.isNone(pty))
161 return yield* failure(
162 "start",
163 "Interactive provider login is unavailable on this environment.",
164 );
165 const exited = yield* Deferred.make<number>();
166 const output = yield* Queue.sliding<string>(64);
167 const process = yield* pty.value
168 .spawn({
169 shell: resolved.spawn.command,
170 args: [...resolved.spawn.args, ...(method.args ?? [])],
171 cwd: options.cwd,
172 cols: 80,
173 rows: 24,
174 env: { ...options.environment, ...resolved.spawn.env, ...method.env },
175 })
176 .pipe(
177 Effect.mapError((cause) =>
178 failure("start", "Could not open the provider sign-in terminal.", cause),
179 ),
180 );
181 const detachData = process.onData((data) => {
182 Queue.offerUnsafe(output, data.slice(-16_384));
183 });
184 const detachExit = process.onExit(({ exitCode }) => {
185 Deferred.doneUnsafe(exited, Effect.succeed(exitCode));
186 });
187 yield* Effect.addFinalizer(() =>
188 Effect.sync(() => {
189 detachData();
190 detachExit();
191 try {
192 process.kill();
193 } catch {}
194 }),
195 );
196 let transcript = "";
197 let outputOffset = 0;
198 const update = () =>
199 context.setInteraction(
200 { type: "terminal", id: "terminal", output: transcript, outputOffset },
201 (response) =>
202 response.type === "terminal"
203 ? Effect.try({
204 try: () => {
205 if (response.size) process.resize(response.size.cols, response.size.rows);
206 if (response.data) process.write(response.data);
207 },
208 catch: () =>
209 failure("respond", "The provider sign-in terminal is no longer available."),
210 })
211 : Effect.void,
212 );
213 yield* update();
214 yield* Queue.take(output).pipe(
215 Effect.flatMap((data) => {
216 outputOffset += data.length;
217 transcript = (transcript + data).slice(-16_384);
218 return update();
219 }),
220 Effect.forever,
221 Effect.forkScoped,
222 );
223 if ((yield* Deferred.await(exited)) !== 0)
224 return yield* failure("start", "The provider login command did not finish successfully.");
225 });
226​
227 const authenticate = Effect.fn("AcpRegistryAuth.authenticate")(function* (
228 methodId: string,
229 context: ProviderAuthFlow.ProviderAuthFlowContext,
230 ) {
231 if (!options.settings.enabled)
232 return yield* failure("start", "Enable this provider before signing in.");
233 const login = Effect.scoped(
234 Effect.gen(function* () {
235 const resolved = yield* resolve;
236 const runtimeScope = yield* Scope.make();
237 yield* Effect.addFinalizer(() => Scope.close(runtimeScope, Exit.void));
238 const runtime = yield* makeRuntime(resolved.spawn).pipe(
239 Effect.provideService(Scope.Scope, runtimeScope),
240 );
241 yield* runtime.handleElicitation((request) =>
242 Effect.gen(function* () {
243 if (
244 request.mode !== "url" ||
245 !("url" in request) ||
246 !("elicitationId" in request) ||
247 typeof request.url !== "string" ||
248 typeof request.elicitationId !== "string"
249 )
250 return { action: "decline" } as const;
251 const url = normalizeAcpRegistryWebUrl(request.url);
252 const id = request.elicitationId.trim();
253 if (!url || !id || id.length > 128) return { action: "decline" } as const;
254 const consent = yield* Deferred.make<boolean>();
255 yield* context.setInteraction(
256 { type: "browser", id, url, requiresConsent: true },
257 (response) =>
258 response.type === "browser"
259 ? Deferred.succeed(consent, response.action === "accept").pipe(Effect.asVoid)
260 : Effect.void,
261 );
262 return (yield* Deferred.await(consent))
263 ? ({ action: "accept" } as const)
264 : ({ action: "decline" } as const);
265 }),
266 );
267 const initialized = yield* runtime
268 .initialize()
269 .pipe(
270 Effect.mapError((cause) =>
271 failure("start", "Could not initialize the selected ACP agent.", cause),
272 ),
273 );
274 const method = initialized.authMethods?.find((method) => method.id === methodId);
275 if (!method)
276 return yield* failure("start", "The agent no longer advertises this sign-in method.");
277 if (method.type === "terminal") {
278 yield* Scope.close(runtimeScope, Exit.void);
279 yield* runTerminal(resolved, method, context).pipe(Effect.scoped);
280 // Terminal login is a separate invocation. Reconnect after it exits so
281 // the ACP process reads the credentials its login command persisted.
282 const verifiedRuntime = yield* makeRuntime(resolved.spawn);
283 yield* context.verifying;
284 yield* verifiedRuntime
285 .start()
286 .pipe(
287 Effect.mapError((cause) =>
288 failure(
289 "verify",
290 "The provider could not create a session after terminal sign-in.",
291 cause,
292 ),
293 ),
294 );
295 } else {
296 if (method.type === undefined || method.type === "agent") {
297 if (!runtime.authenticate)
298 return yield* failure("start", "This runtime does not support explicit ACP sign-in.");
299 yield* runtime
300 .authenticate(methodId)
301 .pipe(
302 Effect.mapError((cause) =>
303 failure("start", "The ACP agent could not complete sign-in.", cause),
304 ),
305 );
306 }
307 // Legacy env_var methods use the secret-backed environment fields in
308 // provider settings. Never send their ID to authenticate.
309 yield* context.verifying;
310 yield* runtime
311 .start()
312 .pipe(
313 Effect.mapError((cause) =>
314 failure("verify", "The provider could not create a session after sign-in.", cause),
315 ),
316 );
317 }
318 }),
319 );
320 yield* Option.isSome(coordinator)
321 ? coordinator.value.withForegroundStartup(agentKey, login)
322 : login;
323 yield* options.onChanged(true);
324 });
325 const logout = Effect.scoped(
326 Effect.gen(function* () {
327 const resolved = yield* resolve;
328 const runtime = yield* makeRuntime(resolved.spawn);
329 yield* runtime.logout.pipe(
330 Effect.mapError((cause) =>
331 failure(
332 "logout",
333 "This ACP agent could not sign out. It may not advertise logout support.",
334 cause,
335 ),
336 ),
337 );
338 }),
339 ).pipe(
340 Effect.timeoutOrElse({
341 duration: "60 seconds",
342 orElse: () =>
343 Effect.fail(failure("logout", "The ACP agent did not finish signing out in time.")),
344 }),
345 );
346 const signOut = (
347 Option.isSome(coordinator) ? coordinator.value.withForegroundStartup(agentKey, logout) : logout
348 ).pipe(Effect.andThen(options.onChanged(false)));
349 return yield* ProviderAuthFlow.make({
350 instanceId: options.instanceId,
351 // ACP omits credential scope; assume an agent's instances share credentials in this environment.
352 credentialBinding: { owner: "provider", key: `acp:${agentKey}` },
353 methods,
354 ...(options.settings.authMethodId ? { defaultMethodId: options.settings.authMethodId } : {}),
355 authenticate,
356 logout: signOut,
357 });
358});