@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.
- package/README.md +3 -1
- package/dist/__tests__/acpClient.test.js +64 -6
- package/dist/__tests__/acpClient.test.js.map +1 -1
- package/dist/__tests__/agentInfo.test.js +55 -2
- package/dist/__tests__/agentInfo.test.js.map +1 -1
- package/dist/__tests__/index.test.js +203 -2
- package/dist/__tests__/index.test.js.map +1 -1
- package/dist/acpClient.js +25 -12
- package/dist/acpClient.js.map +1 -1
- package/dist/agentInfo.js +58 -7
- package/dist/agentInfo.js.map +1 -1
- package/dist/index.js +357 -60
- package/dist/index.js.map +1 -1
- package/dist/mcpClient.js +20 -2
- package/dist/mcpClient.js.map +1 -1
- package/package.json +1 -1
package/dist/agentInfo.js
CHANGED
|
@@ -20,15 +20,66 @@ function section(title, rows) {
|
|
|
20
20
|
const body = rows.map(([label, value]) => ` ${label.padEnd(width)} ${value}`);
|
|
21
21
|
return [title, ...body].join("\n");
|
|
22
22
|
}
|
|
23
|
-
/** The
|
|
24
|
-
|
|
23
|
+
/** The notification agentrq listens on for which agent is behind the gateway. */
|
|
24
|
+
export const AGENT_NOTIFICATION_METHOD = "notifications/claude/channel/agent";
|
|
25
|
+
/**
|
|
26
|
+
* Sends an agent's identity to the workspace.
|
|
27
|
+
*
|
|
28
|
+
* No task is required. The workspace keys this to the MCP connection it arrived
|
|
29
|
+
* on and ignores the task and session ids entirely, so demanding one would only
|
|
30
|
+
* guarantee silence at the moment it matters most — before any task has run,
|
|
31
|
+
* which is exactly when someone is looking at the workspace wondering what is
|
|
32
|
+
* attached to it.
|
|
33
|
+
*
|
|
34
|
+
* Never throws: this is a label for a human, and a workspace that cannot take
|
|
35
|
+
* it right now must not cost the agent anything.
|
|
36
|
+
*/
|
|
37
|
+
export async function sendAgentIdentity(bridge, identity, scope = {}) {
|
|
38
|
+
const payload = {
|
|
39
|
+
task_id: scope.taskId ?? "",
|
|
40
|
+
session_id: scope.sessionId ?? "",
|
|
41
|
+
name: identity.name,
|
|
42
|
+
title: identity.title,
|
|
43
|
+
version: identity.version,
|
|
44
|
+
};
|
|
45
|
+
try {
|
|
46
|
+
await bridge.sendNotification(AGENT_NOTIFICATION_METHOD, payload);
|
|
47
|
+
console.error(`[acp] Told the workspace it is talking to "${identity.name}"`);
|
|
48
|
+
}
|
|
49
|
+
catch (err) {
|
|
50
|
+
console.error(`[acp] Failed to send agent notification:`, err);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Who the agent is, from its `initialize` response.
|
|
55
|
+
*
|
|
56
|
+
* ACP leaves `agentInfo` optional, so an agent that says nothing about itself
|
|
57
|
+
* is named by how it was launched instead. That is the only name available and
|
|
58
|
+
* it is better than none — the workspace's "which agent is this" is otherwise
|
|
59
|
+
* unanswerable.
|
|
60
|
+
*
|
|
61
|
+
* `title` is dropped when it merely repeats the name, so a caller rendering
|
|
62
|
+
* both does not print the same word twice.
|
|
63
|
+
*/
|
|
64
|
+
export function agentIdentity(initResult, launchedAs) {
|
|
25
65
|
const info = initResult
|
|
26
66
|
.agentInfo;
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
const
|
|
31
|
-
|
|
67
|
+
const name = info?.name?.trim();
|
|
68
|
+
if (!name)
|
|
69
|
+
return { name: launchedAs };
|
|
70
|
+
const identity = { name };
|
|
71
|
+
const title = info?.title?.trim();
|
|
72
|
+
if (title && title !== name)
|
|
73
|
+
identity.title = title;
|
|
74
|
+
const version = info?.version?.trim();
|
|
75
|
+
if (version)
|
|
76
|
+
identity.version = version;
|
|
77
|
+
return identity;
|
|
78
|
+
}
|
|
79
|
+
/** The agent's own name for itself, falling back to how it was launched. */
|
|
80
|
+
function heading(initResult, launchedAs) {
|
|
81
|
+
const { name, title, version } = agentIdentity(initResult, launchedAs);
|
|
82
|
+
return `${name}${title ? ` — ${title}` : ""}${version ? ` ${version}` : ""}`;
|
|
32
83
|
}
|
|
33
84
|
/**
|
|
34
85
|
* Describes an agent's capabilities as the agent itself reported them.
|
package/dist/agentInfo.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agentInfo.js","sourceRoot":"","sources":["../src/agentInfo.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAEhD,8EAA8E;AAC9E,SAAS,SAAS,CAAC,KAAc;IAC/B,OAAO,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,KAAK,CAAC;AAClE,CAAC;AAED,SAAS,KAAK,CAAC,KAAc;IAC3B,OAAO,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;AACzC,CAAC;AAED,SAAS,OAAO,CAAC,KAAa,EAAE,IAA6B;IAC3D,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC;IAC/D,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,KAAK,EAAE,CAAC,CAAC;IAChF,OAAO,CAAC,KAAK,EAAE,GAAG,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACrC,CAAC;AAED,
|
|
1
|
+
{"version":3,"file":"agentInfo.js","sourceRoot":"","sources":["../src/agentInfo.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAEhD,8EAA8E;AAC9E,SAAS,SAAS,CAAC,KAAc;IAC/B,OAAO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ACvB,CAAC,KAAK,EAAE,KAAK,CAAE,GAAyB,CAAC,GAAG,CAAC,CAAC;SAC/C,CAAC;QAEF,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC;YAC/D,yBAAyB,mBAAmB,CAAC,UAAU,CAAC,WAAW,CAAC,EAAE;KACzE,CAAC;IAEF,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC7B,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -68,8 +68,8 @@ export function mapMcpServers(configs, agentCapabilities) {
|
|
|
68
68
|
import { AgentRQACPClient, DEFAULT_PERMISSION_TIMEOUT_MS } from "./acpClient.js";
|
|
69
69
|
import { describeAuthMethods, isAuthRequiredError, login, logout, supportsLogout, } from "./auth.js";
|
|
70
70
|
import { resolveAgentLaunch } from "./agentInstall.js";
|
|
71
|
-
import { 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,89 +494,279 @@ 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}`);
|
|
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.
|
|
460
577
|
try {
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
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
|
+
if (modelConfig.modelId && modelConfig.modelId !== modelsResult.currentModelId) {
|
|
601
|
+
const targetModel = modelsResult.models.find((m) => m.id === modelConfig.modelId || m.name === modelConfig.modelId);
|
|
602
|
+
if (targetModel) {
|
|
603
|
+
try {
|
|
604
|
+
const updateRes = await setSessionModel(connection, sessionResult.sessionId, modelsResult.configId, targetModel.id);
|
|
605
|
+
const updatedModels = extractModels(updateRes.configOptions) ?? {
|
|
606
|
+
...modelsResult,
|
|
607
|
+
currentModelId: targetModel.id,
|
|
608
|
+
models: modelsResult.models.map((m) => ({
|
|
609
|
+
...m,
|
|
610
|
+
current: m.id === targetModel.id,
|
|
611
|
+
})),
|
|
612
|
+
};
|
|
613
|
+
void acpClient.sendModelsToWorkspace(sessionResult.sessionId, updatedModels);
|
|
614
|
+
}
|
|
615
|
+
catch (err) {
|
|
616
|
+
console.error(`[acp] Failed to set requested model "${modelConfig.modelId}":`, err);
|
|
617
|
+
void acpClient.sendModelsToWorkspace(sessionResult.sessionId, modelsResult);
|
|
618
|
+
}
|
|
477
619
|
}
|
|
478
|
-
|
|
479
|
-
console.error(`[acp]
|
|
620
|
+
else {
|
|
621
|
+
console.error(`[acp] Requested model "${modelConfig.modelId}" not found in available models: ${modelsResult.models.map((m) => m.id).join(", ")}`);
|
|
480
622
|
void acpClient.sendModelsToWorkspace(sessionResult.sessionId, modelsResult);
|
|
481
623
|
}
|
|
482
624
|
}
|
|
483
625
|
else {
|
|
484
|
-
console.error(`[acp] Requested model "${modelConfig.modelId}" not found in available models: ${modelsResult.models.map((m) => m.id).join(", ")}`);
|
|
485
626
|
void acpClient.sendModelsToWorkspace(sessionResult.sessionId, modelsResult);
|
|
486
627
|
}
|
|
487
628
|
}
|
|
488
|
-
else {
|
|
489
|
-
void acpClient.sendModelsToWorkspace(sessionResult.sessionId, modelsResult);
|
|
490
|
-
}
|
|
491
629
|
}
|
|
630
|
+
catch (err) {
|
|
631
|
+
console.error(`[acp] Failed to extract or configure models for session ${sessionResult.sessionId}:`, err);
|
|
632
|
+
}
|
|
633
|
+
await enforceHumanApprovalMode(connection, sessionResult);
|
|
634
|
+
// The mode is pinned once here, but agents may move themselves back out of
|
|
635
|
+
// it, so keep watching for the rest of the session's life.
|
|
636
|
+
acpClient.setModeChangeHandler((changedSessionId, modeId) => handleAgentModeChange(connection, changedSessionId, modeId, sessionResult.modes));
|
|
637
|
+
const sessionInfo = {
|
|
638
|
+
process: agentProcess,
|
|
639
|
+
connection,
|
|
640
|
+
acpClient,
|
|
641
|
+
sessionId: sessionResult.sessionId,
|
|
642
|
+
initResult,
|
|
643
|
+
adopt(nextTaskId) {
|
|
644
|
+
activeSessions.delete(sessionKey);
|
|
645
|
+
sessionKey = nextTaskId;
|
|
646
|
+
activeSessions.set(sessionKey, sessionInfo);
|
|
647
|
+
assignTask?.(nextTaskId);
|
|
648
|
+
},
|
|
649
|
+
};
|
|
650
|
+
activeSessions.set(sessionKey, sessionInfo);
|
|
651
|
+
return sessionInfo;
|
|
492
652
|
}
|
|
493
653
|
catch (err) {
|
|
494
|
-
|
|
654
|
+
terminateAgentProcess(agentProcess);
|
|
655
|
+
throw err;
|
|
495
656
|
}
|
|
496
|
-
await enforceHumanApprovalMode(connection, sessionResult);
|
|
497
|
-
// The mode is pinned once here, but agents may move themselves back out of
|
|
498
|
-
// it, so keep watching for the rest of the session's life.
|
|
499
|
-
acpClient.setModeChangeHandler((changedSessionId, modeId) => handleAgentModeChange(connection, changedSessionId, modeId, sessionResult.modes));
|
|
500
|
-
const sessionInfo = {
|
|
501
|
-
process: agentProcess,
|
|
502
|
-
connection,
|
|
503
|
-
acpClient,
|
|
504
|
-
sessionId: sessionResult.sessionId,
|
|
505
|
-
initResult,
|
|
506
|
-
};
|
|
507
|
-
activeSessions.set(key, sessionInfo);
|
|
508
|
-
return sessionInfo;
|
|
509
657
|
}
|
|
510
658
|
/**
|
|
511
659
|
* Finds the active agent session for a given task ID (or returns the single active session if none specified).
|
|
512
660
|
*/
|
|
661
|
+
/**
|
|
662
|
+
* Opens a session before any task, so the workspace can say what this agent
|
|
663
|
+
* offers rather than only that something is attached.
|
|
664
|
+
*
|
|
665
|
+
* Models arrive as config options on `session/new` and slash commands as a
|
|
666
|
+
* session notification, so there is no way to learn either without a session —
|
|
667
|
+
* ACP has no question to ask outside one.
|
|
668
|
+
*
|
|
669
|
+
* An agent that demands authentication stops and waits here, which is much of
|
|
670
|
+
* the value of starting a session at all: the terminal someone just typed into
|
|
671
|
+
* is where they can answer.
|
|
672
|
+
*
|
|
673
|
+
* If that login does not happen — refused, or headless where there is nobody to
|
|
674
|
+
* ask — the gateway shuts down rather than carrying on. It would otherwise sit
|
|
675
|
+
* there looking connected, take every task the workspace gave it and fail all
|
|
676
|
+
* of them, which is worse than not running: the workspace would show a live
|
|
677
|
+
* agent while the work quietly went nowhere.
|
|
678
|
+
*
|
|
679
|
+
* Every other failure is survivable and is survived. An agent that could not be
|
|
680
|
+
* spawned may simply have lost a race; it used to fail when the first task
|
|
681
|
+
* arrived and it still does, and turning that into a gateway that refuses to
|
|
682
|
+
* run would be a worse trade than the one this is making.
|
|
683
|
+
*
|
|
684
|
+
* The session is handed to the first task rather than left running beside it —
|
|
685
|
+
* see getOrCreateSession.
|
|
686
|
+
*/
|
|
687
|
+
export async function openIdleSession(acpCmdArgs, configs, agentrqConfig, mcpBridge, loginCommand = loginCommandFor(), timeoutMs = IDLE_SESSION_TIMEOUT_MS) {
|
|
688
|
+
try {
|
|
689
|
+
// Cleared when the session itself settles rather than when this returns:
|
|
690
|
+
// after a timeout the session is still coming, and a task that arrives
|
|
691
|
+
// meanwhile should still wait for it instead of starting a second agent.
|
|
692
|
+
idleSessionInFlight = getOrCreateSession(undefined, acpCmdArgs, configs, agentrqConfig, mcpBridge);
|
|
693
|
+
const settled = idleSessionInFlight;
|
|
694
|
+
void settled.catch(() => { }).finally(() => {
|
|
695
|
+
if (idleSessionInFlight === settled)
|
|
696
|
+
idleSessionInFlight = null;
|
|
697
|
+
});
|
|
698
|
+
// Bounded: nothing reaches the workspace until this settles, so an agent
|
|
699
|
+
// that spawns and then never answers its handshake would otherwise take the
|
|
700
|
+
// whole gateway down with it — a worse failure than the one being fixed,
|
|
701
|
+
// and a new one. On a timeout the gateway carries on; the session may still
|
|
702
|
+
// arrive, and the first task will adopt it if it does.
|
|
703
|
+
const timedOut = Symbol("timed out");
|
|
704
|
+
let timer;
|
|
705
|
+
const result = await Promise.race([
|
|
706
|
+
idleSessionInFlight,
|
|
707
|
+
new Promise((resolve) => {
|
|
708
|
+
timer = setTimeout(() => resolve(timedOut), timeoutMs);
|
|
709
|
+
}),
|
|
710
|
+
]);
|
|
711
|
+
if (timer)
|
|
712
|
+
clearTimeout(timer);
|
|
713
|
+
if (result === timedOut) {
|
|
714
|
+
console.error(`[acp] The agent has not opened a session after ${Math.round(timeoutMs / 1000)}s; ` +
|
|
715
|
+
"carrying on without knowing what it offers.");
|
|
716
|
+
return "unknown";
|
|
717
|
+
}
|
|
718
|
+
return "ready";
|
|
719
|
+
}
|
|
720
|
+
catch (err) {
|
|
721
|
+
if (err instanceof AuthenticationFailed || isAuthRequiredError(err)) {
|
|
722
|
+
const remedy = err instanceof AuthenticationFailed && !err.hasLogin
|
|
723
|
+
? `It offers no way to log in through acp-gateway, so it is expecting a credential ` +
|
|
724
|
+
`of its own — an API key in the environment, or whatever its own documentation ` +
|
|
725
|
+
`asks for. Set that and start acp-gateway again.`
|
|
726
|
+
: `Log in with:\n\n ${loginCommand}\n\nthen start acp-gateway again.`;
|
|
727
|
+
console.error(`\n[acp-gateway] The agent will not start a session until it is authenticated: ` +
|
|
728
|
+
`${err instanceof Error ? err.message : String(err)}\n` +
|
|
729
|
+
`Nothing was started. ${remedy}\n` +
|
|
730
|
+
`Carrying on would leave the workspace showing a live agent that fails every task ` +
|
|
731
|
+
`it is given.`);
|
|
732
|
+
return "unauthenticated";
|
|
733
|
+
}
|
|
734
|
+
console.error("[acp] Could not open a session to learn what the agent offers; " +
|
|
735
|
+
"the first task will start one:", err instanceof Error ? err.message : String(err));
|
|
736
|
+
return "unknown";
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
/**
|
|
740
|
+
* The command that logs this agent in, so the message can name it rather than
|
|
741
|
+
* leave someone to work it out.
|
|
742
|
+
*
|
|
743
|
+
* Built from how the gateway itself was started: the registry id when there was
|
|
744
|
+
* one, and otherwise the command after `--`, since that is the only handle on
|
|
745
|
+
* an agent nobody named.
|
|
746
|
+
*/
|
|
747
|
+
export function loginCommandFor(agentId, agentCommand = []) {
|
|
748
|
+
const base = "npx @agentrq/acp-gateway@latest --login";
|
|
749
|
+
if (agentId)
|
|
750
|
+
return `${base} --agent ${agentId}`;
|
|
751
|
+
if (agentCommand.length)
|
|
752
|
+
return `${base} -- ${agentCommand.join(" ")}`;
|
|
753
|
+
return base;
|
|
754
|
+
}
|
|
755
|
+
/**
|
|
756
|
+
* How long to wait for an agent to open its first session.
|
|
757
|
+
*
|
|
758
|
+
* Generous because the wait includes starting the agent, and an `npx`
|
|
759
|
+
* distribution downloads its package the first time it is spawned — a cold
|
|
760
|
+
* install of a large one on a slow line is minutes, not seconds. (A registry
|
|
761
|
+
* *binary* is already on disk by now: that download happens while the launch
|
|
762
|
+
* command is being resolved, before any of this.)
|
|
763
|
+
*
|
|
764
|
+
* Erring long costs little. A session that arrives after the deadline is still
|
|
765
|
+
* recorded, still reports what the agent offers, and is still adopted by the
|
|
766
|
+
* first task — the timeout only decides how long the gateway waits before
|
|
767
|
+
* connecting to the workspace without knowing those things yet.
|
|
768
|
+
*/
|
|
769
|
+
export const IDLE_SESSION_TIMEOUT_MS = 5 * 60_000;
|
|
513
770
|
export function findActiveSession(taskId) {
|
|
514
771
|
if (taskId) {
|
|
515
772
|
const direct = activeSessions.get(taskId);
|
|
@@ -520,10 +777,15 @@ export function findActiveSession(taskId) {
|
|
|
520
777
|
return session;
|
|
521
778
|
}
|
|
522
779
|
// A session opened from a notification that carried no task id is keyed
|
|
523
|
-
//
|
|
524
|
-
// only have meant it. Never fall back to a session keyed under a
|
|
780
|
+
// under IDLE_SESSION_KEY; when it is the only one running, an id-carrying
|
|
781
|
+
// cancel can only have meant it. Never fall back to a session keyed under a
|
|
525
782
|
// *different* task id — that would abort an unrelated task.
|
|
526
|
-
|
|
783
|
+
//
|
|
784
|
+
// The session opened at startup shares that key until a task adopts it, so
|
|
785
|
+
// this can now match one that has never run anything. That stays correct
|
|
786
|
+
// either way: if it was reused for a task-less prompt it is the session the
|
|
787
|
+
// cancel meant, and if it is untouched it has no turn to cancel.
|
|
788
|
+
const untracked = activeSessions.get(IDLE_SESSION_KEY);
|
|
527
789
|
if (untracked && activeSessions.size === 1) {
|
|
528
790
|
return untracked;
|
|
529
791
|
}
|
|
@@ -875,7 +1137,14 @@ export async function resolveAgentCommand(options, explicitCommand, fetchImpl =
|
|
|
875
1137
|
fetchImpl,
|
|
876
1138
|
});
|
|
877
1139
|
console.error(`[registry] Running "${options.agentId}" via ${spec.kind}: ${spec.command} ${spec.args.join(" ")}`);
|
|
878
|
-
|
|
1140
|
+
// What the registry says this agent is. Known now, before it has been
|
|
1141
|
+
// started, which is the only reason a workspace can name it while the
|
|
1142
|
+
// gateway is idle — the agent itself does not speak until a task arrives.
|
|
1143
|
+
const entry = findAgent(registry, options.agentId);
|
|
1144
|
+
const identity = entry
|
|
1145
|
+
? { name: entry.name || entry.id, version: entry.version }
|
|
1146
|
+
: undefined;
|
|
1147
|
+
return { command: [spec.command, ...spec.args], env: spec.env, identity };
|
|
879
1148
|
}
|
|
880
1149
|
/**
|
|
881
1150
|
* Whether a command can actually be run.
|
|
@@ -1139,7 +1408,6 @@ async function main() {
|
|
|
1139
1408
|
}
|
|
1140
1409
|
process.exit(0);
|
|
1141
1410
|
}
|
|
1142
|
-
await mcpBridge.connect();
|
|
1143
1411
|
let cleanupPromise = null;
|
|
1144
1412
|
const cleanup = async (signal) => {
|
|
1145
1413
|
if (cleanupPromise)
|
|
@@ -1215,6 +1483,35 @@ async function main() {
|
|
|
1215
1483
|
console.error("[bridge] Error handling task cancellation:", err);
|
|
1216
1484
|
});
|
|
1217
1485
|
});
|
|
1486
|
+
// Everything above is listening; nothing below can be missed.
|
|
1487
|
+
//
|
|
1488
|
+
// The agent comes up before the workspace is told anything, so a task can
|
|
1489
|
+
// never be handed to a gateway whose agent is not ready — or, if it needs a
|
|
1490
|
+
// login nobody can give it, to one that will never be ready. Awaited for
|
|
1491
|
+
// that reason: whatever the workspace learns next, it learns about an agent
|
|
1492
|
+
// that already exists.
|
|
1493
|
+
//
|
|
1494
|
+
// The handlers above are registered first because opening that session
|
|
1495
|
+
// sends notifications, and sending one opens the connection. A task pushed
|
|
1496
|
+
// between the connection opening and something listening for it is a task
|
|
1497
|
+
// dropped on the floor.
|
|
1498
|
+
const idle = await openIdleSession(acpCmdArgs, configs, agentrqConfig, mcpBridge, loginCommandFor(options.agentId, explicitCommand));
|
|
1499
|
+
if (idle === "unauthenticated") {
|
|
1500
|
+
// Nothing to unwind: the agent was terminated where it was spawned, and
|
|
1501
|
+
// the workspace connection below has not been opened yet.
|
|
1502
|
+
removeSignalHandlers();
|
|
1503
|
+
process.exit(1);
|
|
1504
|
+
}
|
|
1505
|
+
await mcpBridge.connect();
|
|
1506
|
+
// Only when the agent has not spoken for itself. A session that came up
|
|
1507
|
+
// already reported the agent's own name, title and version from its
|
|
1508
|
+
// handshake, and the registry's entry is a coarser answer to the same
|
|
1509
|
+
// question — sending it after would replace what the agent said about
|
|
1510
|
+
// itself with what an index says about it, dropping the title and swapping
|
|
1511
|
+
// the running version for a published one.
|
|
1512
|
+
if (idle !== "ready" && resolved.identity) {
|
|
1513
|
+
void sendAgentIdentity(mcpBridge, resolved.identity);
|
|
1514
|
+
}
|
|
1218
1515
|
// Initial check for a pending task
|
|
1219
1516
|
await checkForNextTask(mcpBridge, acpCmdArgs, configs, agentrqConfig, taskQueue);
|
|
1220
1517
|
// Keep the process alive
|