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