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

AcpRegistryAuth.ts

370 lines14.0 KB

1import {
2 ProviderSetupError,
3 type AcpRegistrySettings,
4 type ProviderAuthMethod,
5 type ProviderInstanceId,
6} from "@t3tools/contracts";
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 { ChildProcessSpawner } from "effect/unstable/process";
16import type * as AcpSchema from "effect-acp/compat";
17​
18import * as PtyAdapter from "../../terminal/PtyAdapter.ts";
19import * as ProviderAuthFlow from "../ProviderAuthFlow.ts";
20import { normalizeAcpRegistryAuthMethods, normalizeAcpRegistryWebUrl } from "./AcpRegistryProbe.ts";
21import * as AcpRegistrySupport from "./AcpRegistrySupport.ts";
22import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts";
23import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
24​
25type Runtime = Pick<
26 AcpSessionRuntime.AcpSessionRuntime["Service"],
27 "initialize" | "authenticate" | "start" | "handleElicitation" | "logout"
28>;
29​
30/** ACP credentials stay in the agent's own store, using the same launch environment as chat. */
31export const makeAcpRegistryAuth = Effect.fn("makeAcpRegistryAuth")(function* (options: {
32 readonly instanceId: ProviderInstanceId;
33 readonly settings: AcpRegistrySettings;
34 readonly cwd: string;
35 readonly environment: NodeJS.ProcessEnv;
36 readonly onChanged: (authenticated: boolean) => Effect.Effect<void>;
37 readonly makeRuntime?: (
38 spawn: AcpSessionRuntime.AcpSpawnInput,
39 ) => Effect.Effect<Runtime, ProviderSetupError, Scope.Scope>;
40}) {
41 const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog;
42 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
43 const crypto = yield* Crypto.Crypto;
44 const pty = yield* Effect.serviceOption(PtyAdapter.PtyAdapter);
45 const coordinator = yield* Effect.serviceOption(
46 AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
47 );
48 const failure = (operation: string, detail: string, cause?: unknown) =>
49 new ProviderSetupError({ instanceId: options.instanceId, operation, detail, cause });
50 const resolve = catalog
51 .resolve(options.settings, options.cwd, options.environment)
52 .pipe(
53 Effect.mapError((cause) =>
54 failure("start", "Could not prepare the selected ACP agent.", cause),
55 ),
56 );
57 const makeRuntime =
58 options.makeRuntime ??
59 ((spawn) =>
60 Effect.gen(function* () {
61 const context = yield* Layer.build(
62 AcpSessionRuntime.layer({
63 spawn,
64 cwd: options.cwd,
65 authenticateOnAuthRequired: false,
66 clientCapabilities: {
67 auth: { terminal: Option.isSome(pty) },
68 elicitation: { url: {} },
69 fs: { readTextFile: false, writeTextFile: false },
70 terminal: false,
71 },
72 clientInfo: { name: "t3-code-provider-auth", version: "0.0.0" },
73 }).pipe(
74 Layer.provide(
75 Layer.mergeAll(
76 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
77 Layer.succeed(Crypto.Crypto, crypto),
78 ),
79 ),
80 ),
81 );
82 return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
83 Effect.provide(context),
84 );
85 }).pipe(
86 Effect.mapError((cause) =>
87 failure("start", "Could not start the selected ACP agent.", cause),
88 ),
89 ));
90​
91 let knownMethods:
92 | { readonly version: string | null; readonly methods: ReadonlyArray<ProviderAuthMethod> }
93 | undefined;
94 const discoverMethods = Effect.scoped(
95 Effect.gen(function* () {
96 const inspected = yield* catalog
97 .inspect(options.settings, options.environment)
98 .pipe(
99 Effect.mapError((cause) =>
100 failure("methods", "Could not inspect the selected ACP agent.", cause),
101 ),
102 );
103 if (inspected.status !== "ready")
104 return yield* failure("methods", "Prepare this ACP agent before signing in.");
105 // An unversioned command (a path override) can change in place, so only
106 // registry versions reuse earlier discovery.
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(options.settings.agentId, 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 /* The login process may already have exited. */
197 }
198 }),
199 );
200 let transcript = "";
201 let outputOffset = 0;
202 const update = () =>
203 context.setInteraction(
204 { type: "terminal", id: "terminal", output: transcript, outputOffset },
205 (response) =>
206 response.type === "terminal"
207 ? Effect.try({
208 try: () => {
209 if (response.size) process.resize(response.size.cols, response.size.rows);
210 if (response.data) process.write(response.data);
211 },
212 catch: () =>
213 failure("respond", "The provider sign-in terminal is no longer available."),
214 })
215 : Effect.void,
216 );
217 yield* update();
218 yield* Queue.take(output).pipe(
219 Effect.flatMap((data) => {
220 outputOffset += data.length;
221 transcript = (transcript + data).slice(-16_384);
222 return update();
223 }),
224 Effect.forever,
225 Effect.forkScoped,
226 );
227 if ((yield* Deferred.await(exited)) !== 0)
228 return yield* failure("start", "The provider login command did not finish successfully.");
229 });
230​
231 const authenticate = (methodId: string, context: ProviderAuthFlow.ProviderAuthFlowContext) =>
232 Effect.gen(function* () {
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(
301 "start",
302 "This runtime does not support explicit ACP sign-in.",
303 );
304 yield* runtime
305 .authenticate(methodId)
306 .pipe(
307 Effect.mapError((cause) =>
308 failure("start", "The ACP agent could not complete sign-in.", cause),
309 ),
310 );
311 }
312 // Legacy env_var methods use the secret-backed environment fields in
313 // provider settings. Never send their ID to authenticate.
314 yield* context.verifying;
315 yield* runtime
316 .start()
317 .pipe(
318 Effect.mapError((cause) =>
319 failure(
320 "verify",
321 "The provider could not create a session after sign-in.",
322 cause,
323 ),
324 ),
325 );
326 }
327 }),
328 );
329 yield* Option.isSome(coordinator)
330 ? coordinator.value.withForegroundStartup(options.settings.agentId, login)
331 : login;
332 yield* options.onChanged(true);
333 });
334 const logout = Effect.scoped(
335 Effect.gen(function* () {
336 const resolved = yield* resolve;
337 const runtime = yield* makeRuntime(resolved.spawn);
338 yield* runtime.logout.pipe(
339 Effect.mapError((cause) =>
340 failure(
341 "logout",
342 "This ACP agent could not sign out. It may not advertise logout support.",
343 cause,
344 ),
345 ),
346 );
347 }),
348 ).pipe(
349 Effect.timeoutOrElse({
350 duration: "60 seconds",
351 orElse: () =>
352 Effect.fail(failure("logout", "The ACP agent did not finish signing out in time.")),
353 }),
354 );
355 const signOut = (
356 Option.isSome(coordinator)
357 ? coordinator.value.withForegroundStartup(options.settings.agentId, logout)
358 : logout
359 ).pipe(Effect.andThen(options.onChanged(false)));
360 return yield* ProviderAuthFlow.make({
361 instanceId: options.instanceId,
362 // ACP doesn't advertise its credential scope. Conservatively treat all
363 // instances of the same agent on this environment as sharing credentials.
364 credentialBinding: { owner: "provider", key: `acp:${options.settings.agentId}` },
365 methods,
366 ...(options.settings.authMethodId ? { defaultMethodId: options.settings.authMethodId } : {}),
367 authenticate,
368 logout: signOut,
369 });
370});