@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 505 lines 18.2 KB
Raw
1 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import * as Layer from "effect/Layer";
4 import { assert, it } from "@effect/vitest";
5 import { ProviderInstanceId, type ProviderAuthState } from "@t3tools/contracts";
6 import { AcpRegistrySettings } from "../settings.ts";
7 import * as Deferred from "effect/Deferred";
8 import * as Cause from "effect/Cause";
9 import * as Effect from "effect/Effect";
10 import * as Option from "effect/Option";
11 import * as Schema from "effect/Schema";
12 import * as Stream from "effect/Stream";
13 import type * as AcpSchema from "effect-acp/compat";
14 import { AcpRequestError } from "effect-acp/errors";
15
16 import * as PtyAdapter from "@t3tools/shared/PtyAdapter";
17 import { formatFailureDetail, makeAcpRegistryAuth } from "./auth.ts";
18 import * as AcpRegistrySupport from "./AcpRegistrySupport.ts";
19 import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
20
21 const decodeSettings = Schema.decodeSync(AcpRegistrySettings);
22 const instanceId = ProviderInstanceId.make("acp-auth-test");
23 const browserMethod = { id: "browser", name: "Browser", type: "agent" as const };
24 const terminalMethod = {
25 id: "terminal",
26 name: "Terminal",
27 type: "terminal" as const,
28 args: ["login"],
29 env: { LOGIN: "yes", OVERRIDE: "method" },
30 };
31 const 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 };
46 const 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
60 const makeHarness = (
61 method: AcpSchema.AuthMethod,
62 failVerification = false,
63 settings = decodeSettings({ agentId: "test-agent" }),
64 providerInstanceId = instanceId,
65 authenticateError?: AcpRequestError,
66 ) =>
67 Effect.gen(function* () {
68 const verify = yield* Deferred.make<void>();
69 const changed: boolean[] = [];
70 const closed: number[] = [];
71 const authenticated: string[] = [];
72 const started: number[] = [];
73 let runtimes = 0;
74 let version = "1.0.0";
75 let terminalSpawn: PtyAdapter.PtySpawnInput | undefined;
76 let data: ((data: string) => void) | undefined;
77 let exit: ((event: PtyAdapter.PtyExitEvent) => void) | undefined;
78 let killed = false;
79 let closedBeforeTerminal = false;
80 const written: Array<string | Buffer> = [];
81 const sizes: number[][] = [];
82 const controller = yield* makeAcpRegistryAuth({
83 instanceId: providerInstanceId,
84 settings,
85 cwd: "/workspace",
86 environment: { PATH: "/tools", OVERRIDE: "base" },
87 onChanged: (value) =>
88 Effect.sync(() => {
89 changed.push(value);
90 }),
91 makeRuntime: () =>
92 Effect.gen(function* () {
93 const id = ++runtimes;
94 yield* Effect.addFinalizer(() =>
95 Effect.sync(() => {
96 closed.push(id);
97 }),
98 );
99 const initialized: AcpSchema.InitializeResponse = {
100 protocolVersion: 2,
101 agentCapabilities: {},
102 authMethods: [{ ...method, name: `${method.name} ${version}` }],
103 };
104 let elicitation:
105 | Parameters<AcpSessionRuntime.AcpSessionRuntime["Service"]["handleElicitation"]>[0]
106 | undefined;
107 return {
108 initialize: () => Effect.succeed(initialized),
109 handleElicitation: (handler) =>
110 Effect.sync(() => {
111 elicitation = handler;
112 }),
113 authenticate: (methodId) =>
114 Effect.gen(function* () {
115 authenticated.push(methodId);
116 if (authenticateError !== undefined) {
117 return yield* authenticateError;
118 }
119 if (elicitation)
120 yield* elicitation(
121 {
122 mode: "url",
123 url: "https://example.com/login",
124 elicitationId: "consent",
125 requestId: "login",
126 message: "Sign in",
127 },
128 { requestId: "login", method: "elicitation/create" },
129 );
130 }),
131 start: () =>
132 Effect.gen(function* () {
133 started.push(id);
134 yield* Deferred.await(verify);
135 if (failVerification)
136 return yield* new AcpRequestError({
137 method: "session/new",
138 code: -32000,
139 errorMessage: "Authentication required",
140 });
141 return {
142 sessionId: "verified",
143 initializeResult: initialized,
144 sessionSetupResult: { sessionId: "verified" },
145 modelConfigId: undefined,
146 };
147 }),
148 logout: Effect.succeed({}),
149 };
150 }),
151 }).pipe(
152 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, {
153 ...catalog,
154 inspect: () =>
155 Effect.sync(() => ({
156 status: "ready" as const,
157 agentId: "test-agent",
158 version,
159 distribution: "binary" as const,
160 })),
161 }),
162 Effect.provideService(PtyAdapter.PtyAdapter, {
163 spawn: (input) =>
164 Effect.sync(() => {
165 terminalSpawn = input;
166 closedBeforeTerminal = closed.includes(runtimes);
167 return {
168 pid: 123,
169 write: (input) => {
170 written.push(input);
171 },
172 resize: (cols, rows) => {
173 sizes.push([cols, rows]);
174 },
175 kill: () => {
176 killed = true;
177 },
178 onData: (callback) => {
179 data = callback;
180 return () => {
181 data = undefined;
182 };
183 },
184 onExit: (callback) => {
185 exit = callback;
186 return () => {
187 exit = undefined;
188 };
189 },
190 };
191 }),
192 }),
193 );
194 const state = (predicate: (state: ProviderAuthState) => boolean) =>
195 controller
196 .subscribe("owner")
197 .pipe(Stream.filter(predicate), Stream.runHead, Effect.map(Option.getOrThrow));
198 const phase = (phase: ProviderAuthState["phase"]) => state((value) => value.phase === phase);
199 yield* state((value) => (value.methods?.length ?? 0) > 0);
200 return {
201 controller,
202 verify,
203 changed,
204 closed,
205 authenticated,
206 started,
207 phase,
208 state,
209 terminalSpawn: () => terminalSpawn,
210 closedBeforeTerminal: () => closedBeforeTerminal,
211 data: (value: string) => data?.(value),
212 exit: (exitCode: number) => exit?.({ exitCode, signal: null }),
213 killed: () => killed,
214 written,
215 sizes,
216 runtimes: () => runtimes,
217 setVersion: (value: string) => {
218 version = value;
219 },
220 };
221 }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog));
222
223 it.effect("keeps local credentials separate from a matching registry agent ID", () =>
224 Effect.gen(function* () {
225 const registry = yield* makeHarness(browserMethod);
226 const local = yield* makeHarness(
227 browserMethod,
228 false,
229 decodeSettings({ source: "local", commandPath: "/different/agent" }),
230 ProviderInstanceId.make("test-agent"),
231 );
232 assert.deepEqual(registry.controller.credentialBinding, {
233 owner: "provider",
234 key: "acp:test-agent",
235 });
236 assert.deepEqual(local.controller.credentialBinding, {
237 owner: "provider",
238 key: "acp:local:test-agent",
239 });
240 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
241 );
242
243 it.effect(
244 "discovers methods without signing in, then waits for browser consent and session verification",
245 () =>
246 Effect.gen(function* () {
247 const h = yield* makeHarness(browserMethod);
248 assert.deepEqual(h.authenticated, []);
249 assert.deepEqual(h.started, []);
250 assert.deepEqual(h.closed, [1]);
251 const flow = yield* h.controller.start("owner", Effect.void, "browser");
252 const waiting = yield* h.phase("waiting");
253 assert.deepEqual(waiting.interaction, {
254 type: "browser",
255 id: "consent",
256 url: "https://example.com/login",
257 requiresConsent: true,
258 });
259 yield* h.controller.respond!("owner", {
260 instanceId,
261 flowId: flow.flowId!,
262 interactionId: "consent",
263 response: { type: "browser", action: "accept" },
264 });
265 yield* h.phase("verifying");
266 assert.deepEqual(h.changed, []);
267 yield* Deferred.succeed(h.verify, undefined);
268 yield* h.phase("succeeded");
269 assert.deepEqual(h.authenticated, ["browser"]);
270 assert.deepEqual(h.changed, [true]);
271 assert.deepEqual(h.closed, [1, 2]);
272 yield* h.controller.logout(Effect.void);
273 assert.deepEqual(h.changed, [true, false]);
274 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
275 );
276
277 it.effect(
278 "runs terminal auth directly with the resolved environment and reconnects to verify",
279 () =>
280 Effect.gen(function* () {
281 const h = yield* makeHarness(terminalMethod);
282 const flow = yield* h.controller.start("owner", Effect.void, "terminal");
283 yield* h.phase("waiting");
284 assert.isTrue(h.closedBeforeTerminal());
285 assert.deepEqual(h.terminalSpawn(), {
286 shell: "/managed/agent",
287 args: ["--acp", "login"],
288 cwd: "/workspace",
289 cols: 80,
290 rows: 24,
291 env: { PATH: "/tools", OVERRIDE: "method", AGENT_HOME: "/custom/home", LOGIN: "yes" },
292 });
293 h.data("Enter code: ");
294 const output = yield* h.state(
295 (value) =>
296 value.interaction?.type === "terminal" && value.interaction.output === "Enter code: ",
297 );
298 assert.strictEqual(
299 output.interaction?.type === "terminal" && output.interaction.outputOffset,
300 12,
301 );
302 yield* h.controller.respond!("owner", {
303 instanceId,
304 flowId: flow.flowId!,
305 interactionId: "terminal",
306 response: { type: "terminal", data: "123\r", size: { cols: 100, rows: 30 } },
307 });
308 yield* h.controller.respond!("owner", {
309 instanceId,
310 flowId: flow.flowId!,
311 interactionId: "terminal",
312 response: { type: "terminal", data: "\x1b[M \x80(", binary: true },
313 });
314 assert.deepEqual(h.written, ["123\r", Buffer.from([0x1b, 0x5b, 0x4d, 0x20, 0x80, 0x28])]);
315 assert.deepEqual(h.sizes, [[100, 30]]);
316 h.exit(0);
317 yield* h.phase("verifying");
318 assert.isTrue(h.killed());
319 assert.deepEqual(h.authenticated, []);
320 yield* Deferred.succeed(h.verify, undefined);
321 yield* h.phase("succeeded");
322 assert.deepEqual(h.started, [3]);
323 assert.deepEqual(h.changed, [true]);
324 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
325 );
326
327 it.effect("cancels the login PTY and rejects further terminal input", () =>
328 Effect.gen(function* () {
329 const h = yield* makeHarness(terminalMethod);
330 const flow = yield* h.controller.start("owner");
331 yield* h.phase("waiting");
332 yield* h.controller.cancel("owner", flow.flowId!);
333 assert.isTrue(h.killed());
334 assert.deepEqual(h.started, []);
335 assert.deepEqual(h.changed, []);
336 assert.strictEqual(
337 (yield* h.controller.respond!("owner", {
338 instanceId,
339 flowId: flow.flowId!,
340 interactionId: "terminal",
341 response: { type: "terminal", data: "late\r" },
342 }).pipe(Effect.result))._tag,
343 "Failure",
344 );
345 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
346 );
347
348 it.effect("does not report authentication when post-login verification fails", () =>
349 Effect.gen(function* () {
350 const h = yield* makeHarness(terminalMethod, true);
351 yield* h.controller.start("owner");
352 yield* h.phase("waiting");
353 h.exit(0);
354 yield* h.phase("verifying");
355 yield* Deferred.succeed(h.verify, undefined);
356 const failed = yield* h.phase("failed");
357 assert.deepEqual(h.changed, []);
358 assert.isTrue(h.killed());
359 assert.strictEqual(
360 failed.message,
361 "The provider could not create a session after terminal sign-in. Authentication required",
362 );
363 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
364 );
365
366 it.effect("surfaces what the login command printed when it exits non-zero", () =>
367 Effect.gen(function* () {
368 const h = yield* makeHarness(terminalMethod);
369 yield* h.controller.start("owner", Effect.void, "terminal");
370 yield* h.phase("waiting");
371 h.data("Connect to the VPN, then sign in again.\r\n");
372 h.exit(1);
373 const failed = yield* h.phase("failed");
374 assert.strictEqual(
375 failed.message,
376 "The provider login command did not finish successfully. Connect to the VPN, then sign in again.",
377 );
378 assert.deepEqual(h.changed, []);
379 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
380 );
381
382 it.effect("surfaces the agent error message when authenticate fails with AcpRequestError", () =>
383 Effect.gen(function* () {
384 const error = new AcpRequestError({
385 method: "authenticate",
386 code: -32000,
387 errorMessage: "Connect to the VPN, then sign in again.",
388 });
389 const h = yield* makeHarness(
390 browserMethod,
391 false,
392 decodeSettings({ agentId: "test-agent" }),
393 instanceId,
394 error,
395 );
396 yield* h.controller.start("owner", Effect.void, "browser");
397 const failed = yield* h.phase("failed");
398 assert.strictEqual(
399 failed.message,
400 "The ACP agent could not complete sign-in. Connect to the VPN, then sign in again.",
401 );
402 assert.deepEqual(h.changed, []);
403 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
404 );
405
406 it.effect(
407 "surfaces the agent error message when post-sign-in verification fails for agent auth",
408 () =>
409 Effect.gen(function* () {
410 const h = yield* makeHarness(browserMethod, true);
411 const flow = yield* h.controller.start("owner", Effect.void, "browser");
412 yield* h.phase("waiting");
413 yield* h.controller.respond!("owner", {
414 instanceId,
415 flowId: flow.flowId!,
416 interactionId: "consent",
417 response: { type: "browser", action: "accept" },
418 });
419 yield* h.phase("verifying");
420 yield* Deferred.succeed(h.verify, undefined);
421 const failed = yield* h.phase("failed");
422 assert.strictEqual(
423 failed.message,
424 "The provider could not create a session after sign-in. Authentication required",
425 );
426 assert.deepEqual(h.changed, []);
427 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
428 );
429
430 it("formatFailureDetail handles all cause types and formatting edge cases cleanly", () => {
431 const baseWithPeriod = "The ACP agent could not complete sign-in.";
432 const baseWithoutPeriod = "The ACP agent could not complete sign-in";
433
434 // 1. undefined or null cause
435 assert.strictEqual(formatFailureDetail(baseWithPeriod, undefined), baseWithPeriod);
436 assert.strictEqual(formatFailureDetail(baseWithPeriod, null), baseWithPeriod);
437
438 // 2. plain Error object, string, number, or object defect
439 assert.strictEqual(
440 formatFailureDetail(baseWithPeriod, new Error("Something broke")),
441 baseWithPeriod,
442 );
443 assert.strictEqual(formatFailureDetail(baseWithPeriod, "string error"), baseWithPeriod);
444 assert.strictEqual(formatFailureDetail(baseWithPeriod, { foo: "bar" }), baseWithPeriod);
445
446 // 3. AcpRequestError with empty or whitespace-only errorMessage
447 const emptyError = new AcpRequestError({
448 method: "authenticate",
449 code: -32000,
450 errorMessage: "",
451 });
452 const whitespaceError = new AcpRequestError({
453 method: "authenticate",
454 code: -32000,
455 errorMessage: " \t\n ",
456 });
457 assert.strictEqual(formatFailureDetail(baseWithPeriod, emptyError), baseWithPeriod);
458 assert.strictEqual(formatFailureDetail(baseWithPeriod, whitespaceError), baseWithPeriod);
459
460 // 4. AcpRequestError with valid message: ensure no double periods, clean separation
461 const validError = new AcpRequestError({
462 method: "authenticate",
463 code: -32000,
464 errorMessage: "Connect to the VPN, then sign in again.",
465 });
466 assert.strictEqual(
467 formatFailureDetail(baseWithPeriod, validError),
468 "The ACP agent could not complete sign-in. Connect to the VPN, then sign in again.",
469 );
470 assert.strictEqual(
471 formatFailureDetail(baseWithoutPeriod, validError),
472 "The ACP agent could not complete sign-in. Connect to the VPN, then sign in again.",
473 );
474
475 // 5. AcpRequestError with trimmed message and message without ending period
476 const unpunctError = new AcpRequestError({
477 method: "authenticate",
478 code: -32000,
479 errorMessage: " Invalid credentials ",
480 });
481 assert.strictEqual(
482 formatFailureDetail(baseWithPeriod, unpunctError),
483 "The ACP agent could not complete sign-in. Invalid credentials",
484 );
485
486 // 6. Nested Cause (e.g. Cause.fail or Cause.die wrapping AcpRequestError)
487 assert.strictEqual(
488 formatFailureDetail(baseWithPeriod, Cause.fail(validError)),
489 "The ACP agent could not complete sign-in. Connect to the VPN, then sign in again.",
490 );
491 assert.strictEqual(
492 formatFailureDetail(baseWithPeriod, Cause.die(validError)),
493 "The ACP agent could not complete sign-in. Connect to the VPN, then sign in again.",
494 );
495
496 // 7. Extremely long error message: truncates to 500 characters with ellipsis
497 const longText = "A".repeat(600);
498 const longError = new AcpRequestError({
499 method: "authenticate",
500 code: -32000,
501 errorMessage: longText,
502 });
503 const expectedLong = `The ACP agent could not complete sign-in. ${"A".repeat(500)}…`;
504 assert.strictEqual(formatFailureDetail(baseWithPeriod, longError), expectedLong);
505 });