Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import {
4 AcpRegistrySettings,
5 ProviderInstanceId,
6 type ProviderAuthState,
7} from "@t3tools/contracts";
8import * as Deferred from "effect/Deferred";
9import * as Effect from "effect/Effect";
10import * as Option from "effect/Option";
11import * as Schema from "effect/Schema";
12import * as Stream from "effect/Stream";
13import type * as AcpSchema from "effect-acp/compat";
14import { AcpRequestError } from "effect-acp/errors";
15
16import * as PtyAdapter from "../../terminal/PtyAdapter.ts";
17import { makeAcpRegistryAuth } from "./AcpRegistryAuth.ts";
18import * as AcpRegistrySupport from "./AcpRegistrySupport.ts";
19import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
20
21const decodeSettings = Schema.decodeSync(AcpRegistrySettings);
22const instanceId = ProviderInstanceId.make("acp-auth-test");
23const browserMethod = { id: "browser", name: "Browser", type: "agent" as const };
24const terminalMethod = {
25 id: "terminal",
26 name: "Terminal",
27 type: "terminal" as const,
28 args: ["login"],
29 env: { LOGIN: "yes", OVERRIDE: "method" },
30};
31const resolved: AcpRegistrySupport.ResolvedAcpRegistryAgent = {
32 agent: {
33 id: "test-agent",
34 name: "Test",
35 version: "1.0.0",
36 description: "Test",
37 distribution: {},
38 },
39 distribution: "binary",
40 spawn: {
41 command: "/managed/agent",
42 args: ["--acp"],
43 env: { OVERRIDE: "spawn", AGENT_HOME: "/custom/home" },
44 },
45};
46const catalog: AcpRegistrySupport.AcpRegistryCatalog["Service"] = {
47 inspect: () =>
48 Effect.succeed({
49 status: "ready",
50 agentId: "test-agent",
51 version: "1.0.0",
52 distribution: "binary",
53 }),
54 resolve: () => Effect.succeed(resolved),
55 search: () => Effect.die("unused"),
56 prepare: () => Effect.die("unused"),
57 uninstallManagedBinary: () => Effect.die("unused"),
58};
59
60const makeHarness = (
61 method: AcpSchema.AuthMethod,
62 failVerification = false,
63 settings = decodeSettings({ agentId: "test-agent" }),
64 providerInstanceId = instanceId,
65) =>
66 Effect.gen(function* () {
67 const verify = yield* Deferred.make<void>();
68 const changed: boolean[] = [];
69 const closed: number[] = [];
70 const authenticated: string[] = [];
71 const started: number[] = [];
72 let runtimes = 0;
73 let version = "1.0.0";
74 let terminalSpawn: PtyAdapter.PtySpawnInput | undefined;
75 let data: ((data: string) => void) | undefined;
76 let exit: ((event: PtyAdapter.PtyExitEvent) => void) | undefined;
77 let killed = false;
78 let closedBeforeTerminal = false;
79 const written: string[] = [];
80 const sizes: number[][] = [];
81 const controller = yield* makeAcpRegistryAuth({
82 instanceId: providerInstanceId,
83 settings,
84 cwd: "/workspace",
85 environment: { PATH: "/tools", OVERRIDE: "base" },
86 onChanged: (value) =>
87 Effect.sync(() => {
88 changed.push(value);
89 }),
90 makeRuntime: () =>
91 Effect.gen(function* () {
92 const id = ++runtimes;
93 yield* Effect.addFinalizer(() =>
94 Effect.sync(() => {
95 closed.push(id);
96 }),
97 );
98 const initialized: AcpSchema.InitializeResponse = {
99 protocolVersion: 2,
100 agentCapabilities: {},
101 authMethods: [{ ...method, name: `${method.name} ${version}` }],
102 };
103 let elicitation:
104 | Parameters<AcpSessionRuntime.AcpSessionRuntime["Service"]["handleElicitation"]>[0]
105 | undefined;
106 return {
107 initialize: () => Effect.succeed(initialized),
108 handleElicitation: (handler) =>
109 Effect.sync(() => {
110 elicitation = handler;
111 }),
112 authenticate: (methodId) =>
113 Effect.gen(function* () {
114 authenticated.push(methodId);
115 if (elicitation)
116 yield* elicitation(
117 {
118 mode: "url",
119 url: "https://example.com/login",
120 elicitationId: "consent",
121 requestId: "login",
122 message: "Sign in",
123 },
124 { requestId: "login", method: "elicitation/create" },
125 );
126 }),
127 start: () =>
128 Effect.gen(function* () {
129 started.push(id);
130 yield* Deferred.await(verify);
131 if (failVerification)
132 return yield* new AcpRequestError({
133 method: "session/new",
134 code: -32000,
135 errorMessage: "Authentication required",
136 });
137 return {
138 sessionId: "verified",
139 initializeResult: initialized,
140 sessionSetupResult: { sessionId: "verified" },
141 modelConfigId: undefined,
142 };
143 }),
144 logout: Effect.succeed({}),
145 };
146 }),
147 }).pipe(
148 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, {
149 ...catalog,
150 inspect: () =>
151 Effect.sync(() => ({
152 status: "ready" as const,
153 agentId: "test-agent",
154 version,
155 distribution: "binary" as const,
156 })),
157 }),
158 Effect.provideService(PtyAdapter.PtyAdapter, {
159 spawn: (input) =>
160 Effect.sync(() => {
161 terminalSpawn = input;
162 closedBeforeTerminal = closed.includes(runtimes);
163 return {
164 pid: 123,
165 write: (input) => {
166 written.push(input);
167 },
168 resize: (cols, rows) => {
169 sizes.push([cols, rows]);
170 },
171 kill: () => {
172 killed = true;
173 },
174 onData: (callback) => {
175 data = callback;
176 return () => {
177 data = undefined;
178 };
179 },
180 onExit: (callback) => {
181 exit = callback;
182 return () => {
183 exit = undefined;
184 };
185 },
186 };
187 }),
188 }),
189 );
190 const state = (predicate: (state: ProviderAuthState) => boolean) =>
191 controller
192 .subscribe("owner")
193 .pipe(Stream.filter(predicate), Stream.runHead, Effect.map(Option.getOrThrow));
194 const phase = (phase: ProviderAuthState["phase"]) => state((value) => value.phase === phase);
195 yield* state((value) => (value.methods?.length ?? 0) > 0);
196 return {
197 controller,
198 verify,
199 changed,
200 closed,
201 authenticated,
202 started,
203 phase,
204 state,
205 terminalSpawn: () => terminalSpawn,
206 closedBeforeTerminal: () => closedBeforeTerminal,
207 data: (value: string) => data?.(value),
208 exit: (exitCode: number) => exit?.({ exitCode, signal: null }),
209 killed: () => killed,
210 written,
211 sizes,
212 runtimes: () => runtimes,
213 setVersion: (value: string) => {
214 version = value;
215 },
216 };
217 }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog));
218
219it.effect("keeps local credentials separate from a matching registry agent ID", () =>
220 Effect.gen(function* () {
221 const registry = yield* makeHarness(browserMethod);
222 const local = yield* makeHarness(
223 browserMethod,
224 false,
225 decodeSettings({ source: "local", commandPath: "/different/agent" }),
226 ProviderInstanceId.make("test-agent"),
227 );
228 assert.deepEqual(registry.controller.credentialBinding, {
229 owner: "provider",
230 key: "acp:test-agent",
231 });
232 assert.deepEqual(local.controller.credentialBinding, {
233 owner: "provider",
234 key: "acp:local:test-agent",
235 });
236 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
237);
238
239it.effect(
240 "discovers methods without signing in, then waits for browser consent and session verification",
241 () =>
242 Effect.gen(function* () {
243 const h = yield* makeHarness(browserMethod);
244 assert.deepEqual(h.authenticated, []);
245 assert.deepEqual(h.started, []);
246 assert.deepEqual(h.closed, [1]);
247 const flow = yield* h.controller.start("owner", Effect.void, "browser");
248 const waiting = yield* h.phase("waiting");
249 assert.deepEqual(waiting.interaction, {
250 type: "browser",
251 id: "consent",
252 url: "https://example.com/login",
253 requiresConsent: true,
254 });
255 yield* h.controller.respond!("owner", {
256 instanceId,
257 flowId: flow.flowId!,
258 interactionId: "consent",
259 response: { type: "browser", action: "accept" },
260 });
261 yield* h.phase("verifying");
262 assert.deepEqual(h.changed, []);
263 yield* Deferred.succeed(h.verify, undefined);
264 yield* h.phase("succeeded");
265 assert.deepEqual(h.authenticated, ["browser"]);
266 assert.deepEqual(h.changed, [true]);
267 assert.deepEqual(h.closed, [1, 2]);
268 yield* h.controller.logout(Effect.void);
269 assert.deepEqual(h.changed, [true, false]);
270 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
271);
272
273it.effect(
274 "runs terminal auth directly with the resolved environment and reconnects to verify",
275 () =>
276 Effect.gen(function* () {
277 const h = yield* makeHarness(terminalMethod);
278 const flow = yield* h.controller.start("owner", Effect.void, "terminal");
279 yield* h.phase("waiting");
280 assert.isTrue(h.closedBeforeTerminal());
281 assert.deepEqual(h.terminalSpawn(), {
282 shell: "/managed/agent",
283 args: ["--acp", "login"],
284 cwd: "/workspace",
285 cols: 80,
286 rows: 24,
287 env: { PATH: "/tools", OVERRIDE: "method", AGENT_HOME: "/custom/home", LOGIN: "yes" },
288 });
289 h.data("Enter code: ");
290 const output = yield* h.state(
291 (value) =>
292 value.interaction?.type === "terminal" && value.interaction.output === "Enter code: ",
293 );
294 assert.strictEqual(
295 output.interaction?.type === "terminal" && output.interaction.outputOffset,
296 12,
297 );
298 yield* h.controller.respond!("owner", {
299 instanceId,
300 flowId: flow.flowId!,
301 interactionId: "terminal",
302 response: { type: "terminal", data: "123\r", size: { cols: 100, rows: 30 } },
303 });
304 assert.deepEqual(h.written, ["123\r"]);
305 assert.deepEqual(h.sizes, [[100, 30]]);
306 h.exit(0);
307 yield* h.phase("verifying");
308 assert.isTrue(h.killed());
309 assert.deepEqual(h.authenticated, []);
310 yield* Deferred.succeed(h.verify, undefined);
311 yield* h.phase("succeeded");
312 assert.deepEqual(h.started, [3]);
313 assert.deepEqual(h.changed, [true]);
314 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
315);
316
317it.effect("cancels the login PTY and rejects further terminal input", () =>
318 Effect.gen(function* () {
319 const h = yield* makeHarness(terminalMethod);
320 const flow = yield* h.controller.start("owner");
321 yield* h.phase("waiting");
322 yield* h.controller.cancel("owner", flow.flowId!);
323 assert.isTrue(h.killed());
324 assert.deepEqual(h.started, []);
325 assert.deepEqual(h.changed, []);
326 assert.strictEqual(
327 (yield* h.controller.respond!("owner", {
328 instanceId,
329 flowId: flow.flowId!,
330 interactionId: "terminal",
331 response: { type: "terminal", data: "late\r" },
332 }).pipe(Effect.result))._tag,
333 "Failure",
334 );
335 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
336);
337
338it.effect("does not report authentication when post-login verification fails", () =>
339 Effect.gen(function* () {
340 const h = yield* makeHarness(terminalMethod, true);
341 yield* h.controller.start("owner");
342 yield* h.phase("waiting");
343 h.exit(0);
344 yield* h.phase("verifying");
345 yield* Deferred.succeed(h.verify, undefined);
346 yield* h.phase("failed");
347 assert.deepEqual(h.changed, []);
348 assert.isTrue(h.killed());
349 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
350);
351
352it.effect("refreshes advertised methods after a registry version change without logging in", () =>
353 Effect.gen(function* () {
354 const h = yield* makeHarness(browserMethod);
355 const count = h.runtimes();
356 yield* h.controller.refreshMethods!;
357 assert.strictEqual(h.runtimes(), count);
358 h.setVersion("2.0.0");
359 yield* h.controller.refreshMethods!;
360 const state = yield* h.state((value) => value.methods?.[0]?.name === "Browser 2.0.0");
361 assert.strictEqual(state.phase, "idle");
362 assert.strictEqual(h.runtimes(), count + 1);
363 assert.deepEqual(h.authenticated, []);
364 assert.deepEqual(h.started, []);
365 assert.deepEqual(h.closed, [1, 2]);
366 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
367);