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

AcpRegistryProbe.test.ts

483 lines16.1 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodePath from "node:path";
3import * as NodeURL from "node:url";
4​
5import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import * as Layer from "effect/Layer";
8import { ProviderInstanceId } from "@t3tools/contracts";
9import { AcpRegistrySettings } from "@t3tools/provider-acp-registry/settings";
10import { describe, expect, it } from "@effect/vitest";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Schema from "effect/Schema";
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 model ids instead of publishing mutated ids", () => {
145 const result = acpRegistryProbeResult(instanceId, {
146 sessionId: "probe-session",
147 initializeResult: { protocolVersion: 1 },
148 sessionSetupResult: {
149 sessionId: "probe-session",
150 configOptions: [
151 {
152 id: "model",
153 name: "Model",
154 category: "model",
155 type: "select",
156 currentValue: "x".repeat(129),
157 options: [
158 { value: "x".repeat(129), name: "Too long" },
159 { value: "valid", name: "Valid" },
160 ],
161 },
162 ],
163 },
164 modelConfigId: "model",
165 } satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult);
166​
167 expect(result.models).toEqual([{ id: "valid", name: "Valid", description: null }]);
168 expect(result.currentModelId).toBeNull();
169 });
170​
171 it("preserves grouped model values and advertises reasoning choices", () => {
172 const codexModel = '["codex","gpt-6.1-sol"]';
173 const goModel = '["opencode-go","deepseek-v4.1-flash"]';
174 const result = acpRegistryProbeResult(instanceId, {
175 sessionId: "probe-session",
176 initializeResult: { protocolVersion: 1 },
177 sessionSetupResult: {
178 sessionId: "probe-session",
179 configOptions: [
180 {
181 id: "model",
182 name: "Model",
183 category: "model",
184 type: "select",
185 currentValue: goModel,
186 options: [
187 {
188 groupId: "codex",
189 name: "Codex",
190 options: [{ value: codexModel, name: "GPT-6.1 Sol" }],
191 },
192 {
193 groupId: "opencode-go",
194 name: "OpenCode Go",
195 options: [{ value: goModel, name: "DeepSeek V4.1 Flash" }],
196 },
197 ],
198 },
199 {
200 id: "reasoning",
201 name: "Reasoning",
202 category: "thought_level",
203 type: "select",
204 currentValue: "high",
205 options: [
206 {
207 groupId: "effort",
208 name: "Effort",
209 options: [
210 { value: "medium", name: "Medium" },
211 { value: "high", name: "High" },
212 ],
213 },
214 ],
215 },
216 ],
217 },
218 modelConfigId: "model",
219 } satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult);
220​
221 expect(result.models).toEqual([
222 { id: codexModel, name: "GPT-6.1 Sol", description: null },
223 { id: goModel, name: "DeepSeek V4.1 Flash", description: null },
224 ]);
225 expect(result.currentModelId).toBe(goModel);
226 expect(result.configOptions).toEqual([
227 {
228 id: "reasoning",
229 label: "Reasoning",
230 type: "select",
231 currentValue: "high",
232 options: [
233 { id: "medium", label: "Medium" },
234 { id: "high", label: "High" },
235 ],
236 role: "reasoning",
237 },
238 ]);
239 });
240​
241 it.each(["config option", "session model state"] as const)(
242 "retains the current model beyond the catalog cap from %s",
243 (source) => {
244 const models = Array.from({ length: 257 }, (_, index) => ({
245 modelId: `model-${index}`,
246 name: `Model ${index}`,
247 }));
248 const result = acpRegistryProbeResult(instanceId, {
249 sessionId: "probe-session",
250 initializeResult: { protocolVersion: 1 },
251 sessionSetupResult: {
252 sessionId: "probe-session",
253 ...(source === "config option"
254 ? {
255 configOptions: [
256 {
257 id: "model",
258 name: "Model",
259 category: "model",
260 type: "select",
261 currentValue: "model-256",
262 options: models.map(({ modelId, name }) => ({ value: modelId, name })),
263 },
264 ],
265 }
266 : { models: { currentModelId: "model-256", availableModels: models } }),
267 },
268 modelConfigId: source === "config option" ? "model" : undefined,
269 } satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult);
270​
271 expect(result.models).toHaveLength(256);
272 expect(result.models[0]?.id).toBe("model-0");
273 expect(result.models.at(-1)?.id).toBe("model-256");
274 expect(result.currentModelId).toBe("model-256");
275 },
276 );
277​
278 it("keeps every distinct advertised command and de-duplicates the rest", () => {
279 const commands = normalizeAcpRegistryCommands([
280 {
281 name: "create_plan",
282 description: " Create a plan ",
283 input: { type: "text", hint: " topic " },
284 },
285 { name: "CREATE_PLAN", description: "duplicate" },
286 ...Array.from({ length: 140 }, (_, index) => ({
287 name: `command_${index}`,
288 description: "",
289 })),
290 { name: "$late-skill", description: "Advertised after 128 commands" },
291 ]);
292​
293 expect(commands.slashCommands).toHaveLength(141);
294 expect(commands.slashCommands.at(-1)).toEqual({ name: "command_139" });
295 expect(commands.slashCommands[0]).toEqual({
296 name: "create_plan",
297 description: "Create a plan",
298 input: { hint: "topic" },
299 });
300 expect(
301 commands.slashCommands.filter((command) => command.name.toLowerCase() === "create_plan"),
302 ).toHaveLength(1);
303 expect(commands.skills.map((skill) => skill.name)).toEqual(["late-skill"]);
304 });
305​
306 it("routes dollar-prefixed ACP commands to the provider skill menu", () => {
307 expect(
308 normalizeAcpRegistryCommands([
309 { name: "$workspace-skill", description: "Run the workspace skill" },
310 { name: "$WORKSPACE-SKILL", description: "duplicate" },
311 { name: "$", description: "empty" },
312 { name: "review", description: "Review changes" },
313 ]),
314 ).toEqual({
315 slashCommands: [{ name: "review", description: "Review changes" }],
316 skills: [
317 {
318 name: "workspace-skill",
319 description: "Run the workspace skill",
320 path: "acp://skill/workspace-skill",
321 scope: "agent",
322 enabled: true,
323 },
324 ],
325 });
326 });
327​
328 it.effect("lists native sessions and logs out through generic ACP lifecycle methods", () => {
329 const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({
330 search: () => Effect.die("unused search"),
331 prepare: () => Effect.die("unused prepare"),
332 inspect: () => Effect.die("unused inspect"),
333 uninstallManagedBinary: () => Effect.die("unused uninstall"),
334 resolve: () =>
335 Effect.succeed({
336 agent: {
337 id: "mock-agent",
338 name: "Mock Agent",
339 version: "1.0.0",
340 description: "ACP session management test agent",
341 distribution: { npx: { package: "mock-agent@1.0.0" } },
342 },
343 distribution: "npx" as const,
344 spawn: {
345 command: "node",
346 args: [mockAgentPath],
347 env: {
348 ...process.env,
349 T3_ACP_SESSION_LIFECYCLE: "1",
350 T3_ACP_AUTH_METHOD_ID: "mock-login",
351 },
352 },
353 }),
354 });
355 const input = {
356 instanceId,
357 settings: decodeSettings({ agentId: "mock-agent" }),
358 cwd: process.cwd(),
359 environment: process.env,
360 };
361​
362 return Effect.gen(function* () {
363 const listed = yield* listAcpRegistrySessions(input);
364 expect(listed).toMatchObject({
365 canLoad: true,
366 canResume: true,
367 nextCursor: null,
368 sessions: [
369 {
370 sessionId: "mock-session-1",
371 cwd: process.cwd(),
372 importedThreadId: null,
373 },
374 ],
375 });
376 yield* logoutAcpRegistry(input);
377 }).pipe(
378 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
379 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
380 Effect.scoped,
381 );
382 });
383​
384 it.live.each(["succeeds", "fails"] as const)(
385 "deletes its health-probe session when deletion is advertised and %s",
386 (deleteOutcome) =>
387 Effect.gen(function* () {
388 const fs = yield* FileSystem.FileSystem;
389 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "acp-probe-delete-" });
390 const requestLogPath = NodePath.join(directory, "requests.ndjson");
391 const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({
392 search: () => Effect.die("unused search"),
393 prepare: () => Effect.die("unused prepare"),
394 inspect: () => Effect.die("unused inspect"),
395 uninstallManagedBinary: () => Effect.die("unused uninstall"),
396 resolve: () =>
397 Effect.succeed({
398 agent: {
399 id: "mock-agent",
400 name: "Mock Agent",
401 version: "1.0.0",
402 description: "ACP probe cleanup test agent",
403 distribution: { npx: { package: "mock-agent@1.0.0" } },
404 },
405 distribution: "npx" as const,
406 spawn: {
407 command: "node",
408 args: [mockAgentPath],
409 env: {
410 ...process.env,
411 T3_ACP_V2_MANAGEMENT: "1",
412 T3_ACP_REQUEST_LOG_PATH: requestLogPath,
413 ...(deleteOutcome === "fails" ? { T3_ACP_FAIL_DELETE_SESSION: "1" } : {}),
414 },
415 },
416 }),
417 });
418​
419 const result = yield* probeAcpRegistryConfiguration({
420 instanceId,
421 settings: decodeSettings({ agentId: "mock-agent" }),
422 cwd: process.cwd(),
423 environment: process.env,
424 }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog));
425 expect(result.probe.ready).toBe(true);
426 expect(result.probe.sessionManagement.canDelete).toBe(true);
427​
428 const requests = (yield* fs.readFileString(requestLogPath))
429 .split("\n")
430 .filter((line) => line.length > 0)
431 .map((line) => JSON.parse(line));
432 expect(requests.filter((request) => request.method === "session/delete")).toEqual([
433 expect.objectContaining({ params: { sessionId: "mock-session-1" } }),
434 ]);
435 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
436 );
437​
438 it("distinguishes authentication failures from generic probe failures", () => {
439 const advertised = normalizeAcpRegistryAuthMethods([
440 { id: "grok-login", name: "Log in with Grok" },
441 ]);
442 const cause = new EffectAcpErrors.AcpRequestError({
443 code: -32000,
444 errorMessage: "login required",
445 });
446 const authFailure = acpRegistryProbeFailure(cause, advertised);
447 expect(authFailure.reason).toBe("authentication_failed");
448 expect(authFailure.message).toBe("The ACP agent could not complete authentication.");
449 expect(authFailure.cause).toBe(cause);
450 expect(authFailure.authMethods).toEqual([
451 {
452 id: "grok-login",
453 name: "Log in with Grok",
454 description: null,
455 type: "agent",
456 },
457 ]);
458 expect(
459 acpRegistryProbeFailure(
460 new EffectAcpErrors.AcpTransportError({
461 detail: "Authentication required",
462 cause: "credentials missing",
463 }),
464 ).reason,
465 ).toBe("authentication_failed");
466 const genericCause = new EffectAcpErrors.AcpTransportError({
467 detail: "connection closed",
468 cause: "closed",
469 });
470 const genericFailure = acpRegistryProbeFailure(genericCause);
471 expect(genericFailure.reason).toBe("probe_failed");
472 expect(genericFailure.message).toBe("The ACP agent could not create a test session.");
473 expect(genericFailure.cause).toBe(genericCause);
474 expect(
475 acpRegistryProbeFailure(
476 new EffectAcpErrors.AcpTransportError({
477 detail: "Failed while logging request",
478 cause: "logging failed",
479 }),
480 ).reason,
481 ).toBe("probe_failed");
482 });
483});