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

AcpRegistryAuth.test.ts

342 lines11.8 KB

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