@agentrq/acp-gateway 0.2.13 → 0.2.15

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.
@@ -4,7 +4,7 @@ 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, checkForNextTask, mapMcpServers, TaskQueue, getOrCreateSession, activeSessions, 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, cancelledTaskSeq, markTaskCancelled, isTaskCancelled, nextTaskSeq, supportsCloseSession, closeSession, closeAllSessions, setupSignalHandlers, } from "../index.js";
7
+ import { createAcpSessionSwitcher, checkForNextTask, mapMcpServers, TaskQueue, 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, cancelledTaskSeq, markTaskCancelled, isTaskCancelled, nextTaskSeq, supportsCloseSession, closeSession, closeAllSessions, setupSignalHandlers, } from "../index.js";
8
8
  import { AUTH_REQUIRED_CODE } from "../auth.js";
9
9
  /**
10
10
  * A stand-in for the workspace bridge.
@@ -34,6 +34,12 @@ vi.mock("node:child_process", async () => {
34
34
  }),
35
35
  };
36
36
  });
37
+ /** Lets a test make the next `session/new` fail, e.g. with auth_required. */
38
+ const { newSessionError, newSessionHangs } = vi.hoisted(() => ({
39
+ newSessionError: { value: null },
40
+ /** Lets a test make `session/new` never answer, like an agent gone quiet. */
41
+ newSessionHangs: { value: false },
42
+ }));
37
43
  vi.mock("@agentclientprotocol/sdk", async () => {
38
44
  const actual = await vi.importActual("@agentclientprotocol/sdk");
39
45
  return {
@@ -41,7 +47,13 @@ vi.mock("@agentclientprotocol/sdk", async () => {
41
47
  ClientSideConnection: vi.fn().mockImplementation(function () {
42
48
  return {
43
49
  initialize: vi.fn().mockResolvedValue({ protocolVersion: "0.1.0" }),
44
- newSession: vi.fn().mockResolvedValue({ sessionId: "test-sess-123" }),
50
+ newSession: vi.fn().mockImplementation(async () => {
51
+ if (newSessionHangs.value)
52
+ return new Promise(() => { });
53
+ if (newSessionError.value)
54
+ throw newSessionError.value;
55
+ return { sessionId: "test-sess-123" };
56
+ }),
45
57
  prompt: vi.fn().mockResolvedValue({ stopReason: "complete" }),
46
58
  };
47
59
  }),
@@ -395,6 +407,9 @@ describe("index", () => {
395
407
  describe("getOrCreateSession", () => {
396
408
  beforeEach(() => {
397
409
  activeSessions.clear();
410
+ resetIdleSession();
411
+ newSessionError.value = null;
412
+ newSessionHangs.value = false;
398
413
  });
399
414
  it("should spawn a new session when not cached", async () => {
400
415
  const mockBridge = fakeBridge();
@@ -405,6 +420,138 @@ describe("index", () => {
405
420
  expect(session.sessionId).toBe("test-sess-123");
406
421
  expect(activeSessions.has("T-New")).toBe(true);
407
422
  });
423
+ it("files a session opened with no task under the idle key", async () => {
424
+ // This is the session the gateway opens at startup so a workspace can say
425
+ // what its agent offers before any work arrives.
426
+ const mockBridge = fakeBridge();
427
+ const session = await getOrCreateSession(undefined, ["node", "agent.js"], [], { env: {} }, mockBridge);
428
+ expect(session).toBeDefined();
429
+ expect(activeSessions.has(IDLE_SESSION_KEY)).toBe(true);
430
+ });
431
+ it("hands the startup session to the first task rather than opening a second", async () => {
432
+ // Sessions are keyed by task, so without this the first real task would
433
+ // spawn a second agent alongside the one already running.
434
+ const mockBridge = fakeBridge();
435
+ const idle = await getOrCreateSession(undefined, ["node", "agent.js"], [], { env: {} }, mockBridge);
436
+ const forTask = await getOrCreateSession("T-First", ["node", "agent.js"], [], { env: {} }, mockBridge);
437
+ expect(forTask).toBe(idle);
438
+ expect(activeSessions.has("T-First")).toBe(true);
439
+ expect(activeSessions.has(IDLE_SESSION_KEY)).toBe(false);
440
+ expect(activeSessions.size).toBe(1);
441
+ });
442
+ it("attributes what an adopted session reports to the task that took it", async () => {
443
+ // Everything the session says afterwards — models, commands, replies —
444
+ // belongs to that task, so the task id has to follow the adoption.
445
+ const mockBridge = fakeBridge();
446
+ const idle = await getOrCreateSession(undefined, ["node", "agent.js"], [], { env: {} }, mockBridge);
447
+ mockBridge.sendNotification.mockClear();
448
+ await getOrCreateSession("T-Owner", ["node", "agent.js"], [], { env: {} }, mockBridge);
449
+ await idle.acpClient.sendCommandsToWorkspace(idle.sessionId, [{ name: "init", description: "d" }]);
450
+ expect(mockBridge.sendNotification).toHaveBeenCalledWith("notifications/claude/channel/commands", expect.objectContaining({ task_id: "T-Owner" }));
451
+ });
452
+ it("gives a second task its own session, having only one to hand over", async () => {
453
+ const mockBridge = fakeBridge();
454
+ await getOrCreateSession(undefined, ["node", "agent.js"], [], { env: {} }, mockBridge);
455
+ const first = await getOrCreateSession("T-A", ["node", "agent.js"], [], { env: {} }, mockBridge);
456
+ const second = await getOrCreateSession("T-B", ["node", "agent.js"], [], { env: {} }, mockBridge);
457
+ expect(second).not.toBe(first);
458
+ expect(activeSessions.has("T-A")).toBe(true);
459
+ expect(activeSessions.has("T-B")).toBe(true);
460
+ });
461
+ it("opens the idle session at startup", async () => {
462
+ const mockBridge = fakeBridge();
463
+ await openIdleSession(["node", "agent.js"], [], { env: {} }, mockBridge);
464
+ expect(activeSessions.has(IDLE_SESSION_KEY)).toBe(true);
465
+ });
466
+ it("never fails when the agent cannot be started", async () => {
467
+ // The safety property of the whole change: a broken agent used to fail
468
+ // when the first task arrived, and it still must. Failing at startup
469
+ // would turn it into a gateway that will not run at all.
470
+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => { });
471
+ const mockBridge = fakeBridge();
472
+ newSessionError.value = new Error("agent will not start");
473
+ // Survivable: it says the gateway can carry on, and the first task retries.
474
+ await expect(openIdleSession(["node", "agent.js"], [], { env: {} }, mockBridge)).resolves.toBe("unknown");
475
+ expect(activeSessions.has(IDLE_SESSION_KEY)).toBe(false);
476
+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("the first task will start one"), expect.anything());
477
+ consoleSpy.mockRestore();
478
+ });
479
+ it("reports that the gateway cannot continue when the agent is unauthenticated", async () => {
480
+ // Carrying on would leave the workspace showing a live agent that fails
481
+ // every task it is given, which is worse than not running at all.
482
+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => { });
483
+ const mockBridge = fakeBridge();
484
+ newSessionError.value = { code: -32000, data: { authRequired: true }, message: "auth_required" };
485
+ const outcome = await openIdleSession(["node", "agent.js"], [], { env: {} }, mockBridge);
486
+ expect(outcome).toBe("unauthenticated");
487
+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("until it is authenticated"));
488
+ expect(activeSessions.has(IDLE_SESSION_KEY)).toBe(false);
489
+ // Nothing was claimed about an agent that never started.
490
+ expect(mockBridge.sendNotification).not.toHaveBeenCalledWith("notifications/claude/channel/models", expect.anything());
491
+ consoleSpy.mockRestore();
492
+ });
493
+ it("shuts down when the login itself went wrong", async () => {
494
+ // A terminal login the human abandoned, a login subcommand exiting
495
+ // non-zero, no usable method on a headless run: all of them come back as
496
+ // AuthenticationFailed, so none of them has to be recognised by its
497
+ // message. The conclusion is the same — an agent that cannot authenticate
498
+ // cannot work.
499
+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => { });
500
+ const mockBridge = fakeBridge();
501
+ newSessionError.value = new AuthenticationFailed(new Error('Terminal login "oauth" failed (code=1, signal=null).'));
502
+ const outcome = await openIdleSession(["node", "agent.js"], [], { env: {} }, mockBridge);
503
+ expect(outcome).toBe("unauthenticated");
504
+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("npx @agentrq/acp-gateway@latest --login"));
505
+ consoleSpy.mockRestore();
506
+ });
507
+ it("tells the owner of an API-key agent to set the key, not to log in", async () => {
508
+ // Plenty of agents never ask anyone to log in — they read a key from the
509
+ // environment. When one of those refuses, sending its owner looking for a
510
+ // login prompt that does not exist is worse than saying nothing.
511
+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => { });
512
+ const mockBridge = fakeBridge();
513
+ newSessionError.value = new AuthenticationFailed(new Error("auth_required"), false);
514
+ const outcome = await openIdleSession(["node", "agent.js"], [], { env: {} }, mockBridge);
515
+ expect(outcome).toBe("unauthenticated");
516
+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("expecting a credential of its own"));
517
+ expect(consoleSpy).not.toHaveBeenCalledWith(expect.stringContaining("--login"));
518
+ consoleSpy.mockRestore();
519
+ });
520
+ it("gives up waiting on an agent that never opens a session", async () => {
521
+ // Nothing reaches the workspace until this settles, so an agent that
522
+ // spawns and then goes quiet would otherwise take the whole gateway with
523
+ // it — a worse failure than the one the startup session fixes.
524
+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => { });
525
+ const mockBridge = fakeBridge();
526
+ newSessionHangs.value = true;
527
+ const outcome = await openIdleSession(["node", "agent.js"], [], { env: {} }, mockBridge, loginCommandFor("some-agent"), 20);
528
+ expect(outcome).toBe("unknown");
529
+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("has not opened a session"));
530
+ consoleSpy.mockRestore();
531
+ });
532
+ it("keeps running when the agent merely failed to start", async () => {
533
+ // Not the same thing at all: that may have been a race, it used to fail
534
+ // when the first task arrived, and it still should.
535
+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => { });
536
+ const mockBridge = fakeBridge();
537
+ newSessionError.value = new Error("spawn ENOENT");
538
+ const outcome = await openIdleSession(["node", "agent.js"], [], { env: {} }, mockBridge);
539
+ // Survivable, so the gateway keeps running.
540
+ expect(outcome).toBe("unknown");
541
+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("the first task will start one"), expect.anything());
542
+ consoleSpy.mockRestore();
543
+ });
544
+ it("makes a task wait for a startup session still coming up, rather than starting a second agent", async () => {
545
+ // Opening one can take a long time when an agent wants a human to log in,
546
+ // and a task arriving in that window used to find nothing cached.
547
+ const mockBridge = fakeBridge();
548
+ const startup = openIdleSession(["node", "agent.js"], [], { env: {} }, mockBridge);
549
+ const forTask = getOrCreateSession("T-Racer", ["node", "agent.js"], [], { env: {} }, mockBridge);
550
+ await startup;
551
+ const session = await forTask;
552
+ expect(activeSessions.size).toBe(1);
553
+ expect(activeSessions.get("T-Racer")).toBe(session);
554
+ });
408
555
  it("should return cached session when already created", async () => {
409
556
  const mockBridge = fakeBridge();
410
557
  const configs = [];
@@ -849,6 +996,20 @@ describe("index", () => {
849
996
  // gets its own: two backslashes and a quote need five and a quote.
850
997
  expect(quoteForCmd('a\\\\"b')).toBe('^"a\\\\\\\\\\^"b^"');
851
998
  });
999
+ it("stays fast on a long run of backslashes", () => {
1000
+ // The two regexes this replaced asked for a run of backslashes followed
1001
+ // by a quote, so a long run with no quote after it was re-tried from
1002
+ // every position in the run. 50k backslashes took long enough to matter;
1003
+ // counting the run once does not care.
1004
+ const run = "\\".repeat(50_000);
1005
+ const started = Date.now();
1006
+ const quoted = quoteForCmd(run);
1007
+ const elapsed = Date.now() - started;
1008
+ // Untouched, because nothing follows them but the closing quote — which
1009
+ // is exactly the case that doubles them.
1010
+ expect(quoted).toBe(`^"${"\\".repeat(100_000)}^"`);
1011
+ expect(elapsed).toBeLessThan(1_000);
1012
+ });
852
1013
  });
853
1014
  describe("spawnArgsFor", () => {
854
1015
  it("passes the command through when no shell is involved", () => {
@@ -987,6 +1148,35 @@ describe("index", () => {
987
1148
  expect(resolved.command.slice(1)).toEqual(["-y", "@google/gemini-cli@0.58.0", "--acp"]);
988
1149
  expect(resolved.env).toEqual({ K: "v" });
989
1150
  });
1151
+ it("reports who the registry says the agent is, before it has been started", async () => {
1152
+ // This is the only name available while the gateway is idle: the agent
1153
+ // itself does not speak until a task starts it, and until then a
1154
+ // workspace can only see the gateway.
1155
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
1156
+ const fetchImpl = vi.fn().mockResolvedValue({
1157
+ ok: true,
1158
+ json: async () => ({
1159
+ version: "1.0.0",
1160
+ agents: [
1161
+ {
1162
+ id: "antigravity-acp",
1163
+ name: "Google Antigravity",
1164
+ version: "1.1.1",
1165
+ description: "…",
1166
+ distribution: { npx: { package: "antigravity-acp@1.1.1", args: [] } },
1167
+ },
1168
+ ],
1169
+ }),
1170
+ });
1171
+ const resolved = await resolveAgentCommand(options({ agentId: "antigravity-acp" }), [], fetchImpl);
1172
+ errorSpy.mockRestore();
1173
+ expect(resolved.identity).toEqual({ name: "Google Antigravity", version: "1.1.1" });
1174
+ });
1175
+ it("has no identity to report for a command given after --", async () => {
1176
+ // Nothing named it, so there is nothing to say until the agent does.
1177
+ const resolved = await resolveAgentCommand(options(), ["gemini", "--acp"], vi.fn());
1178
+ expect(resolved.identity).toBeUndefined();
1179
+ });
990
1180
  it("should surface a registry id that does not exist", async () => {
991
1181
  const fetchImpl = vi.fn().mockResolvedValue({
992
1182
  ok: true,
@@ -1712,4 +1902,15 @@ describe("index", () => {
1712
1902
  });
1713
1903
  });
1714
1904
  });
1905
+ describe("loginCommandFor", () => {
1906
+ it("names the agent, so nobody has to work the command out", () => {
1907
+ expect(loginCommandFor("antigravity-acp")).toBe("npx @agentrq/acp-gateway@latest --login --agent antigravity-acp");
1908
+ });
1909
+ it("repeats the command after -- when no registry id named the agent", () => {
1910
+ expect(loginCommandFor(undefined, ["node", "my-agent.js"])).toBe("npx @agentrq/acp-gateway@latest --login -- node my-agent.js");
1911
+ });
1912
+ it("falls back to the bare command when nothing identifies the agent", () => {
1913
+ expect(loginCommandFor()).toBe("npx @agentrq/acp-gateway@latest --login");
1914
+ });
1915
+ });
1715
1916
  //# sourceMappingURL=index.test.js.map