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 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 makeAcpRegistryTextGeneration,
23 normalizeAcpRegistryAuthMethods,
24 normalizeAcpRegistryCommands,
25 probeAcpRegistryConfiguration,
26} from "@t3tools/provider-acp-registry/testing";
27import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRegistrySupport";
28
29const instanceId = ProviderInstanceId.make("acpRegistry_codex");
30const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
31const mockAgentPath = NodePath.join(__dirname, "../../scripts/acp-mock-agent.ts");
32const decodeSettings = Schema.decodeSync(AcpRegistrySettings);
33
34describe("ACP Registry probe", () => {
35 it("returns advertised auth methods and de-duplicated models", () => {
36 const result = acpRegistryProbeResult(instanceId, {
37 sessionId: "probe-session",
38 initializeResult: {
39 protocolVersion: 1,
40 agentCapabilities: {
41 loadSession: true,
42 auth: { logout: {} },
43 sessionCapabilities: { list: {}, resume: {} },
44 },
45 authMethods: [
46 { id: "chatgpt", name: "ChatGPT" },
47 {
48 id: "api-key",
49 name: "API key",
50 type: "env_var",
51 vars: [{ name: "OPENAI_API_KEY", label: "OpenAI API key" }],
52 },
53 { id: "login", name: "Terminal login", type: "terminal" },
54 ],
55 },
56 sessionSetupResult: {
57 sessionId: "probe-session",
58 configOptions: [
59 {
60 id: "model",
61 name: "Model",
62 category: "model",
63 type: "select",
64 currentValue: "gpt-5.4",
65 options: [
66 { value: "gpt-5.4", name: "GPT-5.4" },
67 { value: "gpt-5.4", name: "Duplicate" },
68 ],
69 },
70 {
71 id: "effort",
72 name: "Effort",
73 category: "thought_level",
74 type: "select",
75 currentValue: "high",
76 options: [{ value: "high", name: "High" }],
77 },
78 {
79 id: "mode",
80 name: "Mode",
81 category: "mode",
82 type: "select",
83 currentValue: "ask",
84 options: [{ value: "ask", name: "Ask" }],
85 },
86 ],
87 },
88 modelConfigId: "model",
89 } satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult);
90
91 expect(result).toEqual({
92 instanceId,
93 ready: true,
94 icon: null,
95 authMethods: [
96 { id: "chatgpt", name: "ChatGPT", description: null, type: "agent" },
97 {
98 id: "api-key",
99 name: "API key",
100 description: null,
101 type: "env_var",
102 envVarNames: ["OPENAI_API_KEY"],
103 },
104 { id: "login", name: "Terminal login", description: null, type: "terminal" },
105 ],
106 models: [{ id: "gpt-5.4", name: "GPT-5.4", description: null }],
107 currentModelId: "gpt-5.4",
108 configOptions: [
109 {
110 id: "effort",
111 label: "Effort",
112 type: "select",
113 options: [{ id: "high", label: "High" }],
114 currentValue: "high",
115 role: "reasoning",
116 },
117 {
118 id: "mode",
119 label: "Mode",
120 type: "select",
121 options: [{ id: "ask", label: "Ask" }],
122 currentValue: "ask",
123 role: "mode",
124 },
125 ],
126 modelOptionIds: ["effort"],
127 sessionManagement: {
128 canList: true,
129 canLoad: true,
130 canResume: true,
131 canLogout: true,
132 canDelete: false,
133 canConfigureProviders: false,
134 },
135 });
136 });
137
138 it("composes runnable terminal auth commands from the resolved spawn recipe", () => {
139 const methods = normalizeAcpRegistryAuthMethods(
140 [
141 {
142 id: "login",
143 name: "Terminal login",
144 type: "terminal",
145 args: ["auth", "log in"],
146 env: { FORCE_TTY: "1" },
147 },
148 ],
149 { command: "/opt/agents/devin", args: ["--acp"] },
150 );
151
152 expect(methods).toEqual([
153 {
154 id: "login",
155 name: "Terminal login",
156 description: null,
157 type: "terminal",
158 command: "FORCE_TTY=1 /opt/agents/devin --acp auth 'log in'",
159 },
160 ]);
161 });
162
163 it("omits unsafe truncated auth commands instead of publishing broken shell", () => {
164 const methods = normalizeAcpRegistryAuthMethods(
165 [
166 {
167 id: "login",
168 name: "Terminal login",
169 type: "terminal",
170 args: ["x".repeat(2_048)],
171 },
172 ],
173 { command: "/opt/agents/devin", args: ["--acp"] },
174 );
175
176 expect(methods[0]).not.toHaveProperty("command");
177 });
178
179 it("omits overlong opaque model ids instead of publishing mutated ids", () => {
180 const result = acpRegistryProbeResult(instanceId, {
181 sessionId: "probe-session",
182 initializeResult: { protocolVersion: 1 },
183 sessionSetupResult: {
184 sessionId: "probe-session",
185 configOptions: [
186 {
187 id: "model",
188 name: "Model",
189 category: "model",
190 type: "select",
191 currentValue: "x".repeat(129),
192 options: [
193 { value: "x".repeat(129), name: "Too long" },
194 { value: "valid", name: "Valid" },
195 ],
196 },
197 ],
198 },
199 modelConfigId: "model",
200 } satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult);
201
202 expect(result.models).toEqual([{ id: "valid", name: "Valid", description: null }]);
203 expect(result.currentModelId).toBeNull();
204 });
205
206 it("preserves grouped model values and advertises reasoning choices", () => {
207 const codexModel = '["codex","gpt-6.1-sol"]';
208 const goModel = '["opencode-go","deepseek-v4.1-flash"]';
209 const result = acpRegistryProbeResult(instanceId, {
210 sessionId: "probe-session",
211 initializeResult: { protocolVersion: 1 },
212 sessionSetupResult: {
213 sessionId: "probe-session",
214 configOptions: [
215 {
216 id: "model",
217 name: "Model",
218 category: "model",
219 type: "select",
220 currentValue: goModel,
221 options: [
222 {
223 groupId: "codex",
224 name: "Codex",
225 options: [{ value: codexModel, name: "GPT-6.1 Sol" }],
226 },
227 {
228 groupId: "opencode-go",
229 name: "OpenCode Go",
230 options: [{ value: goModel, name: "DeepSeek V4.1 Flash" }],
231 },
232 ],
233 },
234 {
235 id: "reasoning",
236 name: "Reasoning",
237 category: "thought_level",
238 type: "select",
239 currentValue: "high",
240 options: [
241 {
242 groupId: "effort",
243 name: "Effort",
244 options: [
245 { value: "medium", name: "Medium" },
246 { value: "high", name: "High" },
247 ],
248 },
249 ],
250 },
251 ],
252 },
253 modelConfigId: "model",
254 } satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult);
255
256 expect(result.models).toEqual([
257 { id: codexModel, name: "GPT-6.1 Sol", description: null },
258 { id: goModel, name: "DeepSeek V4.1 Flash", description: null },
259 ]);
260 expect(result.currentModelId).toBe(goModel);
261 expect(result.configOptions).toEqual([
262 {
263 id: "reasoning",
264 label: "Reasoning",
265 type: "select",
266 currentValue: "high",
267 options: [
268 { id: "medium", label: "Medium" },
269 { id: "high", label: "High" },
270 ],
271 role: "reasoning",
272 },
273 ]);
274 });
275
276 it.each(["config option", "session model state"] as const)(
277 "retains the current model beyond the catalog cap from %s",
278 (source) => {
279 const models = Array.from({ length: 257 }, (_, index) => ({
280 modelId: `model-${index}`,
281 name: `Model ${index}`,
282 }));
283 const result = acpRegistryProbeResult(instanceId, {
284 sessionId: "probe-session",
285 initializeResult: { protocolVersion: 1 },
286 sessionSetupResult: {
287 sessionId: "probe-session",
288 ...(source === "config option"
289 ? {
290 configOptions: [
291 {
292 id: "model",
293 name: "Model",
294 category: "model",
295 type: "select",
296 currentValue: "model-256",
297 options: models.map(({ modelId, name }) => ({ value: modelId, name })),
298 },
299 ],
300 }
301 : { models: { currentModelId: "model-256", availableModels: models } }),
302 },
303 modelConfigId: source === "config option" ? "model" : undefined,
304 } satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult);
305
306 expect(result.models).toHaveLength(256);
307 expect(result.models[0]?.id).toBe("model-0");
308 expect(result.models.at(-1)?.id).toBe("model-256");
309 expect(result.currentModelId).toBe("model-256");
310 },
311 );
312
313 it("keeps every distinct advertised command and de-duplicates the rest", () => {
314 const commands = normalizeAcpRegistryCommands([
315 {
316 name: "create_plan",
317 description: " Create a plan ",
318 input: { type: "text", hint: " topic " },
319 },
320 { name: "CREATE_PLAN", description: "duplicate" },
321 ...Array.from({ length: 140 }, (_, index) => ({
322 name: `command_${index}`,
323 description: "",
324 })),
325 { name: "$late-skill", description: "Advertised after 128 commands" },
326 ]);
327
328 expect(commands.slashCommands).toHaveLength(141);
329 expect(commands.slashCommands.at(-1)).toEqual({ name: "command_139" });
330 expect(commands.slashCommands[0]).toEqual({
331 name: "create_plan",
332 description: "Create a plan",
333 input: { hint: "topic" },
334 });
335 expect(
336 commands.slashCommands.filter((command) => command.name.toLowerCase() === "create_plan"),
337 ).toHaveLength(1);
338 expect(commands.skills.map((skill) => skill.name)).toEqual(["late-skill"]);
339 });
340
341 it("routes dollar-prefixed ACP commands to the provider skill menu", () => {
342 expect(
343 normalizeAcpRegistryCommands([
344 { name: "$workspace-skill", description: "Run the workspace skill" },
345 { name: "$WORKSPACE-SKILL", description: "duplicate" },
346 { name: "$", description: "empty" },
347 { name: "review", description: "Review changes" },
348 ]),
349 ).toEqual({
350 slashCommands: [{ name: "review", description: "Review changes" }],
351 skills: [
352 {
353 name: "workspace-skill",
354 description: "Run the workspace skill",
355 path: "acp://skill/workspace-skill",
356 scope: "agent",
357 enabled: true,
358 },
359 ],
360 });
361 });
362
363 it.effect("lists native sessions and logs out through generic ACP lifecycle methods", () => {
364 const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({
365 search: () => Effect.die("unused search"),
366 prepare: () => Effect.die("unused prepare"),
367 refreshIndex: () => Effect.succeed(false),
368 invalidateIndex: () => Effect.void,
369 inspect: () => Effect.die("unused inspect"),
370 uninstallManagedBinary: () => Effect.die("unused uninstall"),
371 resolve: () =>
372 Effect.succeed({
373 agent: {
374 id: "mock-agent",
375 name: "Mock Agent",
376 version: "1.0.0",
377 description: "ACP session management test agent",
378 distribution: { npx: { package: "mock-agent@1.0.0" } },
379 },
380 distribution: "npx" as const,
381 spawn: {
382 command: "node",
383 args: [mockAgentPath],
384 env: {
385 ...process.env,
386 T3_ACP_SESSION_LIFECYCLE: "1",
387 T3_ACP_AUTH_METHOD_ID: "mock-login",
388 },
389 },
390 }),
391 });
392 const input = {
393 instanceId,
394 settings: decodeSettings({ agentId: "mock-agent" }),
395 cwd: process.cwd(),
396 environment: process.env,
397 };
398
399 return Effect.gen(function* () {
400 const listed = yield* listAcpRegistrySessions(input);
401 expect(listed).toMatchObject({
402 canLoad: true,
403 canResume: true,
404 nextCursor: null,
405 sessions: [
406 {
407 sessionId: "mock-session-1",
408 cwd: process.cwd(),
409 importedThreadId: null,
410 },
411 ],
412 });
413 yield* logoutAcpRegistry(input);
414 }).pipe(
415 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
416 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
417 );
418 });
419
420 it.live.each(["succeeds", "fails"] as const)(
421 "deletes its health-probe session when deletion is advertised and %s",
422 (deleteOutcome) =>
423 Effect.gen(function* () {
424 const fs = yield* FileSystem.FileSystem;
425 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "acp-probe-delete-" });
426 const requestLogPath = NodePath.join(directory, "requests.ndjson");
427 const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({
428 search: () => Effect.die("unused search"),
429 prepare: () => Effect.die("unused prepare"),
430 refreshIndex: () => Effect.succeed(false),
431 invalidateIndex: () => Effect.void,
432 inspect: () => Effect.die("unused inspect"),
433 uninstallManagedBinary: () => Effect.die("unused uninstall"),
434 resolve: () =>
435 Effect.succeed({
436 agent: {
437 id: "mock-agent",
438 name: "Mock Agent",
439 version: "1.0.0",
440 description: "ACP probe cleanup test agent",
441 distribution: { npx: { package: "mock-agent@1.0.0" } },
442 },
443 distribution: "npx" as const,
444 spawn: {
445 command: "node",
446 args: [mockAgentPath],
447 env: {
448 ...process.env,
449 T3_ACP_V2_MANAGEMENT: "1",
450 T3_ACP_REQUEST_LOG_PATH: requestLogPath,
451 ...(deleteOutcome === "fails" ? { T3_ACP_FAIL_DELETE_SESSION: "1" } : {}),
452 },
453 },
454 }),
455 });
456
457 const result = yield* probeAcpRegistryConfiguration({
458 instanceId,
459 settings: decodeSettings({ agentId: "mock-agent" }),
460 cwd: process.cwd(),
461 environment: process.env,
462 }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog));
463 expect(result.probe.ready).toBe(true);
464 expect(result.probe.sessionManagement.canDelete).toBe(true);
465
466 const requests = (yield* fs.readFileString(requestLogPath))
467 .split("\n")
468 .filter((line) => line.length > 0)
469 .map((line) => JSON.parse(line));
470 expect(requests.filter((request) => request.method === "session/delete")).toEqual([
471 expect.objectContaining({ params: { sessionId: "mock-session-1" } }),
472 ]);
473 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
474 );
475
476 it.live("keeps DeepSeek Harness probe history in a temporary directory", () =>
477 Effect.gen(function* () {
478 const fs = yield* FileSystem.FileSystem;
479 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "acp-probe-dsh-" });
480 const launcher = NodePath.join(directory, "dsh-fixture.mjs");
481 const launchLog = NodePath.join(directory, "launch.json");
482 yield* fs.writeFileString(
483 launcher,
484 `
485import { readFileSync, writeFileSync } from "node:fs";
486import { pathToFileURL } from "node:url";
487const [,, agentPath, logPath, ...args] = process.argv;
488const patchFlag = args.lastIndexOf("--patch");
489const patchPath = patchFlag === -1 ? null : args[patchFlag + 1];
490const patch = patchPath === null ? null : JSON.parse(readFileSync(patchPath, "utf8"));
491writeFileSync(logPath, JSON.stringify({ args, patch }));
492await import(pathToFileURL(agentPath).href);
493`,
494 );
495 const userPatch = NodePath.join(directory, "user-patch.json");
496 yield* fs.writeFileString(userPatch, "[]");
497 const commandArgs = ["--profile", "acp", "--patch", userPatch];
498 const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({
499 search: () => Effect.die("unused search"),
500 prepare: () => Effect.die("unused prepare"),
501 refreshIndex: () => Effect.succeed(false),
502 invalidateIndex: () => Effect.void,
503 inspect: () => Effect.die("unused inspect"),
504 uninstallManagedBinary: () => Effect.die("unused uninstall"),
505 resolve: () =>
506 Effect.succeed({
507 distribution: "local",
508 spawn: {
509 command: process.execPath,
510 args: [launcher, mockAgentPath, launchLog, ...commandArgs],
511 },
512 }),
513 });
514 const result = yield* probeAcpRegistryConfiguration({
515 instanceId,
516 settings: decodeSettings({ source: "local", commandPath: "dsh", commandArgs }),
517 cwd: directory,
518 environment: process.env,
519 }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog));
520 expect(result.probe.ready).toBe(true);
521 expect(result.probe.models.length).toBeGreaterThan(0);
522
523 const { args, patch } = JSON.parse(yield* fs.readFileString(launchLog));
524 expect(args).toEqual([...commandArgs, "--patch", expect.any(String)]);
525 const probeDirectory = NodePath.dirname(args.at(-1));
526 expect(patch).toEqual([
527 {
528 id: "session-persistence-jsonl",
529 config: { root: NodePath.join(probeDirectory, "sessions") },
530 },
531 { id: "session-projection-cache", disabled: true },
532 ]);
533 expect(yield* fs.exists(probeDirectory)).toBe(false);
534 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
535 );
536
537 it.live.each([
538 { model: "default", omitModelOptions: false, customModels: [], writes: 0 },
539 { model: "composer-2", omitModelOptions: false, customModels: [], writes: 1 },
540 { model: "retired-model", omitModelOptions: false, customModels: [], writes: 0 },
541 { model: "composer-2", omitModelOptions: true, customModels: [], writes: 0 },
542 { model: "custom-model", omitModelOptions: false, customModels: ["custom-model"], writes: 1 },
543 ])(
544 "generates text and deletes its session with $model and omitted options $omitModelOptions",
545 ({ model, omitModelOptions, customModels, writes }) =>
546 Effect.gen(function* () {
547 const fs = yield* FileSystem.FileSystem;
548 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "acp-title-" });
549 const requestLogPath = NodePath.join(directory, "requests.ndjson");
550 let failResolution = false;
551 const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({
552 search: () => Effect.die("unused search"),
553 prepare: () => Effect.die("unused prepare"),
554 refreshIndex: () => Effect.succeed(false),
555 invalidateIndex: () => Effect.void,
556 inspect: () => Effect.die("unused inspect"),
557 uninstallManagedBinary: () => Effect.die("unused uninstall"),
558 resolve: () =>
559 failResolution
560 ? Effect.fail(
561 new AcpRegistrySupport.AcpRegistryError({
562 reason: "runner_unavailable",
563 detail: "private provider failure",
564 }),
565 )
566 : Effect.succeed({
567 distribution: "local" as const,
568 spawn: {
569 command: "node",
570 args: [mockAgentPath],
571 env: {
572 ...process.env,
573 T3_ACP_SESSION_LIFECYCLE: "1",
574 T3_ACP_V2_MANAGEMENT: "1",
575 T3_ACP_REQUEST_LOG_PATH: requestLogPath,
576 T3_ACP_PROMPT_RESPONSE_TEXT: '{"title":"Migrate Sessions to Postgres"}',
577 T3_ACP_OMIT_MODEL_OPTIONS: omitModelOptions ? "1" : "0",
578 },
579 },
580 }),
581 });
582 const textGeneration = yield* makeAcpRegistryTextGeneration({
583 instanceId,
584 settings: decodeSettings({ agentId: "mock-agent", customModels }),
585 environment: process.env,
586 }).pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog));
587
588 const result = yield* textGeneration.generateThreadTitle({
589 cwd: process.cwd(),
590 message: "Move session storage from Redis to Postgres",
591 modelSelection: { instanceId, model },
592 });
593
594 expect(result.title).toBe("Migrate Sessions to Postgres");
595 failResolution = true;
596 const failure = yield* textGeneration
597 .generateThreadTitle({
598 cwd: process.cwd(),
599 message: "Generate a title",
600 modelSelection: { instanceId, model: "default" },
601 })
602 .pipe(Effect.result);
603 expect(failure).toMatchObject({
604 _tag: "Failure",
605 failure: { detail: "The ACP text generation request failed." },
606 });
607 const requests = (yield* fs.readFileString(requestLogPath))
608 .split("\n")
609 .filter((line) => line.length > 0)
610 .map((line) => JSON.parse(line));
611 expect(
612 requests.filter((request) => request.method === "session/set_config_option"),
613 ).toHaveLength(writes);
614 expect(requests.filter((request) => request.method === "session/set_model")).toHaveLength(
615 0,
616 );
617 expect(requests.filter((request) => request.method === "session/delete")).toEqual([
618 expect.objectContaining({ params: { sessionId: "mock-session-1" } }),
619 ]);
620 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
621 );
622
623 it("distinguishes authentication failures from generic probe failures", () => {
624 const advertised = normalizeAcpRegistryAuthMethods([
625 { id: "grok-login", name: "Log in with Grok" },
626 ]);
627 const cause = new EffectAcpErrors.AcpRequestError({
628 code: -32000,
629 errorMessage: "login required",
630 });
631 const authFailure = acpRegistryProbeFailure(cause, advertised);
632 expect(authFailure.reason).toBe("authentication_failed");
633 expect(authFailure.message).toBe("The ACP agent could not complete authentication.");
634 expect(authFailure.cause).toBe(cause);
635 expect(authFailure.authMethods).toEqual([
636 {
637 id: "grok-login",
638 name: "Log in with Grok",
639 description: null,
640 type: "agent",
641 },
642 ]);
643 expect(
644 acpRegistryProbeFailure(
645 new EffectAcpErrors.AcpTransportError({
646 detail: "Authentication required",
647 cause: "credentials missing",
648 }),
649 ).reason,
650 ).toBe("authentication_failed");
651 const genericCause = new EffectAcpErrors.AcpTransportError({
652 detail: "connection closed",
653 cause: "closed",
654 });
655 const genericFailure = acpRegistryProbeFailure(genericCause);
656 expect(genericFailure.reason).toBe("probe_failed");
657 expect(genericFailure.message).toBe("The ACP agent could not create a test session.");
658 expect(genericFailure.cause).toBe(genericCause);
659 expect(
660 acpRegistryProbeFailure(
661 new EffectAcpErrors.AcpTransportError({
662 detail: "Failed while logging request",
663 cause: "logging failed",
664 }),
665 ).reason,
666 ).toBe("probe_failed");
667 });
668});