@agentrq/acp-gateway 0.2.34 → 0.3.0

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.34`
40
+ `0.3.0`
41
41
 
42
42
  ## Usage
43
43
 
@@ -74,6 +74,8 @@ You can specify gateway options before the `--` separator:
74
74
  - `--list-auth-methods`: Prints the login methods the agent advertises, then exits.
75
75
  - `--login [method-id]`: Logs in to the agent, then exits.
76
76
  - `--logout`: Ends the agent's authenticated state, then exits (only for agents that support logout).
77
+ - `--acp-version <1|2>`: Native mode. AgentRQ speaks ACP itself, and the gateway only pipes the agent's stdio to it (see [Native Mode](#native-mode-agentrq-speaks-acp)).
78
+ - `--acp-url <url>`: The native endpoint, for a deployment where it cannot be worked out from `.mcp.json`.
77
79
 
78
80
  Example:
79
81
  ```bash
@@ -256,6 +258,39 @@ The limit lives in memory. It survives MCP reconnects but not a gateway restart,
256
258
  number means. Nothing reports a flag back to the person who typed it, so unlike the workspace's path the
257
259
  gateway says out loud on startup when a flag value was capped or could not be read.
258
260
 
261
+ ### Native Mode (AgentRQ Speaks ACP)
262
+
263
+ ```bash
264
+ acp-gateway --acp-version 1 --agent codex-acp
265
+ acp-gateway --acp-version 1 -- your-acp-agent --flag1
266
+ ```
267
+
268
+ With `--acp-version`, AgentRQ is the ACP client and the gateway no longer translates anything. It starts the
269
+ agent exactly as it would otherwise (a registry id or the command after `--`) and moves bytes: each line the
270
+ agent writes becomes one WebSocket text frame to AgentRQ, and each frame AgentRQ sends becomes one line on the
271
+ agent's stdin. It never parses the ACP messages in between.
272
+
273
+ - **Where it connects.** `.mcp.json` is still where the workspace comes from. The endpoint is the AgentRQ
274
+ server's own origin with the path `/api/acp/v1` (or `/api/acp/v2`), over `wss://` for an `https://` server
275
+ and `ws://` for `http://`. The workspace token is the URL's `?token=` or the entry's `Authorization: Bearer`
276
+ header. `--acp-url` names the endpoint outright.
277
+ - **Before connecting** it sends a plain `GET` with the token, so a problem is named rather than retried for ever:
278
+ an old server without the endpoint (404), a bad token (401/403, with the server's reason), or a proxy that does
279
+ not pass `Upgrade` for `/api/acp/`. Each of these exits 1.
280
+ - **Options travel as headers.** `--agent`, `--model`, `--max-concurrency`, `--permission-timeout` and
281
+ `--auth-method` reach AgentRQ in the WebSocket handshake, along with the working directory every session runs in.
282
+ - **Dropped connections resume.** The gateway reconnects with backoff (1 s doubling to 60 s), and AgentRQ keeps
283
+ the connection for two minutes. Within that time nothing is lost or repeated: each side replays what the other
284
+ had not acknowledged, up to 1,024 frames or 8 MiB. Past it, the agent is restarted and starts over.
285
+ - **A dead agent is restarted** after 2 s, doubling to a minute. After five exits within five minutes the gateway
286
+ gives up and exits 1 with the agent's last output.
287
+ - **Errors that a retry cannot fix** (an agent that speaks a different ACP version, a login that needs a terminal)
288
+ are printed and exit 1.
289
+ - `--login`, `--logout`, `--list-models`, `--list-auth-methods` and `--agent-info` ignore the flag: they still talk
290
+ to the agent locally, as before.
291
+ - Native mode needs **Node 22 or newer**. Without `--acp-version`, the gateway behaves exactly as before, on Node 20
292
+ too.
293
+
259
294
  ## How It Works
260
295
 
261
296
  ```
@@ -306,6 +341,8 @@ gateway says out loud on startup when a flag value was capped or could not be re
306
341
  | `src/registry.ts` | Reads the ACP registry index — agent lookup, host platform matching, and package launch commands. |
307
342
  | `src/agentInstall.ts` | Downloads, verifies, unpacks and caches a registry agent's binary distribution. |
308
343
  | `src/progress.ts` | Draws the single-line download progress bar, on a terminal and nowhere else. |
344
+ | `src/native.ts` | Native mode: runs the agent and pipes its stdio to AgentRQ's WebSocket, with resume, reconnect and respawn. |
345
+ | `src/nativeFrames.ts` | Native mode's pure parts: line splitting, control frames, the replay ring, the endpoint and headers. |
309
346
 
310
347
  ## Development
311
348
 
@@ -333,6 +370,8 @@ acp-gateway/
333
370
  │ ├── config.ts # .mcp.json loader
334
371
  │ ├── index.ts # Entry point & orchestrator
335
372
  │ ├── mcpClient.ts # MCP Bridge with auto-reconnect
373
+ │ ├── native.ts # Native mode byte bridge (--acp-version)
374
+ │ ├── nativeFrames.ts # Native mode frames, replay ring, headers
336
375
  │ ├── progress.ts # Download progress bar
337
376
  │ ├── registry.ts # ACP registry index client
338
377
  │ ├── telemetry.ts # Thought / plan / usage rendering
@@ -5,7 +5,7 @@ import { tmpdir } from "node:os";
5
5
  import { join } from "node:path";
6
6
  import { EventEmitter } from "node:events";
7
7
  import * as acp from "@agentclientprotocol/sdk";
8
- 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, agentExitFailed, showAgentStderr, shouldPrintBanner, parseGatewayArgs, assertAgentRunnable, helpText, isRunnable, resolveOnPath, spawnTarget, needsShell, escapeCmdCommand, quoteForCmd, spawnArgsFor, terminateAgentProcess, printHelp, resolveAgentCommand, runListAgents, pickHumanApprovalMode, enforceHumanApprovalMode, handleAgentModeChange, runAgentCommand, loadWorkspace, createDetachedBridge, makeIsolatedDir, WORKSPACE_OPTIONAL_COMMANDS, findActiveSession, handleTaskCancellation, handleSetModel, handleSetConcurrency, runTurnForTask, resetTaskTurns, registerConcurrencyListeners, reportConcurrency, applyModelSelection, cancelledTaskSeq, markTaskCancelled, isTaskCancelled, nextTaskSeq, supportsCloseSession, closeSession, closeAllSessions, setupSignalHandlers, } from "../index.js";
8
+ 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, agentExitFailed, showAgentStderr, shouldPrintBanner, parseGatewayArgs, assertAgentRunnable, helpText, isRunnable, resolveOnPath, spawnTarget, needsShell, escapeCmdCommand, quoteForCmd, spawnArgsFor, terminateAgentProcess, printHelp, resolveAgentCommand, runListAgents, pickHumanApprovalMode, enforceHumanApprovalMode, handleAgentModeChange, runAgentCommand, loadWorkspace, createDetachedBridge, makeIsolatedDir, WORKSPACE_OPTIONAL_COMMANDS, findActiveSession, handleTaskCancellation, handleSetModel, handleSetConcurrency, runTurnForTask, resetTaskTurns, registerConcurrencyListeners, reportConcurrency, applyModelSelection, cancelledTaskSeq, markTaskCancelled, isTaskCancelled, nextTaskSeq, supportsCloseSession, closeSession, closeAllSessions, setupSignalHandlers, nativeOptionsFor, startNativeMode, } from "../index.js";
9
9
  import { AgentRQACPClient, sendModelsNotification } from "../acpClient.js";
10
10
  import { AUTH_REQUIRED_CODE } from "../auth.js";
11
11
  /**
@@ -2307,6 +2307,31 @@ describe("index", () => {
2307
2307
  expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("--mcp-json provided without a path"));
2308
2308
  errorSpy.mockRestore();
2309
2309
  });
2310
+ it("leaves native mode off unless --acp-version is given", () => {
2311
+ const options = parseGatewayArgs(["--agent", "gemini"]);
2312
+ expect(options.acpVersion).toBeUndefined();
2313
+ expect(options.acpUrl).toBeUndefined();
2314
+ });
2315
+ it.each([["1", 1], ["2", 2]])("reads --acp-version %s", (value, version) => {
2316
+ expect(parseGatewayArgs(["--acp-version", value, "--acp-url", "wss://x/api/acp/v1", "gemini"])).toMatchObject({ acpVersion: version, acpUrl: "wss://x/api/acp/v1", rest: ["gemini"] });
2317
+ });
2318
+ it.each([["3"], ["v1"], [undefined]])("refuses --acp-version %s", (value) => {
2319
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
2320
+ const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {
2321
+ throw new Error("exit");
2322
+ }));
2323
+ expect(() => parseGatewayArgs(value ? ["--acp-version", value] : ["--acp-version"])).toThrow("exit");
2324
+ expect(errorSpy).toHaveBeenCalledWith("[acp-gateway] --acp-version must be 1 or 2");
2325
+ expect(exitSpy).toHaveBeenCalledWith(1);
2326
+ errorSpy.mockRestore();
2327
+ exitSpy.mockRestore();
2328
+ });
2329
+ it("says so when --acp-url is given no URL", () => {
2330
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
2331
+ expect(parseGatewayArgs(["--acp-url"]).acpUrl).toBeUndefined();
2332
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("--acp-url provided without a URL"));
2333
+ errorSpy.mockRestore();
2334
+ });
2310
2335
  it("should recognise model options", () => {
2311
2336
  expect(parseGatewayArgs(["--list-models"])).toMatchObject({ command: "list-models" });
2312
2337
  expect(parseGatewayArgs(["--model", "claude-3-7-sonnet"])).toMatchObject({
@@ -2563,6 +2588,108 @@ describe("index", () => {
2563
2588
  agents: [{ id: "gemini", name: "Gemini CLI", runtimes: ["npx"] }],
2564
2589
  });
2565
2590
  });
2591
+ it("marks agents installing without a checksum with unverified: true in JSON output and omits the field otherwise", async () => {
2592
+ const fullRegistry = {
2593
+ version: "1.0.0",
2594
+ agents: [
2595
+ {
2596
+ id: "crow-cli",
2597
+ name: "crow-cli",
2598
+ version: "1.0.0",
2599
+ description: "Binary agent without checksum",
2600
+ distribution: {
2601
+ binary: {
2602
+ "darwin-aarch64": {
2603
+ archive: "https://example.com/crow.tar.gz",
2604
+ cmd: "./crow",
2605
+ },
2606
+ },
2607
+ },
2608
+ },
2609
+ {
2610
+ id: "opencode",
2611
+ name: "OpenCode",
2612
+ version: "1.0.0",
2613
+ description: "Binary agent with checksum",
2614
+ distribution: {
2615
+ binary: {
2616
+ "darwin-aarch64": {
2617
+ archive: "https://example.com/opencode.tar.gz",
2618
+ sha256: "a".repeat(64),
2619
+ cmd: "./opencode",
2620
+ },
2621
+ },
2622
+ },
2623
+ },
2624
+ {
2625
+ id: "gemini",
2626
+ name: "Gemini CLI",
2627
+ version: "0.58.0",
2628
+ description: "npx agent",
2629
+ distribution: { npx: { package: "@google/gemini-cli" } },
2630
+ },
2631
+ {
2632
+ id: "fast-agent",
2633
+ name: "fast-agent",
2634
+ version: "1.0.0",
2635
+ description: "uvx agent",
2636
+ distribution: { uvx: { package: "fast-agent" } },
2637
+ },
2638
+ {
2639
+ id: "hybrid",
2640
+ name: "Hybrid",
2641
+ version: "1.0.0",
2642
+ description: "npx and binary agent without checksum",
2643
+ distribution: {
2644
+ npx: { package: "hybrid-cli" },
2645
+ binary: {
2646
+ "darwin-aarch64": {
2647
+ archive: "https://example.com/hybrid.tar.gz",
2648
+ cmd: "./hybrid",
2649
+ },
2650
+ },
2651
+ },
2652
+ },
2653
+ {
2654
+ id: "linux-only",
2655
+ name: "Linux Only",
2656
+ version: "1.0.0",
2657
+ description: "no build for darwin",
2658
+ distribution: {
2659
+ binary: {
2660
+ "linux-x86_64": {
2661
+ archive: "https://example.com/linux.tar.gz",
2662
+ cmd: "./linux",
2663
+ },
2664
+ },
2665
+ },
2666
+ },
2667
+ ],
2668
+ };
2669
+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => { });
2670
+ const fetchImpl = vi.fn().mockResolvedValue({ ok: true, json: async () => fullRegistry });
2671
+ await runListAgents(undefined, fetchImpl, true, "darwin-aarch64");
2672
+ const calls = logSpy.mock.calls;
2673
+ logSpy.mockRestore();
2674
+ expect(calls).toHaveLength(1);
2675
+ const parsed = JSON.parse(calls[0][0]);
2676
+ expect(parsed).toEqual({
2677
+ agents: [
2678
+ { id: "crow-cli", name: "crow-cli", runtimes: ["binary"], unverified: true },
2679
+ { id: "opencode", name: "OpenCode", runtimes: ["binary"] },
2680
+ { id: "gemini", name: "Gemini CLI", runtimes: ["npx"] },
2681
+ { id: "fast-agent", name: "fast-agent", runtimes: ["uvx"] },
2682
+ { id: "hybrid", name: "Hybrid", runtimes: ["npx", "binary"] },
2683
+ { id: "linux-only", name: "Linux Only", runtimes: [] },
2684
+ ],
2685
+ });
2686
+ expect(parsed.agents[0]).toHaveProperty("unverified", true);
2687
+ expect(parsed.agents[1]).not.toHaveProperty("unverified");
2688
+ expect(parsed.agents[2]).not.toHaveProperty("unverified");
2689
+ expect(parsed.agents[3]).not.toHaveProperty("unverified");
2690
+ expect(parsed.agents[4]).not.toHaveProperty("unverified");
2691
+ expect(parsed.agents[5]).not.toHaveProperty("unverified");
2692
+ });
2566
2693
  });
2567
2694
  describe("resolveAgentCommand", () => {
2568
2695
  const options = (overrides = {}) => ({
@@ -2971,6 +3098,71 @@ describe("index", () => {
2971
3098
  expect(spawnedAgents[0].kill).toHaveBeenCalled();
2972
3099
  });
2973
3100
  });
3101
+ describe("nativeOptionsFor", () => {
3102
+ const agentrq = {
3103
+ name: "agentrq",
3104
+ type: "http",
3105
+ url: "https://4hro0x9eslxd.mcp.agentrq.com/?token=t",
3106
+ env: { A: "1" },
3107
+ };
3108
+ it("derives the endpoint and passes every option through as a header value", () => {
3109
+ const options = parseGatewayArgs([
3110
+ "--acp-version", "1", "--agent", "codex-acp", "--model", "m", "--max-concurrency", "4",
3111
+ "--permission-timeout", "5", "--auth-method", "chatgpt",
3112
+ ]);
3113
+ expect(nativeOptionsFor(options, ["npx", "codex-acp"], agentrq, "/work")).toEqual({
3114
+ version: 1,
3115
+ acpCmdArgs: ["npx", "codex-acp"],
3116
+ env: { A: "1" },
3117
+ endpoint: "wss://4hro0x9eslxd.mcp.agentrq.com/api/acp/v1",
3118
+ token: "t",
3119
+ agentId: "codex-acp",
3120
+ modelId: "m",
3121
+ maxConcurrency: 4,
3122
+ permissionTimeoutMinutes: 5,
3123
+ authMethodId: "chatgpt",
3124
+ cwd: "/work",
3125
+ });
3126
+ });
3127
+ it("names a command-line agent by its basename and honours --acp-url", () => {
3128
+ const options = parseGatewayArgs(["--acp-version", "2", "--acp-url", "ws://other/x"]);
3129
+ const native = nativeOptionsFor(options, ["/opt/bin/gemini", "--acp"], agentrq);
3130
+ expect(native).toMatchObject({ version: 2, agentId: "gemini", endpoint: "ws://other/x", cwd: process.cwd() });
3131
+ });
3132
+ it("needs the workspace token", () => {
3133
+ const options = parseGatewayArgs(["--acp-version", "1"]);
3134
+ expect(nativeOptionsFor(options, ["a"], { ...agentrq, url: "https://h/" })).toBe("native mode needs the workspace token from .mcp.json");
3135
+ });
3136
+ it("needs a URL, from .mcp.json or --acp-url", () => {
3137
+ const options = parseGatewayArgs(["--acp-version", "1"]);
3138
+ expect(nativeOptionsFor(options, ["a"], { name: "x", type: "http", headers: { Authorization: "Bearer t" } })).toMatch(/needs the AgentRQ URL/);
3139
+ });
3140
+ it("explains a URL it cannot read", () => {
3141
+ const options = parseGatewayArgs(["--acp-version", "1"]);
3142
+ expect(nativeOptionsFor(options, ["a"], { name: "x", type: "http", url: "not a url", headers: { Authorization: "Bearer t" } })).toMatch(/cannot work out the AgentRQ endpoint from "not a url"; pass --acp-url/);
3143
+ });
3144
+ it("starts native mode with those options", async () => {
3145
+ const run = vi.fn(async () => { });
3146
+ const exit = vi.fn();
3147
+ await startNativeMode(parseGatewayArgs(["--acp-version", "1"]), ["a"], agentrq, run, exit);
3148
+ expect(run).toHaveBeenCalledWith(expect.objectContaining({ endpoint: "wss://4hro0x9eslxd.mcp.agentrq.com/api/acp/v1", token: "t" }));
3149
+ expect(exit).not.toHaveBeenCalled();
3150
+ });
3151
+ it("says why native mode cannot start and exits 1", async () => {
3152
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
3153
+ const run = vi.fn(async () => { });
3154
+ const exit = vi.fn();
3155
+ await startNativeMode(parseGatewayArgs(["--acp-version", "1"]), ["a"], { name: "x", type: "http", url: "https://h/" }, run, exit);
3156
+ expect(errorSpy).toHaveBeenCalledWith("[acp-gateway] native mode needs the workspace token from .mcp.json");
3157
+ expect(exit).toHaveBeenCalledWith(1);
3158
+ expect(run).not.toHaveBeenCalled();
3159
+ errorSpy.mockRestore();
3160
+ });
3161
+ it("defaults to version 1 when called without one", () => {
3162
+ const options = parseGatewayArgs([]);
3163
+ expect(nativeOptionsFor(options, [], agentrq)).toMatchObject({ version: 1, agentId: "" });
3164
+ });
3165
+ });
2974
3166
  describe("helpText", () => {
2975
3167
  it("should explain every option the parser accepts", () => {
2976
3168
  const text = helpText("9.9.9");
@@ -2993,6 +3185,8 @@ describe("index", () => {
2993
3185
  "--max-concurrency",
2994
3186
  "--permission-timeout",
2995
3187
  "--mcp-json",
3188
+ "--acp-version",
3189
+ "--acp-url",
2996
3190
  "--verbose",
2997
3191
  "--help",
2998
3192
  ]));