Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodePath from "node:path";
3import * as NodeURL from "node:url";
4
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import { ProviderInstanceId } from "@t3tools/contracts";
7import { AcpRegistrySettings } from "@t3tools/provider-acp-registry/settings";
8import { describe, expect, it } from "@effect/vitest";
9import * as Deferred from "effect/Deferred";
10import * as Effect from "effect/Effect";
11import * as Fiber from "effect/Fiber";
12import * as Schema from "effect/Schema";
13import * as TestClock from "effect/testing/TestClock";
14import * as EffectAcpErrors from "effect-acp/errors";
15
16import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
17import {
18 acpRegistryProbeFailure,
19 acpRegistryProbeResult,
20 listAcpRegistrySessions,
21 logoutAcpRegistry,
22 normalizeAcpRegistryAuthMethods,
23 normalizeAcpRegistryCommands,
24 probeAcpRegistryConfiguration,
25} from "@t3tools/provider-acp-registry/testing";
26import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRegistrySupport";
27
28const instanceId = ProviderInstanceId.make("acpRegistry_codex");
29const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
30const mockAgentPath = NodePath.join(__dirname, "../../scripts/acp-mock-agent.ts");
31const decodeSettings = Schema.decodeSync(AcpRegistrySettings);
32
33describe("ACP Registry probe", () => {
34 it("returns advertised auth methods and de-duplicated models", () => {
35 const result = acpRegistryProbeResult(instanceId, {
36 sessionId: "probe-session",
37 initializeResult: {
38 protocolVersion: 1,
39 agentCapabilities: {
40 loadSession: true,
41 auth: { logout: {} },
42 sessionCapabilities: { list: {}, resume: {} },
43 },
44 authMethods: [
45 { id: "chatgpt", name: "ChatGPT" },
46 {
47 id: "api-key",
48 name: "API key",
49 type: "env_var",
50 vars: [{ name: "OPENAI_API_KEY", label: "OpenAI API key" }],
51 },
52 { id: "login", name: "Terminal login", type: "terminal" },
53 ],
54 },
55 sessionSetupResult: {
56 sessionId: "probe-session",
57 configOptions: [
58 {
59 id: "model",
60 name: "Model",
61 category: "model",
62 type: "select",
63 currentValue: "gpt-5.4",
64 options: [
65 { value: "gpt-5.4", name: "GPT-5.4" },
66 { value: "gpt-5.4", name: "Duplicate" },
67 ],
68 },
69 ],
70 },
71 modelConfigId: "model",
72 } satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult);
73
74 expect(result).toEqual({
75 instanceId,
76 ready: true,
77 icon: null,
78 authMethods: [
79 { id: "chatgpt", name: "ChatGPT", description: null, type: "agent" },
80 {
81 id: "api-key",
82 name: "API key",
83 description: null,
84 type: "env_var",
85 envVarNames: ["OPENAI_API_KEY"],
86 },
87 { id: "login", name: "Terminal login", description: null, type: "terminal" },
88 ],
89 models: [{ id: "gpt-5.4", name: "GPT-5.4", description: null }],
90 currentModelId: "gpt-5.4",
91 configOptions: [],
92 sessionManagement: {
93 canList: true,
94 canLoad: true,
95 canResume: true,
96 canLogout: true,
97 canDelete: false,
98 canConfigureProviders: false,
99 },
100 });
101 });
102
103 it("composes runnable terminal auth commands from the resolved spawn recipe", () => {
104 const methods = normalizeAcpRegistryAuthMethods(
105 [
106 {
107 id: "login",
108 name: "Terminal login",
109 type: "terminal",
110 args: ["auth", "log in"],
111 env: { FORCE_TTY: "1" },
112 },
113 ],
114 { command: "/opt/agents/devin", args: ["--acp"] },
115 );
116
117 expect(methods).toEqual([
118 {
119 id: "login",
120 name: "Terminal login",
121 description: null,
122 type: "terminal",
123 command: "FORCE_TTY=1 /opt/agents/devin --acp auth 'log in'",
124 },
125 ]);
126 });
127
128 it("omits unsafe truncated auth commands instead of publishing broken shell", () => {
129 const methods = normalizeAcpRegistryAuthMethods(
130 [
131 {
132 id: "login",
133 name: "Terminal login",
134 type: "terminal",
135 args: ["x".repeat(2_048)],
136 },
137 ],
138 { command: "/opt/agents/devin", args: ["--acp"] },
139 );
140
141 expect(methods[0]).not.toHaveProperty("command");
142 });
143
144 it("omits overlong opaque auth method and environment variable ids", () => {
145 const methods = normalizeAcpRegistryAuthMethods([
146 { id: "x".repeat(129), name: "Invalid" },
147 {
148 id: "api-key",
149 name: "API key",
150 type: "env_var",
151 vars: [
152 { name: "y".repeat(129), label: "Invalid" },
153 { name: "OPENAI_API_KEY", label: "OpenAI API key" },
154 ],
155 },
156 ]);
157
158 expect(methods).toEqual([
159 {
160 id: "api-key",
161 name: "API key",
162 description: null,
163 type: "env_var",
164 envVarNames: ["OPENAI_API_KEY"],
165 },
166 ]);
167 });
168
169 it("falls back to model-category configuration options", () => {
170 const result = acpRegistryProbeResult(instanceId, {
171 sessionId: "probe-session",
172 initializeResult: { protocolVersion: 1 },
173 sessionSetupResult: {
174 sessionId: "probe-session",
175 configOptions: [
176 {
177 id: "model",
178 name: "Model",
179 category: "model",
180 type: "select",
181 currentValue: "sonnet",
182 options: [
183 { value: "sonnet", name: "Sonnet", description: "Balanced" },
184 { value: "haiku", name: "Haiku" },
185 ],
186 },
187 ],
188 },
189 modelConfigId: "model",
190 } satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult);
191
192 expect(result.models).toEqual([
193 { id: "sonnet", name: "Sonnet", description: "Balanced" },
194 { id: "haiku", name: "Haiku", description: null },
195 ]);
196 expect(result.currentModelId).toBe("sonnet");
197 });
198
199 it("omits overlong opaque model ids instead of publishing mutated ids", () => {
200 const result = acpRegistryProbeResult(instanceId, {
201 sessionId: "probe-session",
202 initializeResult: { protocolVersion: 1 },
203 sessionSetupResult: {
204 sessionId: "probe-session",
205 configOptions: [
206 {
207 id: "model",
208 name: "Model",
209 category: "model",
210 type: "select",
211 currentValue: "x".repeat(129),
212 options: [
213 { value: "x".repeat(129), name: "Too long" },
214 { value: "valid", name: "Valid" },
215 ],
216 },
217 ],
218 },
219 modelConfigId: "model",
220 } satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult);
221
222 expect(result.models).toEqual([{ id: "valid", name: "Valid", description: null }]);
223 expect(result.currentModelId).toBeNull();
224 });
225
226 it("preserves grouped model values and advertises reasoning choices", () => {
227 const codexModel = '["codex","gpt-6.1-sol"]';
228 const goModel = '["opencode-go","deepseek-v4.1-flash"]';
229 const result = acpRegistryProbeResult(instanceId, {
230 sessionId: "probe-session",
231 initializeResult: { protocolVersion: 1 },
232 sessionSetupResult: {
233 sessionId: "probe-session",
234 configOptions: [
235 {
236 id: "model",
237 name: "Model",
238 category: "model",
239 type: "select",
240 currentValue: goModel,
241 options: [
242 {
243 groupId: "codex",
244 name: "Codex",
245 options: [{ value: codexModel, name: "GPT-6.1 Sol" }],
246 },
247 {
248 groupId: "opencode-go",
249 name: "OpenCode Go",
250 options: [{ value: goModel, name: "DeepSeek V4.1 Flash" }],
251 },
252 ],
253 },
254 {
255 id: "reasoning",
256 name: "Reasoning",
257 category: "thought_level",
258 type: "select",
259 currentValue: "high",
260 options: [
261 {
262 groupId: "effort",
263 name: "Effort",
264 options: [
265 { value: "medium", name: "Medium" },
266 { value: "high", name: "High" },
267 ],
268 },
269 ],
270 },
271 ],
272 },
273 modelConfigId: "model",
274 } satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult);
275
276 expect(result.models).toEqual([
277 { id: codexModel, name: "GPT-6.1 Sol", description: null },
278 { id: goModel, name: "DeepSeek V4.1 Flash", description: null },
279 ]);
280 expect(result.currentModelId).toBe(goModel);
281 expect(result.configOptions).toEqual([
282 {
283 id: "reasoning",
284 label: "Reasoning",
285 type: "select",
286 currentValue: "high",
287 options: [
288 { id: "medium", label: "Medium" },
289 { id: "high", label: "High" },
290 ],
291 },
292 ]);
293 });
294
295 it.each(["config option", "session model state"] as const)(
296 "retains the current model beyond the catalog cap from %s",
297 (source) => {
298 const models = Array.from({ length: 257 }, (_, index) => ({
299 modelId: `model-${index}`,
300 name: `Model ${index}`,
301 }));
302 const result = acpRegistryProbeResult(instanceId, {
303 sessionId: "probe-session",
304 initializeResult: { protocolVersion: 1 },
305 sessionSetupResult: {
306 sessionId: "probe-session",
307 ...(source === "config option"
308 ? {
309 configOptions: [
310 {
311 id: "model",
312 name: "Model",
313 category: "model",
314 type: "select",
315 currentValue: "model-256",
316 options: models.map(({ modelId, name }) => ({ value: modelId, name })),
317 },
318 ],
319 }
320 : { models: { currentModelId: "model-256", availableModels: models } }),
321 },
322 modelConfigId: source === "config option" ? "model" : undefined,
323 } satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult);
324
325 expect(result.models).toHaveLength(256);
326 expect(result.models[0]?.id).toBe("model-0");
327 expect(result.models.at(-1)?.id).toBe("model-256");
328 expect(result.currentModelId).toBe("model-256");
329 },
330 );
331
332 it("bounds and de-duplicates advertised commands", () => {
333 const commands = normalizeAcpRegistryCommands([
334 {
335 name: "create_plan",
336 description: " Create a plan ",
337 input: { type: "text", hint: " topic " },
338 },
339 { name: "CREATE_PLAN", description: "duplicate" },
340 ...Array.from({ length: 140 }, (_, index) => ({
341 name: `command_${index}`,
342 description: "",
343 })),
344 ]);
345
346 expect(commands.slashCommands).toHaveLength(128);
347 expect(commands.slashCommands[0]).toEqual({
348 name: "create_plan",
349 description: "Create a plan",
350 input: { hint: "topic" },
351 });
352 expect(
353 commands.slashCommands.filter((command) => command.name.toLowerCase() === "create_plan"),
354 ).toHaveLength(1);
355 expect(commands.skills).toEqual([]);
356 });
357
358 it("routes dollar-prefixed ACP commands to the provider skill menu", () => {
359 expect(
360 normalizeAcpRegistryCommands([
361 { name: "$workspace-skill", description: "Run the workspace skill" },
362 { name: "$WORKSPACE-SKILL", description: "duplicate" },
363 { name: "$", description: "empty" },
364 { name: "review", description: "Review changes" },
365 ]),
366 ).toEqual({
367 slashCommands: [{ name: "review", description: "Review changes" }],
368 skills: [
369 {
370 name: "workspace-skill",
371 description: "Run the workspace skill",
372 path: "acp://skill/workspace-skill",
373 scope: "agent",
374 enabled: true,
375 },
376 ],
377 });
378 });
379
380 it.effect("captures commands advertised just after session creation", () =>
381 Effect.gen(function* () {
382 const result = yield* probeAcpRegistryConfiguration({
383 instanceId,
384 settings: decodeSettings({ agentId: "mock-agent" }),
385 cwd: process.cwd(),
386 environment: process.env,
387 });
388
389 expect(result.slashCommands).toEqual([
390 {
391 name: "review",
392 description: "Review the current changes",
393 input: { hint: "focus" },
394 },
395 ]);
396 expect(result.skills).toEqual([
397 {
398 name: "workspace-skill",
399 description: "Run the workspace skill",
400 path: "acp://skill/workspace-skill",
401 scope: "agent",
402 enabled: true,
403 },
404 ]);
405 }).pipe(
406 Effect.provideService(
407 AcpRegistrySupport.AcpRegistryCatalog,
408 AcpRegistrySupport.AcpRegistryCatalog.of({
409 search: () => Effect.die("unused search"),
410 prepare: () => Effect.die("unused prepare"),
411 inspect: () => Effect.die("unused inspect"),
412 uninstallManagedBinary: () => Effect.die("unused uninstall"),
413 resolve: () =>
414 Effect.succeed({
415 agent: {
416 id: "mock-agent",
417 name: "Mock Agent",
418 version: "1.0.0",
419 description: "ACP probe test agent",
420 distribution: { npx: { package: "mock-agent@1.0.0" } },
421 },
422 distribution: "npx",
423 spawn: {
424 command: "node",
425 args: [mockAgentPath],
426 env: {
427 ...process.env,
428 T3_ACP_COMMAND_ADVERTISEMENT_DELAY_MS: "25",
429 },
430 },
431 }),
432 }),
433 ),
434 Effect.provide(NodeServices.layer),
435 Effect.scoped,
436 ),
437 );
438
439 it.effect("includes package resolution in the probe timeout", () =>
440 Effect.gen(function* () {
441 const resolveStarted = yield* Deferred.make<void>();
442 const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({
443 search: () => Effect.die("unused search"),
444 prepare: () => Effect.die("unused prepare"),
445 inspect: () => Effect.die("unused inspect"),
446 uninstallManagedBinary: () => Effect.die("unused uninstall"),
447 resolve: () =>
448 Deferred.succeed(resolveStarted, undefined).pipe(Effect.andThen(Effect.never)),
449 });
450 const probe = yield* probeAcpRegistryConfiguration({
451 instanceId,
452 settings: decodeSettings({ agentId: "slow-agent" }),
453 cwd: process.cwd(),
454 environment: process.env,
455 }).pipe(
456 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
457 Effect.flip,
458 Effect.forkChild({ startImmediately: true }),
459 );
460
461 yield* Deferred.await(resolveStarted);
462 yield* TestClock.adjust("60 seconds");
463
464 expect(yield* Fiber.join(probe)).toMatchObject({
465 reason: "probe_failed",
466 message: expect.stringContaining("within 60 seconds"),
467 });
468 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
469 );
470
471 it.effect("lists native sessions and logs out through generic ACP lifecycle methods", () => {
472 const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({
473 search: () => Effect.die("unused search"),
474 prepare: () => Effect.die("unused prepare"),
475 inspect: () => Effect.die("unused inspect"),
476 uninstallManagedBinary: () => Effect.die("unused uninstall"),
477 resolve: () =>
478 Effect.succeed({
479 agent: {
480 id: "mock-agent",
481 name: "Mock Agent",
482 version: "1.0.0",
483 description: "ACP session management test agent",
484 distribution: { npx: { package: "mock-agent@1.0.0" } },
485 },
486 distribution: "npx" as const,
487 spawn: {
488 command: "node",
489 args: [mockAgentPath],
490 env: {
491 ...process.env,
492 T3_ACP_SESSION_LIFECYCLE: "1",
493 T3_ACP_AUTH_METHOD_ID: "mock-login",
494 },
495 },
496 }),
497 });
498 const input = {
499 instanceId,
500 settings: decodeSettings({ agentId: "mock-agent" }),
501 cwd: process.cwd(),
502 environment: process.env,
503 };
504
505 return Effect.gen(function* () {
506 const listed = yield* listAcpRegistrySessions(input);
507 expect(listed).toMatchObject({
508 canLoad: true,
509 canResume: true,
510 nextCursor: null,
511 sessions: [
512 {
513 sessionId: "mock-session-1",
514 cwd: process.cwd(),
515 importedThreadId: null,
516 },
517 ],
518 });
519 yield* logoutAcpRegistry(input);
520 }).pipe(
521 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
522 Effect.provide(NodeServices.layer),
523 Effect.scoped,
524 );
525 });
526
527 it.effect("preserves the ACP method error for unsupported session management", () => {
528 const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({
529 search: () => Effect.die("unused search"),
530 prepare: () => Effect.die("unused prepare"),
531 inspect: () => Effect.die("unused inspect"),
532 uninstallManagedBinary: () => Effect.die("unused uninstall"),
533 resolve: () =>
534 Effect.succeed({
535 agent: {
536 id: "mock-agent",
537 name: "Mock Agent",
538 version: "1.0.0",
539 description: "ACP unsupported management test agent",
540 distribution: { npx: { package: "mock-agent@1.0.0" } },
541 },
542 distribution: "npx" as const,
543 spawn: {
544 command: "node",
545 args: [mockAgentPath],
546 env: { ...process.env, T3_ACP_OMIT_SESSION_LIST_HANDLER: "1" },
547 },
548 }),
549 });
550
551 return Effect.gen(function* () {
552 const failure = yield* listAcpRegistrySessions({
553 instanceId,
554 settings: decodeSettings({ agentId: "mock-agent" }),
555 cwd: process.cwd(),
556 environment: process.env,
557 }).pipe(Effect.flip);
558
559 expect(failure).toMatchObject({
560 reason: "session_list_unsupported",
561 message: "The ACP agent does not advertise session listing.",
562 cause: { _tag: "AcpRequestError", code: -32601 },
563 });
564 }).pipe(
565 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
566 Effect.provide(NodeServices.layer),
567 Effect.scoped,
568 );
569 });
570
571 it("distinguishes authentication failures from generic probe failures", () => {
572 const advertised = normalizeAcpRegistryAuthMethods([
573 { id: "grok-login", name: "Log in with Grok" },
574 ]);
575 const cause = new EffectAcpErrors.AcpRequestError({
576 code: -32000,
577 errorMessage: "login required",
578 });
579 const authFailure = acpRegistryProbeFailure(cause, advertised);
580 expect(authFailure.reason).toBe("authentication_failed");
581 expect(authFailure.message).toBe("The ACP agent could not complete authentication.");
582 expect(authFailure.cause).toBe(cause);
583 expect(authFailure.authMethods).toEqual([
584 {
585 id: "grok-login",
586 name: "Log in with Grok",
587 description: null,
588 type: "agent",
589 },
590 ]);
591 expect(
592 acpRegistryProbeFailure(
593 new EffectAcpErrors.AcpTransportError({
594 detail: "Authentication required",
595 cause: "credentials missing",
596 }),
597 ).reason,
598 ).toBe("authentication_failed");
599 const genericCause = new EffectAcpErrors.AcpTransportError({
600 detail: "connection closed",
601 cause: "closed",
602 });
603 const genericFailure = acpRegistryProbeFailure(genericCause);
604 expect(genericFailure.reason).toBe("probe_failed");
605 expect(genericFailure.message).toBe("The ACP agent could not create a test session.");
606 expect(genericFailure.cause).toBe(genericCause);
607 expect(
608 acpRegistryProbeFailure(
609 new EffectAcpErrors.AcpTransportError({
610 detail: "Failed while logging request",
611 cause: "logging failed",
612 }),
613 ).reason,
614 ).toBe("probe_failed");
615 });
616});