@agentrq/acp-gateway 0.2.24 → 0.2.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -37,7 +37,7 @@ npm install -g @agentrq/acp-gateway
37
37
 
38
38
  ## Current Version
39
39
 
40
- `0.2.24`
40
+ `0.2.25`
41
41
 
42
42
  ## Usage
43
43
 
@@ -172,6 +172,8 @@ Credentials are never stored by the gateway; the agent keeps its own, exactly as
172
172
 
173
173
  `acp-gateway` searches for `.mcp.json` starting in the current working directory and up to 3 parent directories.
174
174
 
175
+ `--list-models`, `--agent-info` and `--list-auth-methods` only ask the agent about itself, so they do not need a workspace: they skip the search and run without a `.mcp.json`. They still read a config named with `--mcp-json`.
176
+
175
177
  `--mcp-json <path>` names a config directly, wherever it lives and whatever it is called. It is read *as well as* whatever the search finds, with the named file winning any name collision — so a gateway started from somewhere other than its workspace still connects to the right one.
176
178
 
177
179
  Example `.mcp.json`:
@@ -1,10 +1,10 @@
1
1
  import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
2
- import { mkdtempSync, writeFileSync } from "node:fs";
2
+ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { EventEmitter } from "node:events";
6
6
  import * as acp from "@agentclientprotocol/sdk";
7
- import { createAcpSessionSwitcher, fetchNextTask, startPendingTask, drainPendingTasks, createSelfFillingTaskQueue, MAX_SKIPPED_FETCHES, freeSlots, resetPendingTaskDrain, mapMcpServers, TaskQueue, createTaskQueue, resetConcurrencyReports, getOrCreateSession, openIdleSession, resetIdleSession, activeSessions, AuthenticationFailed, IDLE_SESSION_KEY, loginCommandFor, authConfig, modelConfig, createSessionWithAuth, isInteractiveTerminal, openAgentConnection, parseGatewayArgs, assertAgentRunnable, helpText, isRunnable, resolveOnPath, spawnTarget, needsShell, escapeCmdCommand, quoteForCmd, spawnArgsFor, terminateAgentProcess, printHelp, resolveAgentCommand, runListAgents, pickHumanApprovalMode, enforceHumanApprovalMode, handleAgentModeChange, runAgentCommand, findActiveSession, handleTaskCancellation, handleSetModel, handleSetConcurrency, runTurnForTask, resetTaskTurns, registerConcurrencyListeners, reportConcurrency, applyModelSelection, cancelledTaskSeq, markTaskCancelled, isTaskCancelled, nextTaskSeq, supportsCloseSession, closeSession, closeAllSessions, setupSignalHandlers, } from "../index.js";
7
+ import { createAcpSessionSwitcher, fetchNextTask, startPendingTask, drainPendingTasks, createSelfFillingTaskQueue, MAX_SKIPPED_FETCHES, IDLE_TASK_POLL_INTERVAL_MS, freeSlots, resetPendingTaskDrain, mapMcpServers, TaskQueue, createTaskQueue, resetConcurrencyReports, getOrCreateSession, openIdleSession, resetIdleSession, activeSessions, AuthenticationFailed, IDLE_SESSION_KEY, loginCommandFor, authConfig, modelConfig, createSessionWithAuth, isInteractiveTerminal, openAgentConnection, parseGatewayArgs, assertAgentRunnable, helpText, isRunnable, resolveOnPath, spawnTarget, needsShell, escapeCmdCommand, quoteForCmd, spawnArgsFor, terminateAgentProcess, printHelp, resolveAgentCommand, runListAgents, pickHumanApprovalMode, enforceHumanApprovalMode, handleAgentModeChange, runAgentCommand, loadWorkspace, createDetachedBridge, WORKSPACE_OPTIONAL_COMMANDS, findActiveSession, handleTaskCancellation, handleSetModel, handleSetConcurrency, runTurnForTask, resetTaskTurns, registerConcurrencyListeners, reportConcurrency, applyModelSelection, cancelledTaskSeq, markTaskCancelled, isTaskCancelled, nextTaskSeq, supportsCloseSession, closeSession, closeAllSessions, setupSignalHandlers, } from "../index.js";
8
8
  import { sendModelsNotification } from "../acpClient.js";
9
9
  import { AUTH_REQUIRED_CODE } from "../auth.js";
10
10
  /**
@@ -582,6 +582,72 @@ describe("index", () => {
582
582
  resetConcurrencyReports();
583
583
  vi.restoreAllMocks();
584
584
  });
585
+ it("keeps checking for work on an interval while idle, so a workspace with nothing at startup is not idle forever", async () => {
586
+ // Nothing ever runs in this test, so nothing frees a slot and the
587
+ // event-driven check (a task finishing) never fires. A fetch here can
588
+ // only be the idle timer.
589
+ vi.spyOn(console, "error").mockImplementation(() => { });
590
+ vi.spyOn(console, "log").mockImplementation(() => { });
591
+ resetPendingTaskDrain();
592
+ resetTaskTurns();
593
+ resetConcurrencyReports();
594
+ vi.useFakeTimers();
595
+ const bridge = {
596
+ callTool: vi.fn().mockResolvedValue({
597
+ isError: false,
598
+ content: [{ type: "text", text: "no pending tasks exist" }],
599
+ }),
600
+ sendNotification: vi.fn().mockResolvedValue(undefined),
601
+ };
602
+ createSelfFillingTaskQueue(1, bridge, {
603
+ acpCmdArgsOrConnection: [],
604
+ configsOrSessionSwitcher: [],
605
+ agentrqConfigOrAcpClient: {},
606
+ });
607
+ expect(bridge.callTool).not.toHaveBeenCalled();
608
+ await vi.advanceTimersByTimeAsync(IDLE_TASK_POLL_INTERVAL_MS);
609
+ expect(bridge.callTool).toHaveBeenCalledTimes(1);
610
+ await vi.advanceTimersByTimeAsync(IDLE_TASK_POLL_INTERVAL_MS);
611
+ expect(bridge.callTool).toHaveBeenCalledTimes(2);
612
+ vi.useRealTimers();
613
+ resetConcurrencyReports();
614
+ vi.restoreAllMocks();
615
+ });
616
+ it("skips the idle check while a task is still running", async () => {
617
+ // A running task will free its own slot and trigger the event-driven
618
+ // check when it finishes, so the idle timer firing in the meantime has
619
+ // nothing to do here.
620
+ vi.spyOn(console, "error").mockImplementation(() => { });
621
+ vi.spyOn(console, "log").mockImplementation(() => { });
622
+ resetPendingTaskDrain();
623
+ resetTaskTurns();
624
+ resetConcurrencyReports();
625
+ vi.useFakeTimers();
626
+ const bridge = {
627
+ callTool: vi.fn().mockResolvedValue({
628
+ isError: false,
629
+ content: [{ type: "text", text: "no pending tasks exist" }],
630
+ }),
631
+ sendNotification: vi.fn().mockResolvedValue(undefined),
632
+ };
633
+ const queue = createSelfFillingTaskQueue(1, bridge, {
634
+ acpCmdArgsOrConnection: [],
635
+ configsOrSessionSwitcher: [],
636
+ agentrqConfigOrAcpClient: {},
637
+ });
638
+ let release;
639
+ const held = new Promise((resolve) => {
640
+ release = resolve;
641
+ });
642
+ void queue.run(() => held);
643
+ await vi.advanceTimersByTimeAsync(IDLE_TASK_POLL_INTERVAL_MS);
644
+ expect(bridge.callTool).not.toHaveBeenCalled();
645
+ release();
646
+ await vi.advanceTimersByTimeAsync(0);
647
+ vi.useRealTimers();
648
+ resetConcurrencyReports();
649
+ vi.restoreAllMocks();
650
+ });
585
651
  });
586
652
  describe("freeSlots", () => {
587
653
  it("counts the room left, with what is waiting already spoken for", () => {
@@ -2455,6 +2521,72 @@ describe("index", () => {
2455
2521
  await expect(resolveAgentCommand(options({ agentId: "nope" }), [], fetchImpl)).rejects.toThrow(/No agent "nope" in the ACP registry/);
2456
2522
  });
2457
2523
  });
2524
+ describe("loadWorkspace", () => {
2525
+ let errorSpy;
2526
+ beforeEach(() => {
2527
+ errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
2528
+ });
2529
+ afterEach(() => {
2530
+ errorSpy.mockRestore();
2531
+ });
2532
+ /** A directory with no .mcp.json in it or in the three above it. */
2533
+ function emptyWorkspaceDir() {
2534
+ const root = mkdtempSync(join(tmpdir(), "acp-gw-noworkspace-"));
2535
+ const dir = join(root, "a", "b", "c", "d");
2536
+ mkdirSync(dir, { recursive: true });
2537
+ return dir;
2538
+ }
2539
+ function writeMcpJson(dir, name = ".mcp.json") {
2540
+ const file = join(dir, name);
2541
+ writeFileSync(file, JSON.stringify({ mcpServers: { "agentrq-ws": { type: "http", url: "http://localhost:1/mcp" } } }));
2542
+ return file;
2543
+ }
2544
+ it("should name the commands that only ask the agent about itself", () => {
2545
+ expect([...WORKSPACE_OPTIONAL_COMMANDS].sort()).toEqual(["agent-info", "list-auth-methods", "list-models"]);
2546
+ });
2547
+ it.each(["list-models", "agent-info", "list-auth-methods"])("should let --%s run without a .mcp.json", (command) => {
2548
+ const workspace = loadWorkspace(command, undefined, emptyWorkspaceDir());
2549
+ expect(workspace.configs).toEqual([]);
2550
+ expect(workspace.agentrqConfig.env).toEqual({});
2551
+ expect(workspace.mcpBridge.getSessionId()).toBeUndefined();
2552
+ });
2553
+ it("should not read a .mcp.json that is there, when the command does not need it", () => {
2554
+ const dir = emptyWorkspaceDir();
2555
+ // Broken on purpose: had it been read, this would throw.
2556
+ writeFileSync(join(dir, ".mcp.json"), "{ not json");
2557
+ expect(loadWorkspace("list-models", undefined, dir).configs).toEqual([]);
2558
+ });
2559
+ it("should still use a config named with --mcp-json", () => {
2560
+ const file = writeMcpJson(emptyWorkspaceDir(), "servers.json");
2561
+ const workspace = loadWorkspace("list-models", file, emptyWorkspaceDir());
2562
+ expect(workspace.agentrqConfig.name).toBe("agentrq-ws");
2563
+ expect(workspace.mcpBridge.getServerName()).toBe("agentrq-ws");
2564
+ });
2565
+ it("should still report a --mcp-json path that is wrong", () => {
2566
+ expect(() => loadWorkspace("list-models", "/nowhere/servers.json", emptyWorkspaceDir())).toThrow();
2567
+ });
2568
+ it.each(["run", "login", "logout"])("should still require a .mcp.json to %s", (command) => {
2569
+ expect(() => loadWorkspace(command, undefined, emptyWorkspaceDir())).toThrow("Could not find .mcp.json");
2570
+ });
2571
+ it("should connect running tasks to the workspace it finds", () => {
2572
+ const dir = emptyWorkspaceDir();
2573
+ writeMcpJson(dir);
2574
+ const workspace = loadWorkspace("run", undefined, dir);
2575
+ expect(workspace.configs.map((c) => c.name)).toEqual(["agentrq-ws"]);
2576
+ expect(workspace.mcpBridge.getServerName()).toBe("agentrq-ws");
2577
+ });
2578
+ });
2579
+ describe("createDetachedBridge", () => {
2580
+ it("should fail whatever is asked of the workspace, and close quietly", async () => {
2581
+ const bridge = createDetachedBridge();
2582
+ await expect(bridge.callTool("elicit", {})).rejects.toThrow("No agentrq workspace is configured");
2583
+ await expect(bridge.sendNotification("notifications/x", {})).rejects.toThrow("No agentrq workspace is configured");
2584
+ expect(bridge.getSessionId()).toBeUndefined();
2585
+ expect(bridge.getServerName()).toBeUndefined();
2586
+ expect(bridge.getAdvertisedTools()).toBeUndefined();
2587
+ await expect(bridge.close()).resolves.toBeUndefined();
2588
+ });
2589
+ });
2458
2590
  describe("runAgentCommand", () => {
2459
2591
  const agentrqConfig = { env: {} };
2460
2592
  let logSpy;
@@ -2510,6 +2642,25 @@ describe("index", () => {
2510
2642
  expect(printed).toContain("Claude 3.7 Sonnet");
2511
2643
  expect(spawnedAgents[0].kill).toHaveBeenCalled();
2512
2644
  });
2645
+ it("should list models with no workspace behind it", async () => {
2646
+ mockConnection({
2647
+ newSession: vi.fn().mockResolvedValue({
2648
+ sessionId: "m-sess",
2649
+ configOptions: [
2650
+ {
2651
+ id: "model",
2652
+ name: "Model",
2653
+ type: "select",
2654
+ currentValue: "gemini-pro",
2655
+ options: [{ value: "gemini-pro", name: "Gemini Pro" }],
2656
+ },
2657
+ ],
2658
+ }),
2659
+ });
2660
+ await runAgentCommand("list-models", ["gemini", "--acp"], { name: "none", type: "http", env: {} }, createDetachedBridge());
2661
+ expect(logSpy.mock.calls.flat().join("\n")).toContain("gemini-pro");
2662
+ expect(spawnedAgents[0].kill).toHaveBeenCalled();
2663
+ });
2513
2664
  it("should print models as a single JSON line when asked for JSON", async () => {
2514
2665
  mockConnection({
2515
2666
  newSession: vi.fn().mockResolvedValue({