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