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