@agentrq/acp-gateway 0.2.19 → 0.2.21

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, 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, 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";
8
8
  import { sendModelsNotification } from "../acpClient.js";
9
9
  import { AUTH_REQUIRED_CODE } from "../auth.js";
10
10
  /**
@@ -253,13 +253,21 @@ describe("index", () => {
253
253
  expect(switcher.getTaskIdForSession("session-for-task-2")).toBe("task-2");
254
254
  });
255
255
  });
256
- describe("checkForNextTask", () => {
256
+ describe("running a task the workspace handed over", () => {
257
257
  let mockMcpBridge;
258
258
  let mockConnection;
259
259
  let mockSessionSwitcher;
260
260
  let mockAcpClient;
261
+ /** What the gateway's fetch-and-run path needs, with a session already open. */
262
+ const deps = (taskQueue) => ({
263
+ acpCmdArgsOrConnection: mockConnection,
264
+ configsOrSessionSwitcher: mockSessionSwitcher,
265
+ agentrqConfigOrAcpClient: mockAcpClient,
266
+ taskQueue,
267
+ });
261
268
  beforeEach(() => {
262
269
  vi.clearAllMocks();
270
+ resetPendingTaskDrain();
263
271
  mockMcpBridge = {
264
272
  callTool: vi.fn(),
265
273
  };
@@ -272,35 +280,23 @@ describe("index", () => {
272
280
  };
273
281
  mockAcpClient = {
274
282
  flushReply: vi.fn().mockResolvedValue(undefined),
283
+ reportStopReason: vi.fn().mockResolvedValue(undefined),
275
284
  };
276
285
  // Mock console.error to avoid cluttering test output
277
286
  vi.spyOn(console, "error").mockImplementation(() => { });
287
+ vi.spyOn(console, "log").mockImplementation(() => { });
278
288
  });
279
- it("should do nothing if no tasks are found", async () => {
280
- mockMcpBridge.callTool.mockResolvedValue({
281
- isError: false,
282
- content: [{ type: "text", text: "no pending tasks exist" }],
283
- });
284
- await checkForNextTask(mockMcpBridge, mockConnection, mockSessionSwitcher, mockAcpClient);
285
- expect(mockMcpBridge.callTool).toHaveBeenCalledWith("getTask");
286
- expect(mockConnection.prompt).not.toHaveBeenCalled();
287
- });
288
- it("should handle error from MCP bridge", async () => {
289
- mockMcpBridge.callTool.mockResolvedValue({
290
- isError: true,
291
- content: "some error",
292
- });
293
- await checkForNextTask(mockMcpBridge, mockConnection, mockSessionSwitcher, mockAcpClient);
294
- expect(mockMcpBridge.callTool).toHaveBeenCalledWith("getTask");
295
- expect(mockConnection.prompt).not.toHaveBeenCalled();
289
+ afterEach(() => {
290
+ vi.restoreAllMocks();
296
291
  });
297
- it("should process task and NOT recurse if task is found", async () => {
292
+ it("prompts the agent in the session that belongs to the task", async () => {
293
+ const queue = new TaskQueue(1);
298
294
  mockMcpBridge.callTool.mockResolvedValue({
299
295
  isError: false,
300
296
  content: [{ type: "text", text: "Task ID: T1\ndo something" }],
301
297
  });
302
- await checkForNextTask(mockMcpBridge, mockConnection, mockSessionSwitcher, mockAcpClient);
303
- expect(mockMcpBridge.callTool).toHaveBeenCalledTimes(1);
298
+ await drainPendingTasks(mockMcpBridge, queue, deps(queue));
299
+ await new Promise((resolve) => setTimeout(resolve, 10));
304
300
  expect(mockSessionSwitcher.ensureForTask).toHaveBeenCalledWith("T1");
305
301
  expect(mockConnection.prompt).toHaveBeenCalledWith({
306
302
  sessionId: "current-session",
@@ -321,11 +317,12 @@ describe("index", () => {
321
317
  let releaseEarlier;
322
318
  const earlier = new Promise((resolve) => { releaseEarlier = resolve; });
323
319
  const earlierTurn = runTurnForTask("T-Queued", () => earlier);
324
- const checking = checkForNextTask(mockMcpBridge, mockConnection, mockSessionSwitcher, mockAcpClient, queue);
320
+ const draining = drainPendingTasks(mockMcpBridge, queue, deps(queue));
325
321
  await new Promise((resolve) => setTimeout(resolve, 10));
326
322
  expect(mockConnection.prompt).not.toHaveBeenCalled();
327
323
  releaseEarlier();
328
- await Promise.all([earlierTurn, checking]);
324
+ await Promise.all([earlierTurn, draining]);
325
+ await new Promise((resolve) => setTimeout(resolve, 10));
329
326
  expect(mockConnection.prompt).toHaveBeenCalledTimes(1);
330
327
  expect(queue.getActiveCount()).toBe(0);
331
328
  });
@@ -345,7 +342,7 @@ describe("index", () => {
345
342
  let releaseEarlier;
346
343
  const earlier = new Promise((resolve) => { releaseEarlier = resolve; });
347
344
  const earlierTurn = runTurnForTask("T-Chatty", () => earlier);
348
- const checking = checkForNextTask(mockMcpBridge, mockConnection, mockSessionSwitcher, mockAcpClient, queue);
345
+ const draining = drainPendingTasks(mockMcpBridge, queue, deps(queue));
349
346
  await new Promise((resolve) => setTimeout(resolve, 10));
350
347
  // Behind the turn, but not occupying the gateway's only slot.
351
348
  expect(mockConnection.prompt).not.toHaveBeenCalled();
@@ -356,7 +353,8 @@ describe("index", () => {
356
353
  await new Promise((resolve) => setTimeout(resolve, 10));
357
354
  expect(unrelatedRan).toBe(true);
358
355
  releaseEarlier();
359
- await Promise.all([earlierTurn, checking, unrelated]);
356
+ await Promise.all([earlierTurn, draining, unrelated]);
357
+ await new Promise((resolve) => setTimeout(resolve, 10));
360
358
  expect(mockConnection.prompt).toHaveBeenCalledTimes(1);
361
359
  expect(queue.getActiveCount()).toBe(0);
362
360
  });
@@ -365,34 +363,513 @@ describe("index", () => {
365
363
  // prefix at the *start* of it, so anything prepended here — a wrapper, a
366
364
  // task header, a courtesy sentence — stops it being a command at all.
367
365
  // agentrq relies on this passthrough to deliver what the human typed.
366
+ const queue = new TaskQueue(1);
368
367
  mockMcpBridge.callTool.mockResolvedValue({
369
368
  isError: false,
370
369
  content: [{ type: "text", text: "/compact keep the API discussion" }],
371
370
  });
372
- await checkForNextTask(mockMcpBridge, mockConnection, mockSessionSwitcher, mockAcpClient);
371
+ await drainPendingTasks(mockMcpBridge, queue, deps(queue));
372
+ await new Promise((resolve) => setTimeout(resolve, 10));
373
373
  expect(mockConnection.prompt).toHaveBeenCalledWith({
374
374
  sessionId: "current-session",
375
375
  prompt: [{ type: "text", text: "/compact keep the API discussion" }],
376
376
  });
377
377
  });
378
- it("should handle exceptions during execution", async () => {
379
- mockMcpBridge.callTool.mockRejectedValue(new Error("network error"));
380
- await checkForNextTask(mockMcpBridge, mockConnection, mockSessionSwitcher, mockAcpClient);
378
+ });
379
+ describe("fetchNextTask", () => {
380
+ let bridge;
381
+ beforeEach(() => {
382
+ vi.spyOn(console, "error").mockImplementation(() => { });
383
+ vi.spyOn(console, "log").mockImplementation(() => { });
384
+ bridge = { callTool: vi.fn() };
385
+ });
386
+ afterEach(() => {
387
+ vi.restoreAllMocks();
388
+ });
389
+ it("hands back the task the workspace dequeued", async () => {
390
+ bridge.callTool.mockResolvedValue({
391
+ isError: false,
392
+ content: [{ type: "text", text: "Task ID: T-Fetch\nplease do it" }],
393
+ });
394
+ const outcome = await fetchNextTask(bridge);
395
+ expect(bridge.callTool).toHaveBeenCalledWith("getTask");
396
+ expect(outcome.status).toBe("task");
397
+ const task = outcome.task;
398
+ expect(task.text).toBe("Task ID: T-Fetch\nplease do it");
399
+ expect(task.taskId).toBe("T-Fetch");
400
+ // Stamped at the fetch, so a cancel landing during session setup still bites.
401
+ expect(task.queuedSeq).toBeGreaterThan(0);
402
+ });
403
+ it("tells an empty workspace apart from one it could not ask", async () => {
404
+ // A caller filling slots treats these differently: an empty workspace is
405
+ // the end of the drain, while a workspace that could not be reached is
406
+ // the bridge's problem to reconnect rather than this loop's to retry.
407
+ bridge.callTool.mockResolvedValueOnce({
408
+ isError: false,
409
+ content: [{ type: "text", text: "no pending tasks exist" }],
410
+ });
411
+ expect(await fetchNextTask(bridge)).toEqual({ status: "empty" });
412
+ bridge.callTool.mockResolvedValueOnce({ isError: false, content: [] });
413
+ expect(await fetchNextTask(bridge)).toEqual({ status: "empty" });
414
+ bridge.callTool.mockResolvedValueOnce({
415
+ isError: false,
416
+ content: [{ type: "text", text: "" }],
417
+ });
418
+ expect(await fetchNextTask(bridge)).toEqual({ status: "empty" });
419
+ bridge.callTool.mockResolvedValueOnce({ isError: true, content: "nope" });
420
+ expect(await fetchNextTask(bridge)).toEqual({ status: "failed" });
421
+ bridge.callTool.mockRejectedValueOnce(new Error("network error"));
422
+ expect(await fetchNextTask(bridge)).toEqual({ status: "failed" });
381
423
  expect(console.error).toHaveBeenCalledWith(expect.stringContaining("Failed to check for next task"), expect.any(Error));
382
424
  });
383
- it("should drop repetitive task messages for the same taskId", async () => {
384
- mockMcpBridge.callTool.mockResolvedValue({
425
+ it("says a repeat was skipped, not that the workspace is empty", async () => {
426
+ // The difference matters: a repeat has been dequeued and dropped, so the
427
+ // slot it was meant to fill is still free and something else may fill it.
428
+ bridge.callTool.mockResolvedValue({
385
429
  isError: false,
386
- content: [{ type: "text", text: "Task ID: T-Rep\nsome repetitive task" }],
430
+ content: [{ type: "text", text: "Task ID: T-Twice\nsame words" }],
387
431
  });
388
- // First run: should execute
389
- await checkForNextTask(mockMcpBridge, mockConnection, mockSessionSwitcher, mockAcpClient);
390
- expect(mockConnection.prompt).toHaveBeenCalledTimes(1);
391
- // Reset mock connection call count
392
- mockConnection.prompt.mockClear();
393
- // Second run with same content: should drop and not execute
394
- await checkForNextTask(mockMcpBridge, mockConnection, mockSessionSwitcher, mockAcpClient);
395
- expect(mockConnection.prompt).not.toHaveBeenCalled();
432
+ expect((await fetchNextTask(bridge)).status).toBe("task");
433
+ expect(await fetchNextTask(bridge)).toEqual({ status: "skipped" });
434
+ });
435
+ it("takes an unnamed task, since not every delivery carries an id", async () => {
436
+ bridge.callTool.mockResolvedValue({
437
+ isError: false,
438
+ content: [{ type: "text", text: "/compact keep the API discussion" }],
439
+ });
440
+ const outcome = await fetchNextTask(bridge);
441
+ expect(outcome.status).toBe("task");
442
+ const task = outcome.task;
443
+ expect(task.taskId).toBeUndefined();
444
+ expect(task.text).toBe("/compact keep the API discussion");
445
+ });
446
+ });
447
+ describe("startPendingTask", () => {
448
+ afterEach(() => {
449
+ activeSessions.clear();
450
+ resetIdleSession();
451
+ resetTaskTurns();
452
+ vi.restoreAllMocks();
453
+ });
454
+ it("opens a session from the agent command when it was given one", async () => {
455
+ // The gateway's own path passes a command rather than an open
456
+ // connection, and that is the shape `main` uses — so it is the shape
457
+ // that has to work when the workspace hands over a task.
458
+ vi.spyOn(console, "error").mockImplementation(() => { });
459
+ const prompt = vi.fn().mockResolvedValue({ stopReason: "end_turn" });
460
+ const acpClient = {
461
+ flushReply: vi.fn().mockResolvedValue(undefined),
462
+ reportStopReason: vi.fn().mockResolvedValue(undefined),
463
+ };
464
+ activeSessions.set("T-Cmd", {
465
+ process: {},
466
+ connection: { prompt },
467
+ acpClient: acpClient,
468
+ sessionId: "S-Cmd",
469
+ initResult: {},
470
+ adopt: vi.fn(),
471
+ });
472
+ await startPendingTask({ text: "Task ID: T-Cmd\nwork", taskId: "T-Cmd", queuedSeq: 1 }, { callTool: vi.fn() }, {
473
+ acpCmdArgsOrConnection: ["fake-agent"],
474
+ configsOrSessionSwitcher: [],
475
+ agentrqConfigOrAcpClient: { name: "agentrq", type: "http" },
476
+ });
477
+ expect(prompt).toHaveBeenCalledWith({
478
+ sessionId: "S-Cmd",
479
+ prompt: [{ type: "text", text: "Task ID: T-Cmd\nwork" }],
480
+ });
481
+ expect(acpClient.reportStopReason).toHaveBeenCalledWith("S-Cmd", "end_turn");
482
+ });
483
+ it("uses the session it was handed when there is no switcher to ask", async () => {
484
+ // --list-models and friends open a session that belongs to no task and
485
+ // hand it straight over; there is nothing to switch between.
486
+ vi.spyOn(console, "error").mockImplementation(() => { });
487
+ const prompt = vi.fn().mockResolvedValue({ stopReason: "end_turn" });
488
+ const acpClient = {
489
+ flushReply: vi.fn().mockResolvedValue(undefined),
490
+ reportStopReason: vi.fn().mockResolvedValue(undefined),
491
+ };
492
+ await startPendingTask({ text: "just do it", queuedSeq: 1 }, { callTool: vi.fn() }, {
493
+ acpCmdArgsOrConnection: { prompt },
494
+ configsOrSessionSwitcher: undefined,
495
+ agentrqConfigOrAcpClient: acpClient,
496
+ });
497
+ expect(prompt).toHaveBeenCalledWith({
498
+ sessionId: undefined,
499
+ prompt: [{ type: "text", text: "just do it" }],
500
+ });
501
+ });
502
+ it("cancels the session when the cancel lands while it is being opened", async () => {
503
+ // Opening a session takes seconds, and a cancel that arrives inside that
504
+ // window has no turn to stop yet — so the task must not be handed to the
505
+ // agent once the session finally exists.
506
+ vi.spyOn(console, "error").mockImplementation(() => { });
507
+ cancelledTaskSeq.clear();
508
+ const prompt = vi.fn().mockResolvedValue({ stopReason: "end_turn" });
509
+ const acpClient = {
510
+ flushReply: vi.fn().mockResolvedValue(undefined),
511
+ reportStopReason: vi.fn().mockResolvedValue(undefined),
512
+ cancelTurn: vi.fn().mockResolvedValue(undefined),
513
+ };
514
+ const switcher = {
515
+ getSessionId: vi.fn().mockReturnValue("S-Late"),
516
+ ensureForTask: vi.fn(async (id) => {
517
+ markTaskCancelled(id);
518
+ return `S-${id}`;
519
+ }),
520
+ };
521
+ await startPendingTask({ text: "Task ID: T-Late\nnever mind", taskId: "T-Late", queuedSeq: 1 }, { callTool: vi.fn() }, {
522
+ acpCmdArgsOrConnection: { prompt },
523
+ configsOrSessionSwitcher: switcher,
524
+ agentrqConfigOrAcpClient: acpClient,
525
+ });
526
+ expect(acpClient.cancelTurn).toHaveBeenCalledWith("S-T-Late");
527
+ expect(prompt).not.toHaveBeenCalled();
528
+ cancelledTaskSeq.clear();
529
+ });
530
+ });
531
+ describe("createSelfFillingTaskQueue", () => {
532
+ it("fetches work whenever the queue has room, at startup and after", async () => {
533
+ // The whole of "a gateway allowed three tasks runs three tasks": the
534
+ // queue says it has room, and something goes and fills it.
535
+ vi.spyOn(console, "error").mockImplementation(() => { });
536
+ vi.spyOn(console, "log").mockImplementation(() => { });
537
+ resetPendingTaskDrain();
538
+ resetTaskTurns();
539
+ resetConcurrencyReports();
540
+ const bridge = {
541
+ callTool: vi.fn(),
542
+ sendNotification: vi.fn().mockResolvedValue(undefined),
543
+ };
544
+ const connection = {
545
+ prompt: vi.fn().mockResolvedValue({ stopReason: "end_turn" }),
546
+ };
547
+ const acpClient = {
548
+ flushReply: vi.fn().mockResolvedValue(undefined),
549
+ reportStopReason: vi.fn().mockResolvedValue(undefined),
550
+ };
551
+ const switcher = {
552
+ getSessionId: vi.fn().mockReturnValue("S"),
553
+ ensureForTask: vi.fn(async (id) => `S-${id}`),
554
+ };
555
+ bridge.callTool
556
+ .mockResolvedValueOnce({
557
+ isError: false,
558
+ content: [{ type: "text", text: "Task ID: W1\nfirst" }],
559
+ })
560
+ .mockResolvedValue({
561
+ isError: false,
562
+ content: [{ type: "text", text: "no pending tasks exist" }],
563
+ });
564
+ const queue = createSelfFillingTaskQueue(1, bridge, {
565
+ acpCmdArgsOrConnection: connection,
566
+ configsOrSessionSwitcher: switcher,
567
+ agentrqConfigOrAcpClient: acpClient,
568
+ });
569
+ await drainPendingTasks(bridge, queue, {
570
+ acpCmdArgsOrConnection: connection,
571
+ configsOrSessionSwitcher: switcher,
572
+ agentrqConfigOrAcpClient: acpClient,
573
+ taskQueue: queue,
574
+ });
575
+ await new Promise((resolve) => setTimeout(resolve, 10));
576
+ expect(connection.prompt).toHaveBeenCalledTimes(1);
577
+ // The task finished and freed its slot, so the queue went back for more
578
+ // on its own rather than sitting idle until something pushed it.
579
+ expect(bridge.callTool.mock.calls.length).toBeGreaterThanOrEqual(2);
580
+ // And it still reports itself to the workspace, as before.
581
+ expect(bridge.sendNotification).toHaveBeenCalled();
582
+ resetConcurrencyReports();
583
+ vi.restoreAllMocks();
584
+ });
585
+ });
586
+ describe("freeSlots", () => {
587
+ it("counts the room left, with what is waiting already spoken for", () => {
588
+ const queue = new TaskQueue(3);
589
+ expect(freeSlots(queue)).toBe(3);
590
+ });
591
+ it("never goes negative when the limit was lowered under running work", () => {
592
+ // Lowering never interrupts, so the queue can legitimately hold more than
593
+ // the limit allows — and a negative number of slots would read as room.
594
+ const queue = new TaskQueue(3);
595
+ let release;
596
+ const held = new Promise((resolve) => { release = resolve; });
597
+ const running = [queue.run(() => held), queue.run(() => held), queue.run(() => held)];
598
+ queue.setMaxConcurrency(1);
599
+ expect(freeSlots(queue)).toBe(0);
600
+ release();
601
+ return Promise.all(running);
602
+ });
603
+ });
604
+ describe("drainPendingTasks", () => {
605
+ let bridge;
606
+ let connection;
607
+ let switcher;
608
+ let acpClient;
609
+ /** A workspace answer holding one task. */
610
+ const task = (id) => ({
611
+ isError: false,
612
+ content: [{ type: "text", text: `Task ID: ${id}\nwork on ${id}` }],
613
+ });
614
+ /** The workspace answer meaning there is nothing left. */
615
+ const nothing = () => ({
616
+ isError: false,
617
+ content: [{ type: "text", text: "no pending tasks exist" }],
618
+ });
619
+ const deps = () => ({
620
+ acpCmdArgsOrConnection: connection,
621
+ configsOrSessionSwitcher: switcher,
622
+ agentrqConfigOrAcpClient: acpClient,
623
+ });
624
+ beforeEach(() => {
625
+ vi.spyOn(console, "error").mockImplementation(() => { });
626
+ vi.spyOn(console, "log").mockImplementation(() => { });
627
+ resetPendingTaskDrain();
628
+ resetTaskTurns();
629
+ bridge = { callTool: vi.fn() };
630
+ connection = { prompt: vi.fn().mockResolvedValue({ stopReason: "end_turn" }) };
631
+ switcher = {
632
+ getSessionId: vi.fn().mockReturnValue("S"),
633
+ ensureForTask: vi.fn(async (id) => `S-${id}`),
634
+ };
635
+ acpClient = {
636
+ flushReply: vi.fn().mockResolvedValue(undefined),
637
+ reportStopReason: vi.fn().mockResolvedValue(undefined),
638
+ };
639
+ });
640
+ afterEach(() => {
641
+ vi.restoreAllMocks();
642
+ });
643
+ it("fills every free slot instead of taking a single task", async () => {
644
+ // The bug this exists for: three tasks waiting, three slots, and the
645
+ // gateway running one of them because it only ever asked once.
646
+ const queue = new TaskQueue(3);
647
+ let release;
648
+ const held = new Promise((resolve) => { release = resolve; });
649
+ connection.prompt.mockReturnValue(held.then(() => ({ stopReason: "end_turn" })));
650
+ bridge.callTool
651
+ .mockResolvedValueOnce(task("D1"))
652
+ .mockResolvedValueOnce(task("D2"))
653
+ .mockResolvedValueOnce(task("D3"))
654
+ .mockResolvedValue(nothing());
655
+ await drainPendingTasks(bridge, queue, deps());
656
+ expect(queue.getActiveCount()).toBe(3);
657
+ // Three fetches and no fourth: it stops at the limit rather than
658
+ // emptying the workspace into a queue nobody asked it to hold.
659
+ expect(bridge.callTool).toHaveBeenCalledTimes(3);
660
+ release();
661
+ await new Promise((resolve) => setTimeout(resolve, 10));
662
+ expect(connection.prompt).toHaveBeenCalledTimes(3);
663
+ });
664
+ it("keeps working after a drain that found no room at all", async () => {
665
+ // The drain that does nothing never waits for anything, so it finishes
666
+ // before the promise it will be remembered by even exists. Remembering
667
+ // it anyway left a settled promise in the one-drain-at-a-time slot, and
668
+ // every later drain joined it and fetched nothing — the whole feature
669
+ // switching itself off after one harmless call.
670
+ const queue = new TaskQueue(1);
671
+ let release;
672
+ const held = new Promise((resolve) => { release = resolve; });
673
+ const running = queue.run(() => held);
674
+ await drainPendingTasks(bridge, queue, deps());
675
+ expect(bridge.callTool).not.toHaveBeenCalled();
676
+ release();
677
+ await running;
678
+ bridge.callTool.mockResolvedValueOnce(task("A1")).mockResolvedValue(nothing());
679
+ await drainPendingTasks(bridge, queue, deps());
680
+ await new Promise((resolve) => setTimeout(resolve, 10));
681
+ expect(connection.prompt).toHaveBeenCalledTimes(1);
682
+ });
683
+ it("counts a task parked behind an earlier turn against the room it has", async () => {
684
+ // A second message on one chat waits for the first and takes no slot, so
685
+ // the queue still reads as having room. Fetching against that same room
686
+ // again and again would empty the workspace into this process, where
687
+ // nobody else can pick the work up.
688
+ resetTaskTurns();
689
+ const queue = new TaskQueue(2);
690
+ let releaseEarlier;
691
+ const earlier = new Promise((resolve) => { releaseEarlier = resolve; });
692
+ const earlierTurn = runTurnForTask("P1", () => earlier);
693
+ let release;
694
+ const held = new Promise((resolve) => { release = resolve; });
695
+ connection.prompt.mockReturnValue(held.then(() => ({ stopReason: "end_turn" })));
696
+ bridge.callTool
697
+ .mockResolvedValueOnce(task("P1"))
698
+ .mockResolvedValueOnce(task("P2"))
699
+ .mockResolvedValue(nothing());
700
+ await drainPendingTasks(bridge, queue, deps());
701
+ // Two slots, two tasks taken: the parked one counts, so there is no
702
+ // third fetch against the slot it is going to want.
703
+ expect(bridge.callTool).toHaveBeenCalledTimes(2);
704
+ releaseEarlier();
705
+ release();
706
+ await earlierTurn;
707
+ });
708
+ it("moves past a repeat instead of abandoning the slot it was meant to fill", async () => {
709
+ // A repeat has already been dequeued and dropped. Treating that as "the
710
+ // workspace is empty" left every slot idle behind it, and with nothing
711
+ // running there is no completion coming to start another drain.
712
+ const queue = new TaskQueue(2);
713
+ bridge.callTool
714
+ .mockResolvedValueOnce(task("S1"))
715
+ .mockResolvedValueOnce(task("S1"))
716
+ .mockResolvedValueOnce(task("S2"))
717
+ .mockResolvedValue(nothing());
718
+ // The first S1 is taken and run; the second is the repeat.
719
+ await drainPendingTasks(bridge, queue, deps());
720
+ await new Promise((resolve) => setTimeout(resolve, 10));
721
+ expect(connection.prompt).toHaveBeenCalledTimes(2);
722
+ expect(connection.prompt).toHaveBeenLastCalledWith({
723
+ sessionId: "S-S2",
724
+ prompt: [{ type: "text", text: "Task ID: S2\nwork on S2" }],
725
+ });
726
+ });
727
+ it("gives up on a workspace that hands back nothing but repeats", async () => {
728
+ const queue = new TaskQueue(4);
729
+ bridge.callTool.mockResolvedValueOnce(task("K1")).mockResolvedValue(task("K1"));
730
+ await drainPendingTasks(bridge, queue, deps());
731
+ await new Promise((resolve) => setTimeout(resolve, 10));
732
+ // The task itself, then the repeats it is willing to sit through.
733
+ expect(bridge.callTool).toHaveBeenCalledTimes(1 + MAX_SKIPPED_FETCHES);
734
+ });
735
+ it("leaves a workspace it could not reach to its own reconnection", async () => {
736
+ // Retrying a failing call in a tight loop is how a gateway turns a blip
737
+ // into an outage of its own.
738
+ const queue = new TaskQueue(3);
739
+ bridge.callTool.mockRejectedValue(new Error("network error"));
740
+ await drainPendingTasks(bridge, queue, deps());
741
+ expect(bridge.callTool).toHaveBeenCalledTimes(1);
742
+ });
743
+ it("asks once and stops when the workspace has nothing waiting", async () => {
744
+ const queue = new TaskQueue(3);
745
+ bridge.callTool.mockResolvedValue(nothing());
746
+ await drainPendingTasks(bridge, queue, deps());
747
+ expect(bridge.callTool).toHaveBeenCalledTimes(1);
748
+ expect(connection.prompt).not.toHaveBeenCalled();
749
+ });
750
+ it("does not ask at all while the queue is full", async () => {
751
+ const queue = new TaskQueue(1);
752
+ let release;
753
+ const held = new Promise((resolve) => { release = resolve; });
754
+ const running = queue.run(() => held);
755
+ await drainPendingTasks(bridge, queue, deps());
756
+ expect(bridge.callTool).not.toHaveBeenCalled();
757
+ release();
758
+ await running;
759
+ });
760
+ it("counts a task waiting in the queue as a slot already spoken for", async () => {
761
+ // Queued work is work this gateway has promised to run; fetching more
762
+ // against it would pull the whole workspace in and hold it here.
763
+ const queue = new TaskQueue(1);
764
+ let release;
765
+ const held = new Promise((resolve) => { release = resolve; });
766
+ const running = queue.run(() => held);
767
+ const waiting = queue.run(async () => { });
768
+ await drainPendingTasks(bridge, queue, deps());
769
+ expect(bridge.callTool).not.toHaveBeenCalled();
770
+ release();
771
+ await Promise.all([running, waiting]);
772
+ });
773
+ it("joins a drain already running, and answers the wake-up that joining collapsed", async () => {
774
+ // Every trigger — a task finishing, a limit rising — can land while a
775
+ // drain is waiting on getTask. A second drain started there would be
776
+ // asking for the task the first one is about to be handed; but simply
777
+ // swallowing the news would leave the slot that just came free empty,
778
+ // because the drain that swallowed it may already have been told the
779
+ // workspace is empty.
780
+ let queue;
781
+ const rejoined = [];
782
+ queue = new TaskQueue(2, undefined, () => {
783
+ rejoined.push(drainPendingTasks(bridge, queue, { ...deps(), taskQueue: queue }));
784
+ });
785
+ let release;
786
+ const held = new Promise((resolve) => { release = resolve; });
787
+ const running = queue.run(() => held);
788
+ const answerFetch = [];
789
+ bridge.callTool.mockImplementation(() => new Promise((resolve) => { answerFetch.push(resolve); }));
790
+ const draining = drainPendingTasks(bridge, queue, { ...deps(), taskQueue: queue });
791
+ await new Promise((resolve) => setTimeout(resolve, 0));
792
+ expect(answerFetch.length).toBe(1);
793
+ // The slot comes free while that fetch is still in the air.
794
+ release();
795
+ await running;
796
+ await new Promise((resolve) => setTimeout(resolve, 0));
797
+ expect(rejoined).toHaveLength(1);
798
+ expect(rejoined[0]).toBe(draining);
799
+ // The drain that collapsed it is told there is nothing — and goes back
800
+ // anyway, because the slot it heard about came free after it had asked.
801
+ answerFetch[0](nothing());
802
+ await new Promise((resolve) => setTimeout(resolve, 0));
803
+ expect(answerFetch.length).toBe(2);
804
+ answerFetch[1](nothing());
805
+ await draining;
806
+ expect(connection.prompt).not.toHaveBeenCalled();
807
+ });
808
+ it("goes back for more when a finished task frees a slot", async () => {
809
+ let queue;
810
+ queue = new TaskQueue(1, undefined, () => {
811
+ void drainPendingTasks(bridge, queue, { ...deps(), taskQueue: queue });
812
+ });
813
+ bridge.callTool.mockResolvedValueOnce(task("L1")).mockResolvedValue(nothing());
814
+ await drainPendingTasks(bridge, queue, { ...deps(), taskQueue: queue });
815
+ await new Promise((resolve) => setTimeout(resolve, 10));
816
+ expect(connection.prompt).toHaveBeenCalledTimes(1);
817
+ // Asked again once the slot came back, and was told there was nothing.
818
+ expect(bridge.callTool.mock.calls.length).toBeGreaterThanOrEqual(2);
819
+ });
820
+ it("keeps filling slots when one of the tasks fails", async () => {
821
+ // One task that cannot run is not a reason to leave the other slots empty.
822
+ const queue = new TaskQueue(2);
823
+ let release;
824
+ const held = new Promise((resolve) => { release = resolve; });
825
+ connection.prompt
826
+ .mockRejectedValueOnce(new Error("agent said no"))
827
+ .mockReturnValue(held.then(() => ({ stopReason: "end_turn" })));
828
+ bridge.callTool
829
+ .mockResolvedValueOnce(task("F1"))
830
+ .mockResolvedValueOnce(task("F2"))
831
+ .mockResolvedValue(nothing());
832
+ await drainPendingTasks(bridge, queue, deps());
833
+ await new Promise((resolve) => setTimeout(resolve, 10));
834
+ expect(connection.prompt).toHaveBeenCalledTimes(2);
835
+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining("Error running task F1"), expect.any(Error));
836
+ release();
837
+ });
838
+ it("names an unnamed task in the log rather than saying nothing went wrong", async () => {
839
+ const queue = new TaskQueue(1);
840
+ connection.prompt.mockRejectedValue(new Error("agent said no"));
841
+ bridge.callTool
842
+ .mockResolvedValueOnce({
843
+ isError: false,
844
+ content: [{ type: "text", text: "/compact and then some" }],
845
+ })
846
+ .mockResolvedValue(nothing());
847
+ await drainPendingTasks(bridge, queue, deps());
848
+ await new Promise((resolve) => setTimeout(resolve, 10));
849
+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining("Error running task (unnamed)"), expect.any(Error));
850
+ });
851
+ it("fills the slots a raised limit just opened", async () => {
852
+ // Raising the limit with nothing waiting internally used to start
853
+ // nothing at all: the tasks it could now run were in the workspace,
854
+ // and nothing went to ask for them.
855
+ let queue;
856
+ queue = new TaskQueue(1, undefined, () => {
857
+ void drainPendingTasks(bridge, queue, { ...deps(), taskQueue: queue });
858
+ });
859
+ let release;
860
+ const held = new Promise((resolve) => { release = resolve; });
861
+ connection.prompt.mockReturnValue(held.then(() => ({ stopReason: "end_turn" })));
862
+ bridge.callTool
863
+ .mockResolvedValueOnce(task("U1"))
864
+ .mockResolvedValueOnce(task("U2"))
865
+ .mockResolvedValueOnce(task("U3"))
866
+ .mockResolvedValue(nothing());
867
+ await drainPendingTasks(bridge, queue, { ...deps(), taskQueue: queue });
868
+ expect(queue.getActiveCount()).toBe(1);
869
+ queue.setMaxConcurrency(3);
870
+ await new Promise((resolve) => setTimeout(resolve, 10));
871
+ expect(queue.getActiveCount()).toBe(3);
872
+ release();
396
873
  });
397
874
  });
398
875
  describe("TaskQueue", () => {
@@ -643,6 +1120,83 @@ describe("index", () => {
643
1120
  });
644
1121
  });
645
1122
  });
1123
+ describe("offering its free capacity", () => {
1124
+ it("says so when a task finishes, but not when one starts", async () => {
1125
+ // Two different questions: the numbers moved (a start moves them too),
1126
+ // and there may be room now. Only the second is a reason to go and ask
1127
+ // the workspace for more work.
1128
+ let queue;
1129
+ const offers = [];
1130
+ queue = new TaskQueue(1, undefined, () => offers.push(queue.getActiveCount()));
1131
+ let release;
1132
+ const held = new Promise((resolve) => { release = resolve; });
1133
+ const running = queue.run(() => held);
1134
+ expect(offers).toEqual([]);
1135
+ release();
1136
+ await running;
1137
+ expect(offers).toEqual([0]);
1138
+ });
1139
+ it("says so when the limit is raised, even with nothing waiting here", async () => {
1140
+ // The tasks a raise makes room for are usually still in the workspace,
1141
+ // so a raise that told nobody would run nothing at all.
1142
+ let offered = 0;
1143
+ const queue = new TaskQueue(1, undefined, () => { offered++; });
1144
+ queue.setMaxConcurrency(3);
1145
+ expect(offered).toBe(1);
1146
+ // Not a change, so nothing to offer.
1147
+ queue.setMaxConcurrency(3);
1148
+ expect(offered).toBe(1);
1149
+ });
1150
+ it("says nothing when what was queued here takes the slot straight back", async () => {
1151
+ // Otherwise the gateway hears "room!" and fetches a task to sit beside
1152
+ // work it had already promised to run.
1153
+ let queue;
1154
+ const roomSeen = [];
1155
+ queue = new TaskQueue(1, undefined, () => roomSeen.push(freeSlots(queue)));
1156
+ let release;
1157
+ const held = new Promise((resolve) => { release = resolve; });
1158
+ const first = queue.run(() => held);
1159
+ let releaseSecond;
1160
+ const second = queue.run(() => new Promise((resolve) => { releaseSecond = resolve; }));
1161
+ release();
1162
+ await first;
1163
+ expect(roomSeen).toEqual([]);
1164
+ releaseSecond();
1165
+ await second;
1166
+ // Only now, with nothing left waiting, is there room worth mentioning.
1167
+ expect(roomSeen).toEqual([1]);
1168
+ });
1169
+ it("says nothing when the limit is lowered under work already running", async () => {
1170
+ // Lowering never interrupts, so a lowered limit leaves less room, not
1171
+ // more — and asking the workspace for another task would be absurd.
1172
+ let offered = 0;
1173
+ const queue = new TaskQueue(3, undefined, () => { offered++; });
1174
+ let release;
1175
+ const held = new Promise((resolve) => { release = resolve; });
1176
+ const running = [queue.run(() => held), queue.run(() => held), queue.run(() => held)];
1177
+ queue.setMaxConcurrency(1);
1178
+ expect(offered).toBe(0);
1179
+ release();
1180
+ await Promise.all(running);
1181
+ });
1182
+ it("survives a listener that throws, so a finished task still finishes", async () => {
1183
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
1184
+ const queue = new TaskQueue(1, undefined, () => {
1185
+ throw new Error("nobody to tell");
1186
+ });
1187
+ await expect(queue.run(async () => { })).resolves.toBeUndefined();
1188
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("Error offering the queue's free capacity"), expect.any(Error));
1189
+ errorSpy.mockRestore();
1190
+ });
1191
+ it("is wired through createTaskQueue, which is how the gateway gets it", () => {
1192
+ const bridge = { sendNotification: vi.fn().mockResolvedValue(undefined) };
1193
+ let offered = 0;
1194
+ const queue = createTaskQueue(2, bridge, () => { offered++; });
1195
+ queue.setMaxConcurrency(3);
1196
+ expect(offered).toBe(1);
1197
+ resetConcurrencyReports();
1198
+ });
1199
+ });
646
1200
  describe("handleSetConcurrency", () => {
647
1201
  let errorSpy;
648
1202
  beforeEach(() => {
@@ -1546,6 +2100,25 @@ describe("index", () => {
1546
2100
  expect(parseGatewayArgs(["--registry-url", "http://localhost/registry.json"]).registryUrl).toBe("http://localhost/registry.json");
1547
2101
  expect(parseGatewayArgs(["--registry-url"]).registryUrl).toBeUndefined();
1548
2102
  });
2103
+ it("should take a path to an MCP config", () => {
2104
+ expect(parseGatewayArgs(["--mcp-json", "/elsewhere/work-servers.json"])).toMatchObject({
2105
+ mcpJsonPath: "/elsewhere/work-servers.json",
2106
+ command: "run",
2107
+ rest: [],
2108
+ });
2109
+ // The path is consumed, so it cannot fall through into `rest` — which is
2110
+ // the agent command when no `--` was used.
2111
+ expect(parseGatewayArgs(["--mcp-json", "/elsewhere/servers.json", "gemini", "--acp"]).rest).toEqual(["gemini", "--acp"]);
2112
+ });
2113
+ it("should say so when --mcp-json is given no path", () => {
2114
+ // Ignoring it silently would start the gateway against whatever config
2115
+ // happened to be near the working directory — the very thing the flag
2116
+ // was typed to avoid.
2117
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => { });
2118
+ expect(parseGatewayArgs(["--mcp-json"]).mcpJsonPath).toBeUndefined();
2119
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("--mcp-json provided without a path"));
2120
+ errorSpy.mockRestore();
2121
+ });
1549
2122
  it("should recognise model options", () => {
1550
2123
  expect(parseGatewayArgs(["--list-models"])).toMatchObject({ command: "list-models" });
1551
2124
  expect(parseGatewayArgs(["--model", "claude-3-7-sonnet"])).toMatchObject({
@@ -2018,6 +2591,7 @@ describe("index", () => {
2018
2591
  "--auth-method",
2019
2592
  "--max-concurrency",
2020
2593
  "--permission-timeout",
2594
+ "--mcp-json",
2021
2595
  "--help",
2022
2596
  ]));
2023
2597
  });
@@ -2273,7 +2847,12 @@ describe("index", () => {
2273
2847
  return { content: [{ type: "text", text: "task task-queued-1: do work" }] };
2274
2848
  }),
2275
2849
  };
2276
- await checkForNextTask(bridge, connection, switcher, acpClient);
2850
+ resetPendingTaskDrain();
2851
+ await drainPendingTasks(bridge, new TaskQueue(1), {
2852
+ acpCmdArgsOrConnection: connection,
2853
+ configsOrSessionSwitcher: switcher,
2854
+ agentrqConfigOrAcpClient: acpClient,
2855
+ });
2277
2856
  expect(promptMock).not.toHaveBeenCalled();
2278
2857
  });
2279
2858
  it("should not swallow work queued after the cancellation", async () => {
@@ -2290,7 +2869,12 @@ describe("index", () => {
2290
2869
  content: [{ type: "text", text: "task task-queued-2: fresh work" }],
2291
2870
  }),
2292
2871
  };
2293
- await checkForNextTask(bridge, connection, switcher, acpClient);
2872
+ resetPendingTaskDrain();
2873
+ await drainPendingTasks(bridge, new TaskQueue(1), {
2874
+ acpCmdArgsOrConnection: connection,
2875
+ configsOrSessionSwitcher: switcher,
2876
+ agentrqConfigOrAcpClient: acpClient,
2877
+ });
2294
2878
  expect(promptMock).toHaveBeenCalled();
2295
2879
  });
2296
2880
  it("should forget the oldest cancellations rather than grow forever", async () => {