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

auth.ts

367 lines14.0 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 // An unversioned command (a path override) can change in place, so only
107 // registry versions reuse earlier discovery.
108 if (inspected.version !== null && knownMethods?.version === inspected.version)
109 return knownMethods.methods;
110 const resolved = yield* resolve;
111 const runtime = yield* makeRuntime(resolved.spawn);
112 const initialized = yield* runtime
113 .initialize()
114 .pipe(
115 Effect.mapError((cause) =>
116 failure("methods", "Could not discover this agent's sign-in methods.", cause),
117 ),
118 );
119 const advertised = normalizeAcpRegistryAuthMethods(initialized.authMethods)
120 .filter(
121 (method) => method.id.length <= 128 && (method.type !== "terminal" || Option.isSome(pty)),
122 )
123 .slice(0, 32)
124 .map((method) => ({
125 id: method.id,
126 name: method.name,
127 description: method.description,
128 type: method.type === "env_var" ? ("credentials" as const) : method.type,
129 }));
130 knownMethods = { version: inspected.version, methods: advertised };
131 return advertised;
132 }),
133 ).pipe(
134 Effect.timeoutOrElse({
135 duration: "30 seconds",
136 orElse: () =>
137 Effect.fail(failure("methods", "The ACP agent did not advertise sign-in methods in time.")),
138 }),
139 );
140​
141 const methods = Option.isSome(coordinator)
142 ? coordinator.value
143 .runBackgroundProbe(agentKey, discoverMethods)
144 .pipe(
145 Effect.flatMap((result) =>
146 Option.isSome(result)
147 ? Effect.succeed(result.value)
148 : Effect.fail(
149 failure(
150 "methods",
151 "Sign-in discovery was interrupted by an active provider session. Try again.",
152 ),
153 ),
154 ),
155 )
156 : discoverMethods;
157​
158 const runTerminal = Effect.fnUntraced(function* (
159 resolved: AcpRegistrySupport.ResolvedAcpRegistryAgent,
160 method: Extract<AcpSchema.AuthMethod, { readonly type: "terminal" }>,
161 context: ProviderAuthFlow.ProviderAuthFlowContext,
162 ) {
163 if (Option.isNone(pty))
164 return yield* failure(
165 "start",
166 "Interactive provider login is unavailable on this environment.",
167 );
168 const exited = yield* Deferred.make<number>();
169 const output = yield* Queue.sliding<string>(64);
170 const process = yield* pty.value
171 .spawn({
172 shell: resolved.spawn.command,
173 args: [...resolved.spawn.args, ...(method.args ?? [])],
174 cwd: options.cwd,
175 cols: 80,
176 rows: 24,
177 env: { ...options.environment, ...resolved.spawn.env, ...method.env },
178 })
179 .pipe(
180 Effect.mapError((cause) =>
181 failure("start", "Could not open the provider sign-in terminal.", cause),
182 ),
183 );
184 const detachData = process.onData((data) => {
185 Queue.offerUnsafe(output, data.slice(-16_384));
186 });
187 const detachExit = process.onExit(({ exitCode }) => {
188 Deferred.doneUnsafe(exited, Effect.succeed(exitCode));
189 });
190 yield* Effect.addFinalizer(() =>
191 Effect.sync(() => {
192 detachData();
193 detachExit();
194 try {
195 process.kill();
196 } catch {}
197 }),
198 );
199 let transcript = "";
200 let outputOffset = 0;
201 const update = () =>
202 context.setInteraction(
203 { type: "terminal", id: "terminal", output: transcript, outputOffset },
204 (response) =>
205 response.type === "terminal"
206 ? Effect.try({
207 try: () => {
208 if (response.size) process.resize(response.size.cols, response.size.rows);
209 if (response.data) process.write(response.data);
210 },
211 catch: () =>
212 failure("respond", "The provider sign-in terminal is no longer available."),
213 })
214 : Effect.void,
215 );
216 yield* update();
217 yield* Queue.take(output).pipe(
218 Effect.flatMap((data) => {
219 outputOffset += data.length;
220 transcript = (transcript + data).slice(-16_384);
221 return update();
222 }),
223 Effect.forever,
224 Effect.forkScoped,
225 );
226 if ((yield* Deferred.await(exited)) !== 0)
227 return yield* failure("start", "The provider login command did not finish successfully.");
228 });
229​
230 const authenticate = (methodId: string, context: ProviderAuthFlow.ProviderAuthFlowContext) =>
231 Effect.gen(function* () {
232 if (!options.settings.enabled)
233 return yield* failure("start", "Enable this provider before signing in.");
234 const login = Effect.scoped(
235 Effect.gen(function* () {
236 const resolved = yield* resolve;
237 const runtimeScope = yield* Scope.make();
238 yield* Effect.addFinalizer(() => Scope.close(runtimeScope, Exit.void));
239 const runtime = yield* makeRuntime(resolved.spawn).pipe(
240 Effect.provideService(Scope.Scope, runtimeScope),
241 );
242 yield* runtime.handleElicitation((request) =>
243 Effect.gen(function* () {
244 if (
245 request.mode !== "url" ||
246 !("url" in request) ||
247 !("elicitationId" in request) ||
248 typeof request.url !== "string" ||
249 typeof request.elicitationId !== "string"
250 )
251 return { action: "decline" } as const;
252 const url = normalizeAcpRegistryWebUrl(request.url);
253 const id = request.elicitationId.trim();
254 if (!url || !id || id.length > 128) return { action: "decline" } as const;
255 const consent = yield* Deferred.make<boolean>();
256 yield* context.setInteraction(
257 { type: "browser", id, url, requiresConsent: true },
258 (response) =>
259 response.type === "browser"
260 ? Deferred.succeed(consent, response.action === "accept").pipe(Effect.asVoid)
261 : Effect.void,
262 );
263 return (yield* Deferred.await(consent))
264 ? ({ action: "accept" } as const)
265 : ({ action: "decline" } as const);
266 }),
267 );
268 const initialized = yield* runtime
269 .initialize()
270 .pipe(
271 Effect.mapError((cause) =>
272 failure("start", "Could not initialize the selected ACP agent.", cause),
273 ),
274 );
275 const method = initialized.authMethods?.find((method) => method.id === methodId);
276 if (!method)
277 return yield* failure("start", "The agent no longer advertises this sign-in method.");
278 if (method.type === "terminal") {
279 yield* Scope.close(runtimeScope, Exit.void);
280 yield* runTerminal(resolved, method, context).pipe(Effect.scoped);
281 // Terminal login is a separate invocation. Reconnect after it exits so
282 // the ACP process reads the credentials its login command persisted.
283 const verifiedRuntime = yield* makeRuntime(resolved.spawn);
284 yield* context.verifying;
285 yield* verifiedRuntime
286 .start()
287 .pipe(
288 Effect.mapError((cause) =>
289 failure(
290 "verify",
291 "The provider could not create a session after terminal sign-in.",
292 cause,
293 ),
294 ),
295 );
296 } else {
297 if (method.type === undefined || method.type === "agent") {
298 if (!runtime.authenticate)
299 return yield* failure(
300 "start",
301 "This runtime does not support explicit ACP sign-in.",
302 );
303 yield* runtime
304 .authenticate(methodId)
305 .pipe(
306 Effect.mapError((cause) =>
307 failure("start", "The ACP agent could not complete sign-in.", cause),
308 ),
309 );
310 }
311 // Legacy env_var methods use the secret-backed environment fields in
312 // provider settings. Never send their ID to authenticate.
313 yield* context.verifying;
314 yield* runtime
315 .start()
316 .pipe(
317 Effect.mapError((cause) =>
318 failure(
319 "verify",
320 "The provider could not create a session after sign-in.",
321 cause,
322 ),
323 ),
324 );
325 }
326 }),
327 );
328 yield* Option.isSome(coordinator)
329 ? coordinator.value.withForegroundStartup(agentKey, login)
330 : login;
331 yield* options.onChanged(true);
332 });
333 const logout = Effect.scoped(
334 Effect.gen(function* () {
335 const resolved = yield* resolve;
336 const runtime = yield* makeRuntime(resolved.spawn);
337 yield* runtime.logout.pipe(
338 Effect.mapError((cause) =>
339 failure(
340 "logout",
341 "This ACP agent could not sign out. It may not advertise logout support.",
342 cause,
343 ),
344 ),
345 );
346 }),
347 ).pipe(
348 Effect.timeoutOrElse({
349 duration: "60 seconds",
350 orElse: () =>
351 Effect.fail(failure("logout", "The ACP agent did not finish signing out in time.")),
352 }),
353 );
354 const signOut = (
355 Option.isSome(coordinator) ? coordinator.value.withForegroundStartup(agentKey, logout) : logout
356 ).pipe(Effect.andThen(options.onChanged(false)));
357 return yield* ProviderAuthFlow.make({
358 instanceId: options.instanceId,
359 // ACP doesn't advertise its credential scope. Conservatively treat all
360 // instances of the same agent on this environment as sharing credentials.
361 credentialBinding: { owner: "provider", key: `acp:${agentKey}` },
362 methods,
363 ...(options.settings.authMethodId ? { defaultMethodId: options.settings.authMethodId } : {}),
364 authenticate,
365 logout: signOut,
366 });
367});