@agentrq/acp-gateway 0.2.14 → 0.2.16
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 +5 -3
- package/dist/__tests__/acpClient.test.js +56 -11
- package/dist/__tests__/acpClient.test.js.map +1 -1
- package/dist/__tests__/agentInfo.test.js +28 -2
- package/dist/__tests__/agentInfo.test.js.map +1 -1
- package/dist/__tests__/index.test.js +407 -2
- package/dist/__tests__/index.test.js.map +1 -1
- package/dist/__tests__/mcpClient.test.js +62 -1
- package/dist/__tests__/mcpClient.test.js.map +1 -1
- package/dist/acpClient.js +78 -49
- package/dist/acpClient.js.map +1 -1
- package/dist/agentInfo.js +28 -0
- package/dist/agentInfo.js.map +1 -1
- package/dist/index.js +474 -71
- package/dist/index.js.map +1 -1
- package/dist/mcpClient.js +47 -2
- package/dist/mcpClient.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -65,11 +65,11 @@ export function mapMcpServers(configs, agentCapabilities) {
|
|
|
65
65
|
};
|
|
66
66
|
});
|
|
67
67
|
}
|
|
68
|
-
import { AgentRQACPClient, DEFAULT_PERMISSION_TIMEOUT_MS } from "./acpClient.js";
|
|
68
|
+
import { AgentRQACPClient, DEFAULT_PERMISSION_TIMEOUT_MS, lastModelsForSession, sendModelsNotification, } from "./acpClient.js";
|
|
69
69
|
import { describeAuthMethods, isAuthRequiredError, login, logout, supportsLogout, } from "./auth.js";
|
|
70
70
|
import { resolveAgentLaunch } from "./agentInstall.js";
|
|
71
|
-
import { agentIdentity, describeAgentInfo } from "./agentInfo.js";
|
|
72
|
-
import { describeAgents, fetchRegistry, hostPlatformTarget, } from "./registry.js";
|
|
71
|
+
import { agentIdentity, describeAgentInfo, sendAgentIdentity, } from "./agentInfo.js";
|
|
72
|
+
import { describeAgents, fetchRegistry, findAgent, hostPlatformTarget, } from "./registry.js";
|
|
73
73
|
import { extractTaskIdFromMeta, extractTaskIdFromText, } from "./taskIdentity.js";
|
|
74
74
|
import { extractModels, formatModelsText, setSessionModel, } from "./models.js";
|
|
75
75
|
const lastTaskContent = new Map();
|
|
@@ -108,7 +108,29 @@ export function isTaskCancelled(taskId, queuedSeq) {
|
|
|
108
108
|
const seq = cancelledTaskSeq.get(taskId);
|
|
109
109
|
return seq !== undefined && seq > queuedSeq;
|
|
110
110
|
}
|
|
111
|
+
/**
|
|
112
|
+
* Where the session opened before any task is filed.
|
|
113
|
+
*
|
|
114
|
+
* It exists so a connected gateway can say what its agent offers — models and
|
|
115
|
+
* slash commands only exist inside a session, and ACP has no way to ask
|
|
116
|
+
* outside one — and it is handed to the first task rather than duplicated.
|
|
117
|
+
*/
|
|
118
|
+
export const IDLE_SESSION_KEY = "default";
|
|
111
119
|
export const activeSessions = new Map();
|
|
120
|
+
/**
|
|
121
|
+
* The startup session while it is still being opened.
|
|
122
|
+
*
|
|
123
|
+
* Opening one can take a long time — an agent that wants authentication stops
|
|
124
|
+
* and waits for a human — and a task arriving in that window would find nothing
|
|
125
|
+
* in `activeSessions` and start a second agent beside the one already coming
|
|
126
|
+
* up. Waiting for the answer costs nothing and is the difference between one
|
|
127
|
+
* agent and two.
|
|
128
|
+
*/
|
|
129
|
+
let idleSessionInFlight = null;
|
|
130
|
+
/** Forgets any in-flight startup session. For tests. */
|
|
131
|
+
export function resetIdleSession() {
|
|
132
|
+
idleSessionInFlight = null;
|
|
133
|
+
}
|
|
112
134
|
/** How long to wait for `session/close` RPC before terminating the session process regardless. */
|
|
113
135
|
export const CLOSE_SESSION_TIMEOUT_MS = 2000;
|
|
114
136
|
/** Whether the agent advertised `session.close` capability during initialize. */
|
|
@@ -321,10 +343,43 @@ const CMD_SHIM = /node_modules[\\/]\.bin[\\/][^\\/]+\.cmd$/i;
|
|
|
321
343
|
* than taken as a dependency.
|
|
322
344
|
*/
|
|
323
345
|
export function quoteForCmd(arg, doubleEscape = false) {
|
|
324
|
-
const quoted = `"${arg
|
|
346
|
+
const quoted = `"${escapeBackslashesAndQuotes(arg)}"`;
|
|
325
347
|
const escaped = quoted.replace(CMD_META_CHARS, "^$1");
|
|
326
348
|
return doubleEscape ? escaped.replace(CMD_META_CHARS, "^$1") : escaped;
|
|
327
349
|
}
|
|
350
|
+
/**
|
|
351
|
+
* Applies the Windows argument rule: a run of backslashes is doubled when a
|
|
352
|
+
* quote (or the closing quote) follows it, and left alone otherwise, and a
|
|
353
|
+
* literal quote is escaped.
|
|
354
|
+
*
|
|
355
|
+
* Written as a single pass rather than the two regexes this used to use.
|
|
356
|
+
* `/(\\*)"/g` asks the engine to match a run of backslashes and then a quote,
|
|
357
|
+
* so a long run with no quote after it is re-tried from every position in the
|
|
358
|
+
* run — quadratic in the length of the run, which is the sort of thing an
|
|
359
|
+
* argument can carry. Counting the run once cannot do that, and says the rule
|
|
360
|
+
* more plainly than the regex did.
|
|
361
|
+
*/
|
|
362
|
+
function escapeBackslashesAndQuotes(arg) {
|
|
363
|
+
let out = "";
|
|
364
|
+
let slashes = 0;
|
|
365
|
+
for (const ch of arg) {
|
|
366
|
+
if (ch === "\\") {
|
|
367
|
+
slashes++;
|
|
368
|
+
continue;
|
|
369
|
+
}
|
|
370
|
+
if (ch === '"') {
|
|
371
|
+
// The run escapes the quote we are about to add rather than the one in
|
|
372
|
+
// the argument, so it has to survive as literal backslashes: double it.
|
|
373
|
+
out += "\\".repeat(slashes * 2) + '\\"';
|
|
374
|
+
}
|
|
375
|
+
else {
|
|
376
|
+
out += "\\".repeat(slashes) + ch;
|
|
377
|
+
}
|
|
378
|
+
slashes = 0;
|
|
379
|
+
}
|
|
380
|
+
// Whatever is left runs into the closing quote, so it is doubled too.
|
|
381
|
+
return out + "\\".repeat(slashes * 2);
|
|
382
|
+
}
|
|
328
383
|
/**
|
|
329
384
|
* The command and arguments to hand `spawn`.
|
|
330
385
|
*
|
|
@@ -354,7 +409,11 @@ export async function openAgentConnection({ acpCmdArgs, mcpBridge, env, label, t
|
|
|
354
409
|
env: { ...process.env, ...env },
|
|
355
410
|
shell: needsShell(target),
|
|
356
411
|
});
|
|
357
|
-
|
|
412
|
+
// Read through a holder rather than captured directly: a session created
|
|
413
|
+
// before any task exists is later handed to the first one, and everything it
|
|
414
|
+
// reports afterwards has to be attributed to that task.
|
|
415
|
+
let currentTaskId = taskId;
|
|
416
|
+
const acpClient = new AgentRQACPClient(mcpBridge, () => currentTaskId, {
|
|
358
417
|
permissionTimeoutMs: permissionConfig.timeoutMs,
|
|
359
418
|
});
|
|
360
419
|
// Guard against unhandled child-process failures. Without these listeners a
|
|
@@ -411,7 +470,15 @@ export async function openAgentConnection({ acpCmdArgs, mcpBridge, env, label, t
|
|
|
411
470
|
if (initResult.authMethods?.length) {
|
|
412
471
|
console.error(`[auth] Agent offers these login methods:\n${describeAuthMethods(initResult.authMethods)}`);
|
|
413
472
|
}
|
|
414
|
-
return {
|
|
473
|
+
return {
|
|
474
|
+
process: agentProcess,
|
|
475
|
+
connection,
|
|
476
|
+
acpClient,
|
|
477
|
+
initResult,
|
|
478
|
+
assignTask: (id) => {
|
|
479
|
+
currentTaskId = id;
|
|
480
|
+
},
|
|
481
|
+
};
|
|
415
482
|
}
|
|
416
483
|
/**
|
|
417
484
|
* Starts a session, logging in first if the agent refuses without one.
|
|
@@ -427,92 +494,258 @@ export async function createSessionWithAuth(connection, params, auth) {
|
|
|
427
494
|
if (!isAuthRequiredError(err))
|
|
428
495
|
throw err;
|
|
429
496
|
console.error("[auth] Agent requires authentication before a session can start.");
|
|
430
|
-
|
|
431
|
-
|
|
497
|
+
// Everything from here is the login, so everything that goes wrong in it is
|
|
498
|
+
// an authentication failure — whether that is a refusal to pick a method, a
|
|
499
|
+
// terminal login the human abandoned, or the agent still saying no
|
|
500
|
+
// afterwards. Typing it here beats reading messages downstream and missing
|
|
501
|
+
// whichever one nobody thought of.
|
|
502
|
+
try {
|
|
503
|
+
await login({ ...auth, connection: connection });
|
|
504
|
+
return await connection.newSession(params);
|
|
505
|
+
}
|
|
506
|
+
catch (authErr) {
|
|
507
|
+
throw new AuthenticationFailed(authErr, Boolean(auth.methods?.length));
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
/**
|
|
512
|
+
* An agent that could not be authenticated, however the login went wrong.
|
|
513
|
+
*
|
|
514
|
+
* `hasLogin` says whether the agent offered a way in at all. An agent that
|
|
515
|
+
* advertises none is not asking to be logged in — it wants a credential it
|
|
516
|
+
* reads for itself, an API key in the environment or a file on disk — and
|
|
517
|
+
* telling its owner to log in would send them looking for a prompt that does
|
|
518
|
+
* not exist.
|
|
519
|
+
*/
|
|
520
|
+
export class AuthenticationFailed extends Error {
|
|
521
|
+
cause;
|
|
522
|
+
hasLogin;
|
|
523
|
+
constructor(cause, hasLogin = true) {
|
|
524
|
+
super(cause instanceof Error ? cause.message : String(cause));
|
|
525
|
+
this.cause = cause;
|
|
526
|
+
this.hasLogin = hasLogin;
|
|
527
|
+
this.name = "AuthenticationFailed";
|
|
432
528
|
}
|
|
433
529
|
}
|
|
434
530
|
export async function getOrCreateSession(taskId, acpCmdArgs, configs, agentrqConfig, mcpBridge) {
|
|
435
|
-
|
|
436
|
-
const existing = activeSessions.get(
|
|
531
|
+
let sessionKey = taskId || IDLE_SESSION_KEY;
|
|
532
|
+
const existing = activeSessions.get(sessionKey);
|
|
437
533
|
if (existing) {
|
|
438
534
|
return existing;
|
|
439
535
|
}
|
|
536
|
+
// The session made at startup, before any task, is handed to the first task
|
|
537
|
+
// that arrives rather than left beside a second agent doing the same job. Its
|
|
538
|
+
// conversation is empty, so there is nothing for the task to inherit but the
|
|
539
|
+
// process itself.
|
|
540
|
+
if (taskId) {
|
|
541
|
+
// Still coming up — wait for it rather than racing it into a second agent.
|
|
542
|
+
if (idleSessionInFlight) {
|
|
543
|
+
try {
|
|
544
|
+
await idleSessionInFlight;
|
|
545
|
+
}
|
|
546
|
+
catch {
|
|
547
|
+
// It failed; this task opens its own below, and reports the failure
|
|
548
|
+
// itself rather than inheriting a stale one.
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
const idle = activeSessions.get(IDLE_SESSION_KEY);
|
|
552
|
+
if (idle) {
|
|
553
|
+
idle.adopt(taskId);
|
|
554
|
+
console.error(`[acp] Task ${taskId} took over the session opened at startup`);
|
|
555
|
+
return idle;
|
|
556
|
+
}
|
|
557
|
+
}
|
|
440
558
|
const [cmd, ...cmdArgs] = acpCmdArgs;
|
|
441
|
-
const { process: agentProcess, connection, acpClient, initResult } = await openAgentConnection({
|
|
559
|
+
const { process: agentProcess, connection, acpClient, initResult, assignTask } = await openAgentConnection({
|
|
442
560
|
acpCmdArgs,
|
|
443
561
|
mcpBridge,
|
|
444
562
|
env: agentrqConfig.env,
|
|
445
|
-
label: `task ${
|
|
563
|
+
label: taskId ? `task ${taskId}` : "the idle session",
|
|
446
564
|
taskId,
|
|
447
|
-
onExit: () => activeSessions.delete(
|
|
565
|
+
onExit: () => activeSessions.delete(sessionKey),
|
|
448
566
|
});
|
|
449
567
|
const newSessionParams = {
|
|
450
568
|
cwd: process.cwd(),
|
|
451
569
|
mcpServers: mapMcpServers(configs, initResult.agentCapabilities),
|
|
452
570
|
};
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
console.error(`[acp] Created session ${sessionResult.sessionId} for task ${key}`);
|
|
460
|
-
// Tell the workspace which agent this actually is. Its MCP client is this
|
|
461
|
-
// gateway, so without this the workspace can only ever name the bridge.
|
|
462
|
-
void acpClient.sendAgentToWorkspace(sessionResult.sessionId, agentIdentity(initResult, acpCmdArgs.join(" ")));
|
|
571
|
+
// From here on the agent is running but nothing is tracking it yet: it only
|
|
572
|
+
// reaches activeSessions once a session exists, and closeAllSessions can only
|
|
573
|
+
// close what is in there. So anything that goes wrong in between has to take
|
|
574
|
+
// the process with it, or it is left running with nothing attached — an agent
|
|
575
|
+
// that quits when its stdin closes gets away with it, and one with its own
|
|
576
|
+
// event loop, which is the sort that wants a login, does not.
|
|
463
577
|
try {
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
578
|
+
// An agent that demands authentication stops here and waits, including at
|
|
579
|
+
// startup — that is the point of starting a session then. A terminal is where
|
|
580
|
+
// someone can actually answer, and finding out on the first task instead
|
|
581
|
+
// means a gateway that looked connected all along.
|
|
582
|
+
//
|
|
583
|
+
// Headless, `login` refuses rather than blocking on a prompt nobody can see:
|
|
584
|
+
// it only offers a terminal method to an interactive terminal, and throws a
|
|
585
|
+
// message naming --auth-method otherwise. openIdleSession logs that and
|
|
586
|
+
// leaves the gateway up.
|
|
587
|
+
const sessionResult = await createSessionWithAuth(connection, newSessionParams, {
|
|
588
|
+
methods: initResult.authMethods,
|
|
589
|
+
launch: { command: cmd, args: cmdArgs, env: agentrqConfig.env },
|
|
590
|
+
preferredId: authConfig.methodId,
|
|
591
|
+
interactive: isInteractiveTerminal(),
|
|
592
|
+
});
|
|
593
|
+
console.error(`[acp] Created session ${sessionResult.sessionId} for ${taskId ? `task ${taskId}` : "the idle session"}`);
|
|
594
|
+
// Tell the workspace which agent this actually is. Its MCP client is this
|
|
595
|
+
// gateway, so without this the workspace can only ever name the bridge.
|
|
596
|
+
void acpClient.sendAgentToWorkspace(sessionResult.sessionId, agentIdentity(initResult, acpCmdArgs.join(" ")));
|
|
597
|
+
try {
|
|
598
|
+
const modelsResult = extractModels(sessionResult.configOptions);
|
|
599
|
+
if (modelsResult) {
|
|
600
|
+
await applyModelSelection({
|
|
601
|
+
connection,
|
|
602
|
+
acpClient,
|
|
603
|
+
sessionId: sessionResult.sessionId,
|
|
604
|
+
known: modelsResult,
|
|
605
|
+
requested: modelConfig.modelId,
|
|
606
|
+
});
|
|
493
607
|
}
|
|
494
608
|
}
|
|
609
|
+
catch (err) {
|
|
610
|
+
console.error(`[acp] Failed to extract or configure models for session ${sessionResult.sessionId}:`, err);
|
|
611
|
+
}
|
|
612
|
+
await enforceHumanApprovalMode(connection, sessionResult);
|
|
613
|
+
// The mode is pinned once here, but agents may move themselves back out of
|
|
614
|
+
// it, so keep watching for the rest of the session's life.
|
|
615
|
+
acpClient.setModeChangeHandler((changedSessionId, modeId) => handleAgentModeChange(connection, changedSessionId, modeId, sessionResult.modes));
|
|
616
|
+
const sessionInfo = {
|
|
617
|
+
process: agentProcess,
|
|
618
|
+
connection,
|
|
619
|
+
acpClient,
|
|
620
|
+
sessionId: sessionResult.sessionId,
|
|
621
|
+
initResult,
|
|
622
|
+
adopt(nextTaskId) {
|
|
623
|
+
activeSessions.delete(sessionKey);
|
|
624
|
+
sessionKey = nextTaskId;
|
|
625
|
+
activeSessions.set(sessionKey, sessionInfo);
|
|
626
|
+
assignTask?.(nextTaskId);
|
|
627
|
+
},
|
|
628
|
+
};
|
|
629
|
+
activeSessions.set(sessionKey, sessionInfo);
|
|
630
|
+
return sessionInfo;
|
|
495
631
|
}
|
|
496
632
|
catch (err) {
|
|
497
|
-
|
|
633
|
+
terminateAgentProcess(agentProcess);
|
|
634
|
+
throw err;
|
|
498
635
|
}
|
|
499
|
-
await enforceHumanApprovalMode(connection, sessionResult);
|
|
500
|
-
// The mode is pinned once here, but agents may move themselves back out of
|
|
501
|
-
// it, so keep watching for the rest of the session's life.
|
|
502
|
-
acpClient.setModeChangeHandler((changedSessionId, modeId) => handleAgentModeChange(connection, changedSessionId, modeId, sessionResult.modes));
|
|
503
|
-
const sessionInfo = {
|
|
504
|
-
process: agentProcess,
|
|
505
|
-
connection,
|
|
506
|
-
acpClient,
|
|
507
|
-
sessionId: sessionResult.sessionId,
|
|
508
|
-
initResult,
|
|
509
|
-
};
|
|
510
|
-
activeSessions.set(key, sessionInfo);
|
|
511
|
-
return sessionInfo;
|
|
512
636
|
}
|
|
513
637
|
/**
|
|
514
638
|
* Finds the active agent session for a given task ID (or returns the single active session if none specified).
|
|
515
639
|
*/
|
|
640
|
+
/**
|
|
641
|
+
* Opens a session before any task, so the workspace can say what this agent
|
|
642
|
+
* offers rather than only that something is attached.
|
|
643
|
+
*
|
|
644
|
+
* Models arrive as config options on `session/new` and slash commands as a
|
|
645
|
+
* session notification, so there is no way to learn either without a session —
|
|
646
|
+
* ACP has no question to ask outside one.
|
|
647
|
+
*
|
|
648
|
+
* An agent that demands authentication stops and waits here, which is much of
|
|
649
|
+
* the value of starting a session at all: the terminal someone just typed into
|
|
650
|
+
* is where they can answer.
|
|
651
|
+
*
|
|
652
|
+
* If that login does not happen — refused, or headless where there is nobody to
|
|
653
|
+
* ask — the gateway shuts down rather than carrying on. It would otherwise sit
|
|
654
|
+
* there looking connected, take every task the workspace gave it and fail all
|
|
655
|
+
* of them, which is worse than not running: the workspace would show a live
|
|
656
|
+
* agent while the work quietly went nowhere.
|
|
657
|
+
*
|
|
658
|
+
* Every other failure is survivable and is survived. An agent that could not be
|
|
659
|
+
* spawned may simply have lost a race; it used to fail when the first task
|
|
660
|
+
* arrived and it still does, and turning that into a gateway that refuses to
|
|
661
|
+
* run would be a worse trade than the one this is making.
|
|
662
|
+
*
|
|
663
|
+
* The session is handed to the first task rather than left running beside it —
|
|
664
|
+
* see getOrCreateSession.
|
|
665
|
+
*/
|
|
666
|
+
export async function openIdleSession(acpCmdArgs, configs, agentrqConfig, mcpBridge, loginCommand = loginCommandFor(), timeoutMs = IDLE_SESSION_TIMEOUT_MS) {
|
|
667
|
+
try {
|
|
668
|
+
// Cleared when the session itself settles rather than when this returns:
|
|
669
|
+
// after a timeout the session is still coming, and a task that arrives
|
|
670
|
+
// meanwhile should still wait for it instead of starting a second agent.
|
|
671
|
+
idleSessionInFlight = getOrCreateSession(undefined, acpCmdArgs, configs, agentrqConfig, mcpBridge);
|
|
672
|
+
const settled = idleSessionInFlight;
|
|
673
|
+
void settled.catch(() => { }).finally(() => {
|
|
674
|
+
if (idleSessionInFlight === settled)
|
|
675
|
+
idleSessionInFlight = null;
|
|
676
|
+
});
|
|
677
|
+
// Bounded: nothing reaches the workspace until this settles, so an agent
|
|
678
|
+
// that spawns and then never answers its handshake would otherwise take the
|
|
679
|
+
// whole gateway down with it — a worse failure than the one being fixed,
|
|
680
|
+
// and a new one. On a timeout the gateway carries on; the session may still
|
|
681
|
+
// arrive, and the first task will adopt it if it does.
|
|
682
|
+
const timedOut = Symbol("timed out");
|
|
683
|
+
let timer;
|
|
684
|
+
const result = await Promise.race([
|
|
685
|
+
idleSessionInFlight,
|
|
686
|
+
new Promise((resolve) => {
|
|
687
|
+
timer = setTimeout(() => resolve(timedOut), timeoutMs);
|
|
688
|
+
}),
|
|
689
|
+
]);
|
|
690
|
+
if (timer)
|
|
691
|
+
clearTimeout(timer);
|
|
692
|
+
if (result === timedOut) {
|
|
693
|
+
console.error(`[acp] The agent has not opened a session after ${Math.round(timeoutMs / 1000)}s; ` +
|
|
694
|
+
"carrying on without knowing what it offers.");
|
|
695
|
+
return "unknown";
|
|
696
|
+
}
|
|
697
|
+
return "ready";
|
|
698
|
+
}
|
|
699
|
+
catch (err) {
|
|
700
|
+
if (err instanceof AuthenticationFailed || isAuthRequiredError(err)) {
|
|
701
|
+
const remedy = err instanceof AuthenticationFailed && !err.hasLogin
|
|
702
|
+
? `It offers no way to log in through acp-gateway, so it is expecting a credential ` +
|
|
703
|
+
`of its own — an API key in the environment, or whatever its own documentation ` +
|
|
704
|
+
`asks for. Set that and start acp-gateway again.`
|
|
705
|
+
: `Log in with:\n\n ${loginCommand}\n\nthen start acp-gateway again.`;
|
|
706
|
+
console.error(`\n[acp-gateway] The agent will not start a session until it is authenticated: ` +
|
|
707
|
+
`${err instanceof Error ? err.message : String(err)}\n` +
|
|
708
|
+
`Nothing was started. ${remedy}\n` +
|
|
709
|
+
`Carrying on would leave the workspace showing a live agent that fails every task ` +
|
|
710
|
+
`it is given.`);
|
|
711
|
+
return "unauthenticated";
|
|
712
|
+
}
|
|
713
|
+
console.error("[acp] Could not open a session to learn what the agent offers; " +
|
|
714
|
+
"the first task will start one:", err instanceof Error ? err.message : String(err));
|
|
715
|
+
return "unknown";
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
/**
|
|
719
|
+
* The command that logs this agent in, so the message can name it rather than
|
|
720
|
+
* leave someone to work it out.
|
|
721
|
+
*
|
|
722
|
+
* Built from how the gateway itself was started: the registry id when there was
|
|
723
|
+
* one, and otherwise the command after `--`, since that is the only handle on
|
|
724
|
+
* an agent nobody named.
|
|
725
|
+
*/
|
|
726
|
+
export function loginCommandFor(agentId, agentCommand = []) {
|
|
727
|
+
const base = "npx @agentrq/acp-gateway@latest --login";
|
|
728
|
+
if (agentId)
|
|
729
|
+
return `${base} --agent ${agentId}`;
|
|
730
|
+
if (agentCommand.length)
|
|
731
|
+
return `${base} -- ${agentCommand.join(" ")}`;
|
|
732
|
+
return base;
|
|
733
|
+
}
|
|
734
|
+
/**
|
|
735
|
+
* How long to wait for an agent to open its first session.
|
|
736
|
+
*
|
|
737
|
+
* Generous because the wait includes starting the agent, and an `npx`
|
|
738
|
+
* distribution downloads its package the first time it is spawned — a cold
|
|
739
|
+
* install of a large one on a slow line is minutes, not seconds. (A registry
|
|
740
|
+
* *binary* is already on disk by now: that download happens while the launch
|
|
741
|
+
* command is being resolved, before any of this.)
|
|
742
|
+
*
|
|
743
|
+
* Erring long costs little. A session that arrives after the deadline is still
|
|
744
|
+
* recorded, still reports what the agent offers, and is still adopted by the
|
|
745
|
+
* first task — the timeout only decides how long the gateway waits before
|
|
746
|
+
* connecting to the workspace without knowing those things yet.
|
|
747
|
+
*/
|
|
748
|
+
export const IDLE_SESSION_TIMEOUT_MS = 5 * 60_000;
|
|
516
749
|
export function findActiveSession(taskId) {
|
|
517
750
|
if (taskId) {
|
|
518
751
|
const direct = activeSessions.get(taskId);
|
|
@@ -523,10 +756,15 @@ export function findActiveSession(taskId) {
|
|
|
523
756
|
return session;
|
|
524
757
|
}
|
|
525
758
|
// A session opened from a notification that carried no task id is keyed
|
|
526
|
-
//
|
|
527
|
-
// only have meant it. Never fall back to a session keyed under a
|
|
759
|
+
// under IDLE_SESSION_KEY; when it is the only one running, an id-carrying
|
|
760
|
+
// cancel can only have meant it. Never fall back to a session keyed under a
|
|
528
761
|
// *different* task id — that would abort an unrelated task.
|
|
529
|
-
|
|
762
|
+
//
|
|
763
|
+
// The session opened at startup shares that key until a task adopts it, so
|
|
764
|
+
// this can now match one that has never run anything. That stays correct
|
|
765
|
+
// either way: if it was reused for a task-less prompt it is the session the
|
|
766
|
+
// cancel meant, and if it is untouched it has no turn to cancel.
|
|
767
|
+
const untracked = activeSessions.get(IDLE_SESSION_KEY);
|
|
530
768
|
if (untracked && activeSessions.size === 1) {
|
|
531
769
|
return untracked;
|
|
532
770
|
}
|
|
@@ -536,6 +774,131 @@ export function findActiveSession(taskId) {
|
|
|
536
774
|
}
|
|
537
775
|
return undefined;
|
|
538
776
|
}
|
|
777
|
+
/**
|
|
778
|
+
* Switches a session's model and tells the workspace what it ended up as.
|
|
779
|
+
*
|
|
780
|
+
* The one place a model is ever set, reached from two directions: the --model
|
|
781
|
+
* flag as a session opens, and a selection made in the interface while it is
|
|
782
|
+
* running. They were one block until the second existed; keeping two copies of
|
|
783
|
+
* resolve-set-echo would have let the startup path and the runtime path drift
|
|
784
|
+
* into disagreeing about what a failed switch looks like.
|
|
785
|
+
*
|
|
786
|
+
* Whatever happens, the workspace is told something. That is the contract the
|
|
787
|
+
* interface is built on: it marks a chosen model pending and waits for a models
|
|
788
|
+
* notification to settle it, so a switch that quietly failed would leave the
|
|
789
|
+
* picker claiming a model the agent never adopted. Every path below ends in a
|
|
790
|
+
* report — the new list on success, the old one on any failure.
|
|
791
|
+
*/
|
|
792
|
+
export async function applyModelSelection({ connection, acpClient, sessionId, known, requested, configId, }) {
|
|
793
|
+
// Freshest first. `known` was read before the set was attempted, and the agent
|
|
794
|
+
// may have reported a different list while that call was in flight — echoing
|
|
795
|
+
// the older snapshot would tell the workspace the session is on a model it has
|
|
796
|
+
// already left, and, because every report is recorded, would write that stale
|
|
797
|
+
// list back over the newer one. The cache is preferred over it for that reason,
|
|
798
|
+
// and `known` stays as the last resort for the startup path, where the session
|
|
799
|
+
// has not reported anything yet.
|
|
800
|
+
const echo = (result) => {
|
|
801
|
+
const fallback = result ?? acpClient.lastModelsFor(sessionId) ?? known;
|
|
802
|
+
if (fallback)
|
|
803
|
+
void acpClient.sendModelsToWorkspace(sessionId, fallback);
|
|
804
|
+
};
|
|
805
|
+
// Nothing asked for, or already the current model: report and stop. Setting a
|
|
806
|
+
// model the session is already on would be a needless round trip to the agent
|
|
807
|
+
// for an answer nobody is waiting on.
|
|
808
|
+
if (!requested || (known && requested === known.currentModelId)) {
|
|
809
|
+
echo();
|
|
810
|
+
return;
|
|
811
|
+
}
|
|
812
|
+
// Resolved by display name as well as by id, because --model is typed by a
|
|
813
|
+
// human who may well have copied what the picker showed them. A selection
|
|
814
|
+
// from the interface always carries an id and matches on the first branch.
|
|
815
|
+
const target = known?.models.find((m) => m.id === requested || m.name === requested);
|
|
816
|
+
if (known && !target) {
|
|
817
|
+
console.error(`[acp] Requested model "${requested}" not found in available models: ${known.models.map((m) => m.id).join(", ")}`);
|
|
818
|
+
echo();
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
const option = configId ?? known?.configId;
|
|
822
|
+
if (!option) {
|
|
823
|
+
console.error(`[acp] Cannot set model "${requested}" for session ${sessionId}: no config option to write it to`);
|
|
824
|
+
echo();
|
|
825
|
+
return;
|
|
826
|
+
}
|
|
827
|
+
const modelId = target?.id ?? requested;
|
|
828
|
+
try {
|
|
829
|
+
const updateRes = await setSessionModel(connection, sessionId, option, modelId);
|
|
830
|
+
// The agent's own answer is preferred over anything assumed here — it is
|
|
831
|
+
// what actually took effect. The constructed fallback is for agents that
|
|
832
|
+
// answer without repeating their config, and marks the chosen model current
|
|
833
|
+
// rather than leaving the interface with nothing selected.
|
|
834
|
+
const updated = extractModels(updateRes.configOptions) ??
|
|
835
|
+
(known
|
|
836
|
+
? {
|
|
837
|
+
...known,
|
|
838
|
+
currentModelId: modelId,
|
|
839
|
+
models: known.models.map((m) => ({ ...m, current: m.id === modelId })),
|
|
840
|
+
}
|
|
841
|
+
: undefined);
|
|
842
|
+
echo(updated);
|
|
843
|
+
}
|
|
844
|
+
catch (err) {
|
|
845
|
+
console.error(`[acp] Failed to set requested model "${requested}":`, err);
|
|
846
|
+
echo();
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
/**
|
|
850
|
+
* Switches model on a session the workspace names, at the workspace's request.
|
|
851
|
+
*
|
|
852
|
+
* The session id on the wire is the agent's own, which is what activeSessions
|
|
853
|
+
* is searched by — findActiveSession already matches on it, and on the task id
|
|
854
|
+
* a session is filed under, so either identifies the same session.
|
|
855
|
+
*
|
|
856
|
+
* A set for a session that has gone still answers, and so does one that names no
|
|
857
|
+
* model. The interface is holding a pending model and only a models notification
|
|
858
|
+
* releases it, so staying silent about either would leave it pending forever;
|
|
859
|
+
* echoing what was last known lets it revert to the truth. That is why the last
|
|
860
|
+
* report outlives the session that produced it — by the time a set arrives for a
|
|
861
|
+
* finished session, the client that served it has exited with its agent, and the
|
|
862
|
+
* bridge is all that is left to answer through.
|
|
863
|
+
*/
|
|
864
|
+
export async function handleSetModel({ sessionId, configId, modelId, },
|
|
865
|
+
/** How a session that has already gone is answered. Absent only in tests. */
|
|
866
|
+
bridge) {
|
|
867
|
+
const session = findActiveSession(sessionId);
|
|
868
|
+
// Nothing to switch, but the picker is still waiting on an answer, so give it
|
|
869
|
+
// the truth rather than nothing: a live session reports through its own client,
|
|
870
|
+
// and a finished one through whatever was last recorded for it.
|
|
871
|
+
const revert = async (why) => {
|
|
872
|
+
console.error(`[bridge] ${why}; reporting the last known models instead`);
|
|
873
|
+
if (session) {
|
|
874
|
+
const last = session.acpClient.lastModelsFor(session.sessionId);
|
|
875
|
+
if (last)
|
|
876
|
+
await session.acpClient.sendModelsToWorkspace(session.sessionId, last);
|
|
877
|
+
return;
|
|
878
|
+
}
|
|
879
|
+
const last = sessionId ? lastModelsForSession(sessionId) : undefined;
|
|
880
|
+
if (bridge && sessionId && last) {
|
|
881
|
+
await sendModelsNotification(bridge, sessionId, last);
|
|
882
|
+
}
|
|
883
|
+
};
|
|
884
|
+
if (!modelId) {
|
|
885
|
+
await revert("Received a set_model notification naming no model");
|
|
886
|
+
return;
|
|
887
|
+
}
|
|
888
|
+
if (!session) {
|
|
889
|
+
await revert(`Received set_model for session ${sessionId ?? "(unnamed)"}, but no active session matches it`);
|
|
890
|
+
return;
|
|
891
|
+
}
|
|
892
|
+
console.error(`[bridge] Switching session ${session.sessionId} to model "${modelId}"`);
|
|
893
|
+
await applyModelSelection({
|
|
894
|
+
connection: session.connection,
|
|
895
|
+
acpClient: session.acpClient,
|
|
896
|
+
sessionId: session.sessionId,
|
|
897
|
+
known: session.acpClient.lastModelsFor(session.sessionId),
|
|
898
|
+
requested: modelId,
|
|
899
|
+
configId,
|
|
900
|
+
});
|
|
901
|
+
}
|
|
539
902
|
/**
|
|
540
903
|
* Handles task cancellation events from the MCP server.
|
|
541
904
|
* Cancels the ACP session/turn and immediately cancels any pending permissions.
|
|
@@ -878,7 +1241,14 @@ export async function resolveAgentCommand(options, explicitCommand, fetchImpl =
|
|
|
878
1241
|
fetchImpl,
|
|
879
1242
|
});
|
|
880
1243
|
console.error(`[registry] Running "${options.agentId}" via ${spec.kind}: ${spec.command} ${spec.args.join(" ")}`);
|
|
881
|
-
|
|
1244
|
+
// What the registry says this agent is. Known now, before it has been
|
|
1245
|
+
// started, which is the only reason a workspace can name it while the
|
|
1246
|
+
// gateway is idle — the agent itself does not speak until a task arrives.
|
|
1247
|
+
const entry = findAgent(registry, options.agentId);
|
|
1248
|
+
const identity = entry
|
|
1249
|
+
? { name: entry.name || entry.id, version: entry.version }
|
|
1250
|
+
: undefined;
|
|
1251
|
+
return { command: [spec.command, ...spec.args], env: spec.env, identity };
|
|
882
1252
|
}
|
|
883
1253
|
/**
|
|
884
1254
|
* Whether a command can actually be run.
|
|
@@ -1142,7 +1512,6 @@ async function main() {
|
|
|
1142
1512
|
}
|
|
1143
1513
|
process.exit(0);
|
|
1144
1514
|
}
|
|
1145
|
-
await mcpBridge.connect();
|
|
1146
1515
|
let cleanupPromise = null;
|
|
1147
1516
|
const cleanup = async (signal) => {
|
|
1148
1517
|
if (cleanupPromise)
|
|
@@ -1218,6 +1587,40 @@ async function main() {
|
|
|
1218
1587
|
console.error("[bridge] Error handling task cancellation:", err);
|
|
1219
1588
|
});
|
|
1220
1589
|
});
|
|
1590
|
+
mcpBridge.on("setModel", (params) => {
|
|
1591
|
+
handleSetModel(params, mcpBridge).catch((err) => {
|
|
1592
|
+
console.error("[bridge] Error handling model selection:", err);
|
|
1593
|
+
});
|
|
1594
|
+
});
|
|
1595
|
+
// Everything above is listening; nothing below can be missed.
|
|
1596
|
+
//
|
|
1597
|
+
// The agent comes up before the workspace is told anything, so a task can
|
|
1598
|
+
// never be handed to a gateway whose agent is not ready — or, if it needs a
|
|
1599
|
+
// login nobody can give it, to one that will never be ready. Awaited for
|
|
1600
|
+
// that reason: whatever the workspace learns next, it learns about an agent
|
|
1601
|
+
// that already exists.
|
|
1602
|
+
//
|
|
1603
|
+
// The handlers above are registered first because opening that session
|
|
1604
|
+
// sends notifications, and sending one opens the connection. A task pushed
|
|
1605
|
+
// between the connection opening and something listening for it is a task
|
|
1606
|
+
// dropped on the floor.
|
|
1607
|
+
const idle = await openIdleSession(acpCmdArgs, configs, agentrqConfig, mcpBridge, loginCommandFor(options.agentId, explicitCommand));
|
|
1608
|
+
if (idle === "unauthenticated") {
|
|
1609
|
+
// Nothing to unwind: the agent was terminated where it was spawned, and
|
|
1610
|
+
// the workspace connection below has not been opened yet.
|
|
1611
|
+
removeSignalHandlers();
|
|
1612
|
+
process.exit(1);
|
|
1613
|
+
}
|
|
1614
|
+
await mcpBridge.connect();
|
|
1615
|
+
// Only when the agent has not spoken for itself. A session that came up
|
|
1616
|
+
// already reported the agent's own name, title and version from its
|
|
1617
|
+
// handshake, and the registry's entry is a coarser answer to the same
|
|
1618
|
+
// question — sending it after would replace what the agent said about
|
|
1619
|
+
// itself with what an index says about it, dropping the title and swapping
|
|
1620
|
+
// the running version for a published one.
|
|
1621
|
+
if (idle !== "ready" && resolved.identity) {
|
|
1622
|
+
void sendAgentIdentity(mcpBridge, resolved.identity);
|
|
1623
|
+
}
|
|
1221
1624
|
// Initial check for a pending task
|
|
1222
1625
|
await checkForNextTask(mcpBridge, acpCmdArgs, configs, agentrqConfig, taskQueue);
|
|
1223
1626
|
// Keep the process alive
|