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)
235 process.write(PtyAdapter.ptyInput(response.data, response.binary));
236 },
237 catch: () =>
238 failure("respond", "The provider sign-in terminal is no longer available."),
239 })
240 : Effect.void,
241 );
242 yield* update();
243 yield* Queue.take(output).pipe(
244 Effect.flatMap((data) => {
245 outputOffset += data.length;
246 transcript = (transcript + data).slice(-16_384);
247 return update();
248 }),
249 Effect.forever,
250 Effect.forkScoped,
251 );
252 if ((yield* Deferred.await(exited)) !== 0)
253 return yield* failure("start", "The provider login command did not finish successfully.");
254 });
255
256 const authenticate = Effect.fn("AcpRegistryAuth.authenticate")(function* (
257 methodId: string,
258 context: ProviderAuthFlow.ProviderAuthFlowContext,
259 ) {
260 if (!options.settings.enabled)
261 return yield* failure("start", "Enable this provider before signing in.");
262 const login = Effect.scoped(
263 Effect.gen(function* () {
264 const resolved = yield* resolve;
265 const runtimeScope = yield* Scope.make();
266 yield* Effect.addFinalizer(() => Scope.close(runtimeScope, Exit.void));
267 const runtime = yield* makeRuntime(resolved.spawn).pipe(
268 Effect.provideService(Scope.Scope, runtimeScope),
269 );
270 yield* runtime.handleElicitation((request) =>
271 Effect.gen(function* () {
272 if (
273 request.mode !== "url" ||
274 !("url" in request) ||
275 !("elicitationId" in request) ||
276 typeof request.url !== "string" ||
277 typeof request.elicitationId !== "string"
278 )
279 return { action: "decline" } as const;
280 const url = normalizeAcpRegistryWebUrl(request.url);
281 const id = request.elicitationId.trim();
282 if (!url || !id || id.length > 128) return { action: "decline" } as const;
283 const consent = yield* Deferred.make<boolean>();
284 yield* context.setInteraction(
285 { type: "browser", id, url, requiresConsent: true },
286 (response) =>
287 response.type === "browser"
288 ? Deferred.succeed(consent, response.action === "accept").pipe(Effect.asVoid)
289 : Effect.void,
290 );
291 return (yield* Deferred.await(consent))
292 ? ({ action: "accept" } as const)
293 : ({ action: "decline" } as const);
294 }),
295 );
296 const initialized = yield* runtime
297 .initialize()
298 .pipe(
299 Effect.mapError((cause) =>
300 failure("start", "Could not initialize the selected ACP agent.", cause),
301 ),
302 );
303 const method = initialized.authMethods?.find((method) => method.id === methodId);
304 if (!method)
305 return yield* failure("start", "The agent no longer advertises this sign-in method.");
306 if (method.type === "terminal") {
307 yield* Scope.close(runtimeScope, Exit.void);
308 yield* runTerminal(resolved, method, context).pipe(Effect.scoped);
309 // Terminal login is a separate invocation. Reconnect after it exits so
310 // the ACP process reads the credentials its login command persisted.
311 const verifiedRuntime = yield* makeRuntime(resolved.spawn);
312 yield* context.verifying;
313 yield* verifiedRuntime
314 .start()
315 .pipe(
316 Effect.mapError((cause) =>
317 failure(
318 "verify",
319 "The provider could not create a session after terminal sign-in.",
320 cause,
321 ),
322 ),
323 );
324 } else {
325 if (method.type === undefined || method.type === "agent") {
326 if (!runtime.authenticate)
327 return yield* failure("start", "This runtime does not support explicit ACP sign-in.");
328 yield* runtime
329 .authenticate(methodId)
330 .pipe(
331 Effect.mapError((cause) =>
332 failure("start", "The ACP agent could not complete sign-in.", cause),
333 ),
334 );
335 }
336 // Legacy env_var methods use the secret-backed environment fields in
337 // provider settings. Never send their ID to authenticate.
338 yield* context.verifying;
339 yield* runtime
340 .start()
341 .pipe(
342 Effect.mapError((cause) =>
343 failure("verify", "The provider could not create a session after sign-in.", cause),
344 ),
345 );
346 }
347 }),
348 );
349 yield* Option.isSome(coordinator)
350 ? coordinator.value.withForegroundStartup(agentKey, login)
351 : login;
352 yield* options.onChanged(true);
353 });
354 const logout = Effect.scoped(
355 Effect.gen(function* () {
356 const resolved = yield* resolve;
357 const runtime = yield* makeRuntime(resolved.spawn);
358 yield* runtime.logout.pipe(
359 Effect.mapError((cause) =>
360 failure(
361 "logout",
362 "This ACP agent could not sign out. It may not advertise logout support.",
363 cause,
364 ),
365 ),
366 );
367 }),
368 ).pipe(
369 Effect.timeoutOrElse({
370 duration: "60 seconds",
371 orElse: () =>
372 Effect.fail(failure("logout", "The ACP agent did not finish signing out in time.")),
373 }),
374 );
375 const signOut = (
376 Option.isSome(coordinator) ? coordinator.value.withForegroundStartup(agentKey, logout) : logout
377 ).pipe(Effect.andThen(options.onChanged(false)));
378 return yield* ProviderAuthFlow.make({
379 instanceId: options.instanceId,
380 // ACP omits credential scope; assume an agent's instances share credentials in this environment.
381 credentialBinding: { owner: "provider", key: `acp:${agentKey}` },
382 methods,
383 ...(options.settings.authMethodId ? { defaultMethodId: options.settings.authMethodId } : {}),
384 authenticate,
385 logout: signOut,
386 });
387});