@agentrq/acp-gateway 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +59 -169
- package/dist/__tests__/agentInfo.test.js +2 -31
- package/dist/__tests__/agentInfo.test.js.map +1 -1
- package/dist/__tests__/concurrency.test.js +1 -74
- package/dist/__tests__/concurrency.test.js.map +1 -1
- package/dist/__tests__/index.test.js +190 -2672
- package/dist/__tests__/index.test.js.map +1 -1
- package/dist/__tests__/localClient.test.js +100 -0
- package/dist/__tests__/localClient.test.js.map +1 -0
- package/dist/__tests__/log.test.js +1 -42
- package/dist/__tests__/log.test.js.map +1 -1
- package/dist/__tests__/mcpServers.test.js +62 -0
- package/dist/__tests__/mcpServers.test.js.map +1 -0
- package/dist/__tests__/models.test.js +2 -18
- package/dist/__tests__/models.test.js.map +1 -1
- package/dist/__tests__/native.test.js +294 -29
- package/dist/__tests__/native.test.js.map +1 -1
- package/dist/__tests__/nativeFrames.test.js +132 -4
- package/dist/__tests__/nativeFrames.test.js.map +1 -1
- package/dist/__tests__/nativeHeaders.test.js +34 -0
- package/dist/__tests__/nativeHeaders.test.js.map +1 -1
- package/dist/agentInfo.js +0 -31
- package/dist/agentInfo.js.map +1 -1
- package/dist/concurrency.js +6 -64
- package/dist/concurrency.js.map +1 -1
- package/dist/index.js +114 -1729
- package/dist/index.js.map +1 -1
- package/dist/localClient.js +91 -0
- package/dist/localClient.js.map +1 -0
- package/dist/log.js +0 -22
- package/dist/log.js.map +1 -1
- package/dist/mcpServers.js +60 -0
- package/dist/mcpServers.js.map +1 -0
- package/dist/models.js +0 -10
- package/dist/models.js.map +1 -1
- package/dist/native.js +243 -30
- package/dist/native.js.map +1 -1
- package/dist/nativeFrames.js +114 -12
- package/dist/nativeFrames.js.map +1 -1
- package/package.json +4 -6
- package/dist/__tests__/acpClient.test.js +0 -2346
- package/dist/__tests__/acpClient.test.js.map +0 -1
- package/dist/__tests__/collections.test.js +0 -116
- package/dist/__tests__/collections.test.js.map +0 -1
- package/dist/__tests__/commands.test.js +0 -92
- package/dist/__tests__/commands.test.js.map +0 -1
- package/dist/__tests__/mcpClient.test.js +0 -558
- package/dist/__tests__/mcpClient.test.js.map +0 -1
- package/dist/__tests__/taskIdentity.test.js +0 -63
- package/dist/__tests__/taskIdentity.test.js.map +0 -1
- package/dist/__tests__/telemetry.test.js +0 -151
- package/dist/__tests__/telemetry.test.js.map +0 -1
- package/dist/acpClient.js +0 -1112
- package/dist/acpClient.js.map +0 -1
- package/dist/collections.js +0 -105
- package/dist/collections.js.map +0 -1
- package/dist/commands.js +0 -60
- package/dist/commands.js.map +0 -1
- package/dist/mcpClient.js +0 -361
- package/dist/mcpClient.js.map +0 -1
- package/dist/taskIdentity.js +0 -41
- package/dist/taskIdentity.js.map +0 -1
- package/dist/telemetry.js +0 -106
- package/dist/telemetry.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -3,224 +3,32 @@
|
|
|
3
3
|
* index.ts
|
|
4
4
|
*
|
|
5
5
|
* The main entry point for acp-gateway.
|
|
6
|
-
*
|
|
6
|
+
*
|
|
7
|
+
* `run` pipes an ACP agent's stdio to AgentRQ's ACP v1 endpoint (see
|
|
8
|
+
* native.ts); AgentRQ is the ACP client and this process only moves bytes. The
|
|
9
|
+
* one-shot commands — login, logout, listing models and the like — talk to the
|
|
10
|
+
* agent here, with no workspace involved.
|
|
7
11
|
*/
|
|
8
12
|
import { spawn } from "node:child_process";
|
|
9
|
-
import { EventEmitter } from "node:events";
|
|
10
13
|
import { Writable, Readable } from "node:stream";
|
|
11
|
-
import { existsSync, mkdtempSync,
|
|
14
|
+
import { existsSync, mkdtempSync, rmSync } from "node:fs";
|
|
12
15
|
import { tmpdir } from "node:os";
|
|
13
16
|
import * as path from "node:path";
|
|
14
17
|
import * as acp from "@agentclientprotocol/sdk";
|
|
15
|
-
|
|
16
|
-
import { loadMcpConfig, pickAgentrqServer, } from "./config.js";
|
|
17
|
-
import { MCPBridge, callTaskAction } from "./mcpClient.js";
|
|
18
|
-
import { BoundedMap, FifoQueue } from "./collections.js";
|
|
18
|
+
import { loadMcpConfig, pickAgentrqServer } from "./config.js";
|
|
19
19
|
import { runNative } from "./native.js";
|
|
20
20
|
import { nativeEndpoint, tokenFrom } from "./nativeFrames.js";
|
|
21
|
-
|
|
22
|
-
* What the agent said about a transport, if anything.
|
|
23
|
-
*
|
|
24
|
-
* stdio is the one transport every agent must support. For the others the
|
|
25
|
-
* answer is only trustworthy when the agent actually stated it: an agent that
|
|
26
|
-
* advertises no MCP capabilities at all is far more likely to be terse than to
|
|
27
|
-
* be unable to reach an HTTP server, and dropping its servers on that reading
|
|
28
|
-
* would take the workspace's own MCP server away from it.
|
|
29
|
-
*/
|
|
30
|
-
function transportSupport(transport, agentCapabilities) {
|
|
31
|
-
if (transport === "stdio")
|
|
32
|
-
return "required";
|
|
33
|
-
const declared = agentCapabilities?.mcpCapabilities?.[transport];
|
|
34
|
-
if (declared === true)
|
|
35
|
-
return "declared";
|
|
36
|
-
if (declared === false)
|
|
37
|
-
return "refused";
|
|
38
|
-
return "unstated";
|
|
39
|
-
}
|
|
40
|
-
export function mapMcpServers(configs, agentCapabilities) {
|
|
41
|
-
return configs
|
|
42
|
-
.filter((cfg) => {
|
|
43
|
-
const support = transportSupport(cfg.type, agentCapabilities);
|
|
44
|
-
if (support === "refused") {
|
|
45
|
-
console.error(`[acp] ⚠️ Not passing MCP server "${cfg.name}" to the agent: it is ${cfg.type}, ` +
|
|
46
|
-
`and the agent says it does not support that transport. Passing it anyway ` +
|
|
47
|
-
`risks the agent refusing the whole session.`);
|
|
48
|
-
return false;
|
|
49
|
-
}
|
|
50
|
-
if (support === "unstated") {
|
|
51
|
-
debug(`[acp] MCP server "${cfg.name}" is ${cfg.type}, which the agent does not ` +
|
|
52
|
-
`advertise either way — passing it and letting the agent decide.`);
|
|
53
|
-
}
|
|
54
|
-
return true;
|
|
55
|
-
})
|
|
56
|
-
.map((cfg) => {
|
|
57
|
-
if (cfg.type === "stdio") {
|
|
58
|
-
return {
|
|
59
|
-
name: cfg.name,
|
|
60
|
-
command: cfg.command,
|
|
61
|
-
args: cfg.args ?? [],
|
|
62
|
-
env: Object.entries(cfg.env || {}).map(([name, value]) => ({ name, value })),
|
|
63
|
-
};
|
|
64
|
-
}
|
|
65
|
-
return {
|
|
66
|
-
type: cfg.type,
|
|
67
|
-
name: cfg.name,
|
|
68
|
-
url: cfg.url,
|
|
69
|
-
headers: Object.entries(cfg.headers || {}).map(([name, value]) => ({ name, value })),
|
|
70
|
-
};
|
|
71
|
-
});
|
|
72
|
-
}
|
|
73
|
-
import { AgentRQACPClient, DEFAULT_PERMISSION_TIMEOUT_MS, lastModelsForSession, sendModelsNotification, } from "./acpClient.js";
|
|
21
|
+
import { LocalACPClient } from "./localClient.js";
|
|
74
22
|
import { describeAuthMethods, isAuthRequiredError, login, logout, promptUrlElicitationOnTerminal, supportsLogout, } from "./auth.js";
|
|
75
23
|
import { resolveAgentLaunch } from "./agentInstall.js";
|
|
76
|
-
import {
|
|
77
|
-
import { availableKinds, describeAgents, fetchRegistry,
|
|
78
|
-
import {
|
|
79
|
-
import {
|
|
80
|
-
import {
|
|
81
|
-
import {
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
const lastTaskContent = new BoundedMap(200);
|
|
85
|
-
// Cancellations are remembered by *where they fall in the stream of events*
|
|
86
|
-
// rather than as a one-shot flag. agentrq reuses a chat's id as the task id, so
|
|
87
|
-
// a flag that outlived the cancellation it describes would swallow the user's
|
|
88
|
-
// next message on that chat; ordered this way, a task is skipped only when the
|
|
89
|
-
// cancel arrived after it was queued. Wall-clock time is too coarse to order
|
|
90
|
-
// two events in the same millisecond, so this is a plain counter.
|
|
91
|
-
let taskSeq = 0;
|
|
92
|
-
export const nextTaskSeq = () => ++taskSeq;
|
|
93
|
-
// A cancel for a task that never runs (a stale id, a task that already
|
|
94
|
-
// finished) leaves an entry behind, so the map is bounded.
|
|
95
|
-
export const cancelledTaskSeq = new BoundedMap(200);
|
|
96
|
-
/** Records that `taskId` has just been cancelled. */
|
|
97
|
-
export function markTaskCancelled(taskId) {
|
|
98
|
-
cancelledTaskSeq.set(taskId, nextTaskSeq());
|
|
99
|
-
}
|
|
100
|
-
/**
|
|
101
|
-
* Whether a task queued at `queuedSeq` has since been cancelled.
|
|
102
|
-
*
|
|
103
|
-
* Two notifications for the same task id can be queued at once, so the check is
|
|
104
|
-
* against the point each was queued: cancelling the older one must not stop the
|
|
105
|
-
* newer one from running.
|
|
106
|
-
*/
|
|
107
|
-
export function isTaskCancelled(taskId, queuedSeq) {
|
|
108
|
-
if (!taskId)
|
|
109
|
-
return false;
|
|
110
|
-
const seq = cancelledTaskSeq.get(taskId);
|
|
111
|
-
return seq !== undefined && seq > queuedSeq;
|
|
112
|
-
}
|
|
113
|
-
/**
|
|
114
|
-
* Where the session opened before any task is filed.
|
|
115
|
-
*
|
|
116
|
-
* It exists so a connected gateway can say what its agent offers — models and
|
|
117
|
-
* slash commands only exist inside a session, and ACP has no way to ask
|
|
118
|
-
* outside one — and it is handed to the first task rather than duplicated.
|
|
119
|
-
*/
|
|
120
|
-
export const IDLE_SESSION_KEY = "default";
|
|
121
|
-
export const activeSessions = new Map();
|
|
122
|
-
/**
|
|
123
|
-
* The startup session while it is still being opened.
|
|
124
|
-
*
|
|
125
|
-
* Opening one can take a long time — an agent that wants authentication stops
|
|
126
|
-
* and waits for a human — and a task arriving in that window would find nothing
|
|
127
|
-
* in `activeSessions` and start a second agent beside the one already coming
|
|
128
|
-
* up. Waiting for the answer costs nothing and is the difference between one
|
|
129
|
-
* agent and two.
|
|
130
|
-
*/
|
|
131
|
-
let idleSessionInFlight = null;
|
|
132
|
-
/**
|
|
133
|
-
* The turn in progress for each task, so a second delivery waits for it.
|
|
134
|
-
*
|
|
135
|
-
* ACP gives a session one turn at a time, and this gateway gives a task one
|
|
136
|
-
* session — so two deliveries of a task running at once would put two prompts
|
|
137
|
-
* on one session, where the second is refused or interleaves and the streamed
|
|
138
|
-
* output of both lands in a single reply buffer to be flushed twice.
|
|
139
|
-
*
|
|
140
|
-
* Two deliveries of a task is ordinary, not exotic: agentrq reuses a chat's id
|
|
141
|
-
* as the task id, so two messages sent to the same chat arrive as two tasks
|
|
142
|
-
* with one id, and the repetition guard drops neither because it compares text
|
|
143
|
-
* and the two say different things. They must both reach the agent — losing the
|
|
144
|
-
* second would lose what someone typed — so they are serialised rather than
|
|
145
|
-
* deduplicated. A concurrency of 1 used to serialise them by accident; above 1
|
|
146
|
-
* nothing did.
|
|
147
|
-
*/
|
|
148
|
-
const taskTurns = new Map();
|
|
149
|
-
/**
|
|
150
|
-
* Runs a task's turn once every earlier turn for that task has finished.
|
|
151
|
-
*
|
|
152
|
-
* A failed turn does not block the next one: a task whose first message errored
|
|
153
|
-
* must still be able to hear the second.
|
|
154
|
-
*/
|
|
155
|
-
export async function runTurnForTask(taskId, turn) {
|
|
156
|
-
// Nothing to serialise against. A delivery with no task id is not a second
|
|
157
|
-
// message on anything — there is no chat for it to be the second of.
|
|
158
|
-
if (taskId === undefined)
|
|
159
|
-
return turn();
|
|
160
|
-
const previous = taskTurns.get(taskId);
|
|
161
|
-
if (previous) {
|
|
162
|
-
debug(`[bridge] Task ${taskId} is already mid-turn; waiting for it rather than ` +
|
|
163
|
-
`prompting the same session twice at once`);
|
|
164
|
-
}
|
|
165
|
-
// `then(turn, turn)` rather than `then(turn)`: the next turn runs whether the
|
|
166
|
-
// one before it succeeded or threw.
|
|
167
|
-
const mine = previous ? previous.then(turn, turn) : turn();
|
|
168
|
-
const settled = mine.catch(() => { });
|
|
169
|
-
taskTurns.set(taskId, settled);
|
|
170
|
-
try {
|
|
171
|
-
await mine;
|
|
172
|
-
}
|
|
173
|
-
finally {
|
|
174
|
-
// Only if nothing has queued behind it, or the chain's tail is dropped and
|
|
175
|
-
// the next delivery starts beside the one still running.
|
|
176
|
-
if (taskTurns.get(taskId) === settled)
|
|
177
|
-
taskTurns.delete(taskId);
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
/** Forgets every in-progress turn. For tests. */
|
|
181
|
-
export function resetTaskTurns() {
|
|
182
|
-
taskTurns.clear();
|
|
183
|
-
}
|
|
184
|
-
/**
|
|
185
|
-
* Sessions that have been asked for but do not exist yet, by session key.
|
|
186
|
-
*
|
|
187
|
-
* `activeSessions` only learns about a session once the agent has spawned,
|
|
188
|
-
* handshaken, authenticated and opened it — seconds during which the map says
|
|
189
|
-
* nothing is there. Two deliveries of one task inside that window therefore
|
|
190
|
-
* both missed the cache and both spawned an agent: two processes prompting the
|
|
191
|
-
* same agent for the same task, and only the second reachable afterwards, so
|
|
192
|
-
* the first could never be closed.
|
|
193
|
-
*
|
|
194
|
-
* The workspace can deliver one task twice by pushing it and having it picked
|
|
195
|
-
* up by `getTask` — the repetition guard compares the text, and those two paths
|
|
196
|
-
* word it differently — and a raised concurrency limit is what lets both run at
|
|
197
|
-
* once instead of one after the other.
|
|
198
|
-
*/
|
|
199
|
-
const sessionsInFlight = new Map();
|
|
200
|
-
/**
|
|
201
|
-
* Every agent process this gateway has started and not yet seen exit.
|
|
202
|
-
*
|
|
203
|
-
* `activeSessions` holds only the agents that got as far as an open session,
|
|
204
|
-
* which makes it the wrong thing to reap on the way out: an agent that is still
|
|
205
|
-
* handshaking — or one stopped waiting for a login that is never coming — is in
|
|
206
|
-
* no map at all, so shutdown closed nothing and the process was left behind. An
|
|
207
|
-
* agent that quits when its stdin closes gets away with that; one with an event
|
|
208
|
-
* loop of its own, which is exactly the sort that waits for a login, does not.
|
|
209
|
-
*
|
|
210
|
-
* Spawning is the moment to record it, because every window in which a session
|
|
211
|
-
* is not yet tracked begins there.
|
|
212
|
-
*/
|
|
213
|
-
const liveAgentProcesses = new Set();
|
|
214
|
-
/** Stops tracking a process that has gone away on its own. */
|
|
215
|
-
function forgetAgentProcess(child) {
|
|
216
|
-
liveAgentProcesses.delete(child);
|
|
217
|
-
}
|
|
218
|
-
/** Forgets any in-flight startup session. For tests. */
|
|
219
|
-
export function resetIdleSession() {
|
|
220
|
-
idleSessionInFlight = null;
|
|
221
|
-
sessionsInFlight.clear();
|
|
222
|
-
liveAgentProcesses.clear();
|
|
223
|
-
}
|
|
24
|
+
import { describeAgentInfo } from "./agentInfo.js";
|
|
25
|
+
import { availableKinds, describeAgents, fetchRegistry, hostPlatformTarget, isAgentUnverified, } from "./registry.js";
|
|
26
|
+
import { extractModels, formatModelsText } from "./models.js";
|
|
27
|
+
import { MAX_MAX_CONCURRENCY, MIN_MAX_CONCURRENCY, normalizeConcurrency } from "./concurrency.js";
|
|
28
|
+
import { debug, followAgentStderr, isVerbose, setVerbose } from "./log.js";
|
|
29
|
+
import { pkg } from "./version.js";
|
|
30
|
+
/** How long a tool call waits for a human verdict by default: 30 minutes. */
|
|
31
|
+
export const DEFAULT_PERMISSION_TIMEOUT_MS = 30 * 60 * 1000;
|
|
224
32
|
/** How long to wait for `session/close` RPC before terminating the session process regardless. */
|
|
225
33
|
export const CLOSE_SESSION_TIMEOUT_MS = 2000;
|
|
226
34
|
/** Whether the agent advertised `session.close` capability during initialize. */
|
|
@@ -229,20 +37,10 @@ export function supportsCloseSession(agentCapabilities) {
|
|
|
229
37
|
return sessions?.close !== undefined && sessions?.close !== null && sessions?.close !== false;
|
|
230
38
|
}
|
|
231
39
|
/**
|
|
232
|
-
* Cleanly closes an
|
|
233
|
-
*
|
|
234
|
-
* 2. Calls `session/close` RPC on the connection if the agent supports it (with timeout).
|
|
235
|
-
* 3. Kills the agent child process.
|
|
40
|
+
* Cleanly closes an agent session: `session/close` if the agent supports it
|
|
41
|
+
* (bounded by a timeout), then the agent process itself.
|
|
236
42
|
*/
|
|
237
43
|
export async function closeSession(session, timeoutMs = CLOSE_SESSION_TIMEOUT_MS) {
|
|
238
|
-
if (session.acpClient && typeof session.acpClient.cancelTurn === "function") {
|
|
239
|
-
try {
|
|
240
|
-
await session.acpClient.cancelTurn(session.sessionId);
|
|
241
|
-
}
|
|
242
|
-
catch (err) {
|
|
243
|
-
console.error(`[acp] Error cancelling turn while closing session ${session.sessionId}:`, err);
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
44
|
if (supportsCloseSession(session.initResult?.agentCapabilities) &&
|
|
247
45
|
typeof session.connection?.closeSession === "function") {
|
|
248
46
|
try {
|
|
@@ -273,62 +71,6 @@ export async function closeSession(session, timeoutMs = CLOSE_SESSION_TIMEOUT_MS
|
|
|
273
71
|
session.acpClient?.dispose?.();
|
|
274
72
|
}
|
|
275
73
|
}
|
|
276
|
-
/**
|
|
277
|
-
* Cleanly closes all active sessions in parallel and clears the activeSessions map.
|
|
278
|
-
*/
|
|
279
|
-
export async function closeAllSessions(timeoutMs = CLOSE_SESSION_TIMEOUT_MS) {
|
|
280
|
-
const sessions = Array.from(new Set(activeSessions.values()));
|
|
281
|
-
activeSessions.clear();
|
|
282
|
-
if (sessions.length > 0) {
|
|
283
|
-
debug(`[acp] Cleanly closing ${sessions.length} active session(s)...`);
|
|
284
|
-
// Their processes are ended by closeSession; dropping them here keeps the
|
|
285
|
-
// count below honest about what is actually being left behind.
|
|
286
|
-
for (const session of sessions)
|
|
287
|
-
forgetAgentProcess(session.process);
|
|
288
|
-
await Promise.all(sessions.map((session) => closeSession(session, timeoutMs)));
|
|
289
|
-
}
|
|
290
|
-
// Whatever is still running never opened a session, so there is no session to
|
|
291
|
-
// close cleanly and nothing to say goodbye to — only a process to end. This
|
|
292
|
-
// is the agent that is still handshaking, or the one waiting on a login
|
|
293
|
-
// nobody is going to give it.
|
|
294
|
-
const stragglers = Array.from(liveAgentProcesses);
|
|
295
|
-
liveAgentProcesses.clear();
|
|
296
|
-
if (stragglers.length === 0)
|
|
297
|
-
return;
|
|
298
|
-
debug(`[acp] Ending ${stragglers.length} agent process(es) that never opened a session...`);
|
|
299
|
-
for (const child of stragglers) {
|
|
300
|
-
try {
|
|
301
|
-
terminateAgentProcess(child);
|
|
302
|
-
}
|
|
303
|
-
catch (err) {
|
|
304
|
-
console.error("[acp] Error ending an agent process:", err);
|
|
305
|
-
}
|
|
306
|
-
}
|
|
307
|
-
}
|
|
308
|
-
/**
|
|
309
|
-
* Registers signal handlers (SIGINT, SIGTERM) to trigger graceful shutdown.
|
|
310
|
-
* Returns a teardown function to unregister the handlers.
|
|
311
|
-
*/
|
|
312
|
-
export function setupSignalHandlers(onSignal) {
|
|
313
|
-
const sigintHandler = () => {
|
|
314
|
-
void onSignal("SIGINT");
|
|
315
|
-
};
|
|
316
|
-
const sigtermHandler = () => {
|
|
317
|
-
void onSignal("SIGTERM");
|
|
318
|
-
};
|
|
319
|
-
process.on("SIGINT", sigintHandler);
|
|
320
|
-
process.on("SIGTERM", sigtermHandler);
|
|
321
|
-
return () => {
|
|
322
|
-
process.off("SIGINT", sigintHandler);
|
|
323
|
-
process.off("SIGTERM", sigtermHandler);
|
|
324
|
-
};
|
|
325
|
-
}
|
|
326
|
-
/** Login preferences taken from the CLI, consulted whenever an agent demands auth. */
|
|
327
|
-
export const authConfig = {};
|
|
328
|
-
/** Model preference taken from the CLI, applied when a session starts. */
|
|
329
|
-
export const modelConfig = {};
|
|
330
|
-
/** How long tool calls wait for a human, taken from the CLI at startup. */
|
|
331
|
-
export const permissionConfig = {};
|
|
332
74
|
/**
|
|
333
75
|
* Whether a human is sitting in front of this process.
|
|
334
76
|
*
|
|
@@ -539,7 +281,7 @@ export function shouldPrintBanner(options) {
|
|
|
539
281
|
* `initialize` handshake, returning the connection plus what the agent said
|
|
540
282
|
* about itself — including the login methods it advertises.
|
|
541
283
|
*/
|
|
542
|
-
export async function openAgentConnection({ acpCmdArgs,
|
|
284
|
+
export async function openAgentConnection({ acpCmdArgs, env, label, cwd, }) {
|
|
543
285
|
const [cmd, ...cmdArgs] = acpCmdArgs;
|
|
544
286
|
debug(`[acp] Spawning agent for ${label}: ${cmd} ${cmdArgs.join(" ")}`);
|
|
545
287
|
const target = spawnTarget(cmd);
|
|
@@ -552,29 +294,19 @@ export async function openAgentConnection({ acpCmdArgs, mcpBridge, env, label, c
|
|
|
552
294
|
...(cwd === undefined ? {} : { cwd }),
|
|
553
295
|
});
|
|
554
296
|
const agentStderr = followAgentStderr(agentProcess.stderr);
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
const acpClient = new AgentRQACPClient(mcpBridge, () => currentTaskId, {
|
|
560
|
-
permissionTimeoutMs: permissionConfig.timeoutMs,
|
|
561
|
-
// A login URL that arrives before any session belongs to whoever asked for
|
|
562
|
-
// the login, and at a terminal that is the person reading it — so only
|
|
563
|
-
// offer the terminal prompt when there is a terminal to read it at.
|
|
297
|
+
const acpClient = new LocalACPClient({
|
|
298
|
+
// A login URL belongs to whoever asked for the login, and at a terminal
|
|
299
|
+
// that is the person reading it — so only offer the terminal prompt when
|
|
300
|
+
// there is a terminal to read it at.
|
|
564
301
|
promptUrlElicitation: isInteractiveTerminal() ? promptUrlElicitationOnTerminal : undefined,
|
|
565
302
|
});
|
|
566
303
|
// Guard against unhandled child-process failures. Without these listeners a
|
|
567
|
-
// crashed agent
|
|
568
|
-
//
|
|
569
|
-
// Tracked from here rather than from the open session, so shutdown can still
|
|
570
|
-
// end an agent that never reached one — see liveAgentProcesses.
|
|
571
|
-
liveAgentProcesses.add(agentProcess);
|
|
304
|
+
// crashed agent leaves a broken stdin pipe; the next write raises EPIPE as an
|
|
305
|
+
// uncaught error and takes the gateway down with it.
|
|
572
306
|
agentProcess.on("error", (err) => {
|
|
573
307
|
console.error(`[acp] Agent process error for ${label}:`, err.message);
|
|
574
308
|
showAgentStderr(agentStderr());
|
|
575
|
-
forgetAgentProcess(agentProcess);
|
|
576
309
|
acpClient.dispose();
|
|
577
|
-
onExit?.();
|
|
578
310
|
});
|
|
579
311
|
agentProcess.on("exit", (code, signal) => {
|
|
580
312
|
const message = `[acp] Agent process for ${label} exited (code=${code}, signal=${signal})`;
|
|
@@ -585,11 +317,7 @@ export async function openAgentConnection({ acpCmdArgs, mcpBridge, env, label, c
|
|
|
585
317
|
else {
|
|
586
318
|
debug(message);
|
|
587
319
|
}
|
|
588
|
-
forgetAgentProcess(agentProcess);
|
|
589
|
-
// Nothing will act on these answers now, but the tool calls waiting on them
|
|
590
|
-
// are holding task-queue slots that would never be given back.
|
|
591
320
|
acpClient.dispose();
|
|
592
|
-
onExit?.();
|
|
593
321
|
});
|
|
594
322
|
// stdin can emit EPIPE when the child dies mid-write; swallow it so it
|
|
595
323
|
// doesn't surface as an uncaught exception.
|
|
@@ -600,9 +328,6 @@ export async function openAgentConnection({ acpCmdArgs, mcpBridge, env, label, c
|
|
|
600
328
|
const output = Readable.toWeb(agentProcess.stdout);
|
|
601
329
|
const stream = acp.ndJsonStream(input, output);
|
|
602
330
|
const connection = new acp.ClientSideConnection((_agent) => acpClient, stream);
|
|
603
|
-
// Stopping a turn is only possible once the connection exists, and the
|
|
604
|
-
// connection is built around the client — so it is handed over afterwards.
|
|
605
|
-
acpClient.setSessionCanceller((sessionId) => connection.cancel({ sessionId }));
|
|
606
331
|
const initResult = await connection.initialize({
|
|
607
332
|
protocolVersion: acp.PROTOCOL_VERSION,
|
|
608
333
|
clientInfo: {
|
|
@@ -610,15 +335,9 @@ export async function openAgentConnection({ acpCmdArgs, mcpBridge, env, label, c
|
|
|
610
335
|
version: pkg.version,
|
|
611
336
|
},
|
|
612
337
|
clientCapabilities: {
|
|
613
|
-
fs: {
|
|
614
|
-
readTextFile: true,
|
|
615
|
-
writeTextFile: true,
|
|
616
|
-
},
|
|
617
338
|
elicitation: {
|
|
618
|
-
form: {},
|
|
619
339
|
url: {},
|
|
620
340
|
},
|
|
621
|
-
plan: {},
|
|
622
341
|
// Only claim terminal logins when we can actually hand the agent a
|
|
623
342
|
// terminal; otherwise the agent may offer a method we cannot run.
|
|
624
343
|
auth: {
|
|
@@ -640,9 +359,6 @@ export async function openAgentConnection({ acpCmdArgs, mcpBridge, env, label, c
|
|
|
640
359
|
connection,
|
|
641
360
|
acpClient,
|
|
642
361
|
initResult,
|
|
643
|
-
assignTask: (id) => {
|
|
644
|
-
currentTaskId = id;
|
|
645
|
-
},
|
|
646
362
|
};
|
|
647
363
|
}
|
|
648
364
|
/**
|
|
@@ -692,881 +408,6 @@ export class AuthenticationFailed extends Error {
|
|
|
692
408
|
this.name = "AuthenticationFailed";
|
|
693
409
|
}
|
|
694
410
|
}
|
|
695
|
-
export async function getOrCreateSession(taskId, acpCmdArgs, configs, agentrqConfig, mcpBridge) {
|
|
696
|
-
const sessionKey = taskId || IDLE_SESSION_KEY;
|
|
697
|
-
const existing = activeSessions.get(sessionKey);
|
|
698
|
-
if (existing) {
|
|
699
|
-
return existing;
|
|
700
|
-
}
|
|
701
|
-
// Someone already asked for this session and is still waiting for it. Join
|
|
702
|
-
// that wait rather than starting a second agent for the same work — the
|
|
703
|
-
// caller wants a session for this task, not a session of its own.
|
|
704
|
-
const pending = sessionsInFlight.get(sessionKey);
|
|
705
|
-
if (pending) {
|
|
706
|
-
debug(`[acp] A session for ${taskId ? `task ${taskId}` : "the idle session"} is ` +
|
|
707
|
-
`already being opened; waiting for it rather than spawning a second agent`);
|
|
708
|
-
return pending;
|
|
709
|
-
}
|
|
710
|
-
const creation = createSession(taskId, sessionKey, acpCmdArgs, configs, agentrqConfig, mcpBridge);
|
|
711
|
-
sessionsInFlight.set(sessionKey, creation);
|
|
712
|
-
try {
|
|
713
|
-
return await creation;
|
|
714
|
-
}
|
|
715
|
-
finally {
|
|
716
|
-
// Only if it is still this attempt's: a session that was adopted and then
|
|
717
|
-
// re-requested may have registered a newer one under the same key.
|
|
718
|
-
if (sessionsInFlight.get(sessionKey) === creation) {
|
|
719
|
-
sessionsInFlight.delete(sessionKey);
|
|
720
|
-
}
|
|
721
|
-
}
|
|
722
|
-
}
|
|
723
|
-
/** Opens a session, with no regard for whether one is already on its way. */
|
|
724
|
-
async function createSession(taskId, initialSessionKey, acpCmdArgs, configs, agentrqConfig, mcpBridge) {
|
|
725
|
-
let sessionKey = initialSessionKey;
|
|
726
|
-
// The session made at startup, before any task, is handed to the first task
|
|
727
|
-
// that arrives rather than left beside a second agent doing the same job. Its
|
|
728
|
-
// conversation is empty, so there is nothing for the task to inherit but the
|
|
729
|
-
// process itself.
|
|
730
|
-
if (taskId) {
|
|
731
|
-
// Still coming up — wait for it rather than racing it into a second agent.
|
|
732
|
-
if (idleSessionInFlight) {
|
|
733
|
-
try {
|
|
734
|
-
await idleSessionInFlight;
|
|
735
|
-
}
|
|
736
|
-
catch {
|
|
737
|
-
// It failed; this task opens its own below, and reports the failure
|
|
738
|
-
// itself rather than inheriting a stale one.
|
|
739
|
-
}
|
|
740
|
-
}
|
|
741
|
-
const idle = activeSessions.get(IDLE_SESSION_KEY);
|
|
742
|
-
if (idle) {
|
|
743
|
-
idle.adopt(taskId);
|
|
744
|
-
debug(`[acp] Task ${taskId} took over the session opened at startup`);
|
|
745
|
-
const lastModels = idle.acpClient.lastModelsFor(idle.sessionId);
|
|
746
|
-
if (lastModels) {
|
|
747
|
-
void idle.acpClient.sendModelsToWorkspace(idle.sessionId, lastModels);
|
|
748
|
-
}
|
|
749
|
-
return idle;
|
|
750
|
-
}
|
|
751
|
-
}
|
|
752
|
-
const [cmd, ...cmdArgs] = acpCmdArgs;
|
|
753
|
-
const { process: agentProcess, connection, acpClient, initResult, assignTask } = await openAgentConnection({
|
|
754
|
-
acpCmdArgs,
|
|
755
|
-
mcpBridge,
|
|
756
|
-
env: agentrqConfig.env,
|
|
757
|
-
label: taskId ? `task ${taskId}` : "the idle session",
|
|
758
|
-
taskId,
|
|
759
|
-
onExit: () => activeSessions.delete(sessionKey),
|
|
760
|
-
});
|
|
761
|
-
const newSessionParams = {
|
|
762
|
-
cwd: process.cwd(),
|
|
763
|
-
mcpServers: mapMcpServers(configs, initResult.agentCapabilities),
|
|
764
|
-
};
|
|
765
|
-
// From here on the agent is running but nothing is tracking it yet: it only
|
|
766
|
-
// reaches activeSessions once a session exists, and closeAllSessions can only
|
|
767
|
-
// close what is in there. So anything that goes wrong in between has to take
|
|
768
|
-
// the process with it, or it is left running with nothing attached — an agent
|
|
769
|
-
// that quits when its stdin closes gets away with it, and one with its own
|
|
770
|
-
// event loop, which is the sort that wants a login, does not.
|
|
771
|
-
try {
|
|
772
|
-
// An agent that demands authentication stops here and waits, including at
|
|
773
|
-
// startup — that is the point of starting a session then. A terminal is where
|
|
774
|
-
// someone can actually answer, and finding out on the first task instead
|
|
775
|
-
// means a gateway that looked connected all along.
|
|
776
|
-
//
|
|
777
|
-
// Headless, `login` refuses rather than blocking on a prompt nobody can see:
|
|
778
|
-
// it only offers a terminal method to an interactive terminal, and throws a
|
|
779
|
-
// message naming --auth-method otherwise. openIdleSession logs that and
|
|
780
|
-
// leaves the gateway up.
|
|
781
|
-
const sessionResult = await createSessionWithAuth(connection, newSessionParams, {
|
|
782
|
-
methods: initResult.authMethods,
|
|
783
|
-
launch: { command: cmd, args: cmdArgs, env: agentrqConfig.env },
|
|
784
|
-
preferredId: authConfig.methodId,
|
|
785
|
-
interactive: isInteractiveTerminal(),
|
|
786
|
-
});
|
|
787
|
-
debug(`[acp] Created session ${sessionResult.sessionId} for ${taskId ? `task ${taskId}` : "the idle session"}`);
|
|
788
|
-
// Tell the workspace which agent this actually is. Its MCP client is this
|
|
789
|
-
// gateway, so without this the workspace can only ever name the bridge.
|
|
790
|
-
void acpClient.sendAgentToWorkspace(sessionResult.sessionId, agentIdentity(initResult, acpCmdArgs.join(" ")));
|
|
791
|
-
try {
|
|
792
|
-
const modelsResult = extractModels(sessionResult.configOptions);
|
|
793
|
-
if (modelsResult) {
|
|
794
|
-
await applyModelSelection({
|
|
795
|
-
connection,
|
|
796
|
-
acpClient,
|
|
797
|
-
sessionId: sessionResult.sessionId,
|
|
798
|
-
known: modelsResult,
|
|
799
|
-
requested: modelConfig.modelId,
|
|
800
|
-
});
|
|
801
|
-
}
|
|
802
|
-
}
|
|
803
|
-
catch (err) {
|
|
804
|
-
console.error(`[acp] Failed to extract or configure models for session ${sessionResult.sessionId}:`, err);
|
|
805
|
-
}
|
|
806
|
-
await enforceHumanApprovalMode(connection, sessionResult);
|
|
807
|
-
// The mode is pinned once here, but agents may move themselves back out of
|
|
808
|
-
// it, so keep watching for the rest of the session's life.
|
|
809
|
-
acpClient.setModeChangeHandler((changedSessionId, modeId) => handleAgentModeChange(connection, changedSessionId, modeId, sessionResult.modes));
|
|
810
|
-
const sessionInfo = {
|
|
811
|
-
process: agentProcess,
|
|
812
|
-
connection,
|
|
813
|
-
acpClient,
|
|
814
|
-
sessionId: sessionResult.sessionId,
|
|
815
|
-
initResult,
|
|
816
|
-
adopt(nextTaskId) {
|
|
817
|
-
activeSessions.delete(sessionKey);
|
|
818
|
-
sessionKey = nextTaskId;
|
|
819
|
-
activeSessions.set(sessionKey, sessionInfo);
|
|
820
|
-
assignTask?.(nextTaskId);
|
|
821
|
-
},
|
|
822
|
-
};
|
|
823
|
-
activeSessions.set(sessionKey, sessionInfo);
|
|
824
|
-
return sessionInfo;
|
|
825
|
-
}
|
|
826
|
-
catch (err) {
|
|
827
|
-
terminateAgentProcess(agentProcess);
|
|
828
|
-
throw err;
|
|
829
|
-
}
|
|
830
|
-
}
|
|
831
|
-
/**
|
|
832
|
-
* Finds the active agent session for a given task ID (or returns the single active session if none specified).
|
|
833
|
-
*/
|
|
834
|
-
/**
|
|
835
|
-
* Opens a session before any task, so the workspace can say what this agent
|
|
836
|
-
* offers rather than only that something is attached.
|
|
837
|
-
*
|
|
838
|
-
* Models arrive as config options on `session/new` and slash commands as a
|
|
839
|
-
* session notification, so there is no way to learn either without a session —
|
|
840
|
-
* ACP has no question to ask outside one.
|
|
841
|
-
*
|
|
842
|
-
* An agent that demands authentication stops and waits here, which is much of
|
|
843
|
-
* the value of starting a session at all: the terminal someone just typed into
|
|
844
|
-
* is where they can answer.
|
|
845
|
-
*
|
|
846
|
-
* If that login does not happen — refused, or headless where there is nobody to
|
|
847
|
-
* ask — the gateway shuts down rather than carrying on. It would otherwise sit
|
|
848
|
-
* there looking connected, take every task the workspace gave it and fail all
|
|
849
|
-
* of them, which is worse than not running: the workspace would show a live
|
|
850
|
-
* agent while the work quietly went nowhere.
|
|
851
|
-
*
|
|
852
|
-
* Every other failure is survivable and is survived. An agent that could not be
|
|
853
|
-
* spawned may simply have lost a race; it used to fail when the first task
|
|
854
|
-
* arrived and it still does, and turning that into a gateway that refuses to
|
|
855
|
-
* run would be a worse trade than the one this is making.
|
|
856
|
-
*
|
|
857
|
-
* The session is handed to the first task rather than left running beside it —
|
|
858
|
-
* see getOrCreateSession.
|
|
859
|
-
*/
|
|
860
|
-
export async function openIdleSession(acpCmdArgs, configs, agentrqConfig, mcpBridge, loginCommand = loginCommandFor(), timeoutMs = IDLE_SESSION_TIMEOUT_MS) {
|
|
861
|
-
try {
|
|
862
|
-
// Cleared when the session itself settles rather than when this returns:
|
|
863
|
-
// after a timeout the session is still coming, and a task that arrives
|
|
864
|
-
// meanwhile should still wait for it instead of starting a second agent.
|
|
865
|
-
idleSessionInFlight = getOrCreateSession(undefined, acpCmdArgs, configs, agentrqConfig, mcpBridge);
|
|
866
|
-
const settled = idleSessionInFlight;
|
|
867
|
-
void settled.catch(() => { }).finally(() => {
|
|
868
|
-
if (idleSessionInFlight === settled)
|
|
869
|
-
idleSessionInFlight = null;
|
|
870
|
-
});
|
|
871
|
-
// Bounded: nothing reaches the workspace until this settles, so an agent
|
|
872
|
-
// that spawns and then never answers its handshake would otherwise take the
|
|
873
|
-
// whole gateway down with it — a worse failure than the one being fixed,
|
|
874
|
-
// and a new one. On a timeout the gateway carries on; the session may still
|
|
875
|
-
// arrive, and the first task will adopt it if it does.
|
|
876
|
-
const timedOut = Symbol("timed out");
|
|
877
|
-
let timer;
|
|
878
|
-
const result = await Promise.race([
|
|
879
|
-
idleSessionInFlight,
|
|
880
|
-
new Promise((resolve) => {
|
|
881
|
-
timer = setTimeout(() => resolve(timedOut), timeoutMs);
|
|
882
|
-
}),
|
|
883
|
-
]);
|
|
884
|
-
if (timer)
|
|
885
|
-
clearTimeout(timer);
|
|
886
|
-
if (result === timedOut) {
|
|
887
|
-
console.error(`[acp] The agent has not opened a session after ${Math.round(timeoutMs / 1000)}s; ` +
|
|
888
|
-
"carrying on without knowing what it offers.");
|
|
889
|
-
return "unknown";
|
|
890
|
-
}
|
|
891
|
-
return "ready";
|
|
892
|
-
}
|
|
893
|
-
catch (err) {
|
|
894
|
-
if (err instanceof AuthenticationFailed || isAuthRequiredError(err)) {
|
|
895
|
-
const remedy = err instanceof AuthenticationFailed && !err.hasLogin
|
|
896
|
-
? `It offers no way to log in through acp-gateway, so it is expecting a credential ` +
|
|
897
|
-
`of its own — an API key in the environment, or whatever its own documentation ` +
|
|
898
|
-
`asks for. Set that and start acp-gateway again.`
|
|
899
|
-
: `Log in with:\n\n ${loginCommand}\n\nthen start acp-gateway again.`;
|
|
900
|
-
console.error(`\n[acp-gateway] The agent will not start a session until it is authenticated: ` +
|
|
901
|
-
`${err instanceof Error ? err.message : String(err)}\n` +
|
|
902
|
-
`Nothing was started. ${remedy}\n` +
|
|
903
|
-
`Carrying on would leave the workspace showing a live agent that fails every task ` +
|
|
904
|
-
`it is given.`);
|
|
905
|
-
return "unauthenticated";
|
|
906
|
-
}
|
|
907
|
-
console.error("[acp] Could not open a session to learn what the agent offers; " +
|
|
908
|
-
"the first task will start one:", err instanceof Error ? err.message : String(err));
|
|
909
|
-
return "unknown";
|
|
910
|
-
}
|
|
911
|
-
}
|
|
912
|
-
/**
|
|
913
|
-
* The command that logs this agent in, so the message can name it rather than
|
|
914
|
-
* leave someone to work it out.
|
|
915
|
-
*
|
|
916
|
-
* Built from how the gateway itself was started: the registry id when there was
|
|
917
|
-
* one, and otherwise the command after `--`, since that is the only handle on
|
|
918
|
-
* an agent nobody named.
|
|
919
|
-
*/
|
|
920
|
-
export function loginCommandFor(agentId, agentCommand = []) {
|
|
921
|
-
const base = "npx @agentrq/acp-gateway@latest --login";
|
|
922
|
-
if (agentId)
|
|
923
|
-
return `${base} --agent ${agentId}`;
|
|
924
|
-
if (agentCommand.length)
|
|
925
|
-
return `${base} -- ${agentCommand.join(" ")}`;
|
|
926
|
-
return base;
|
|
927
|
-
}
|
|
928
|
-
/**
|
|
929
|
-
* How long to wait for an agent to open its first session.
|
|
930
|
-
*
|
|
931
|
-
* Generous because the wait includes starting the agent, and an `npx`
|
|
932
|
-
* distribution downloads its package the first time it is spawned — a cold
|
|
933
|
-
* install of a large one on a slow line is minutes, not seconds. (A registry
|
|
934
|
-
* *binary* is already on disk by now: that download happens while the launch
|
|
935
|
-
* command is being resolved, before any of this.)
|
|
936
|
-
*
|
|
937
|
-
* Erring long costs little. A session that arrives after the deadline is still
|
|
938
|
-
* recorded, still reports what the agent offers, and is still adopted by the
|
|
939
|
-
* first task — the timeout only decides how long the gateway waits before
|
|
940
|
-
* connecting to the workspace without knowing those things yet.
|
|
941
|
-
*/
|
|
942
|
-
export const IDLE_SESSION_TIMEOUT_MS = 5 * 60_000;
|
|
943
|
-
export function findActiveSession(taskId) {
|
|
944
|
-
if (taskId) {
|
|
945
|
-
const direct = activeSessions.get(taskId);
|
|
946
|
-
if (direct)
|
|
947
|
-
return direct;
|
|
948
|
-
for (const session of activeSessions.values()) {
|
|
949
|
-
if (session.sessionId === taskId)
|
|
950
|
-
return session;
|
|
951
|
-
}
|
|
952
|
-
// A session opened from a notification that carried no task id is keyed
|
|
953
|
-
// under IDLE_SESSION_KEY; when it is the only one running, an id-carrying
|
|
954
|
-
// cancel can only have meant it. Never fall back to a session keyed under a
|
|
955
|
-
// *different* task id — that would abort an unrelated task.
|
|
956
|
-
//
|
|
957
|
-
// The session opened at startup shares that key until a task adopts it, so
|
|
958
|
-
// this can now match one that has never run anything. That stays correct
|
|
959
|
-
// either way: if it was reused for a task-less prompt it is the session the
|
|
960
|
-
// cancel meant, and if it is untouched it has no turn to cancel.
|
|
961
|
-
const untracked = activeSessions.get(IDLE_SESSION_KEY);
|
|
962
|
-
if (untracked && activeSessions.size === 1) {
|
|
963
|
-
return untracked;
|
|
964
|
-
}
|
|
965
|
-
}
|
|
966
|
-
else if (activeSessions.size === 1) {
|
|
967
|
-
return activeSessions.values().next().value;
|
|
968
|
-
}
|
|
969
|
-
return undefined;
|
|
970
|
-
}
|
|
971
|
-
/**
|
|
972
|
-
* Switches a session's model and tells the workspace what it ended up as.
|
|
973
|
-
*
|
|
974
|
-
* The one place a model is ever set, reached from two directions: the --model
|
|
975
|
-
* flag as a session opens, and a selection made in the interface while it is
|
|
976
|
-
* running. They were one block until the second existed; keeping two copies of
|
|
977
|
-
* resolve-set-echo would have let the startup path and the runtime path drift
|
|
978
|
-
* into disagreeing about what a failed switch looks like.
|
|
979
|
-
*
|
|
980
|
-
* Whatever happens, the workspace is told something. That is the contract the
|
|
981
|
-
* interface is built on: it marks a chosen model pending and waits for a models
|
|
982
|
-
* notification to settle it, so a switch that quietly failed would leave the
|
|
983
|
-
* picker claiming a model the agent never adopted. Every path below ends in a
|
|
984
|
-
* report — the new list on success, the old one on any failure.
|
|
985
|
-
*/
|
|
986
|
-
export async function applyModelSelection({ connection, acpClient, sessionId, known, requested, configId, }) {
|
|
987
|
-
// Freshest first. `known` was read before the set was attempted, and the agent
|
|
988
|
-
// may have reported a different list while that call was in flight — echoing
|
|
989
|
-
// the older snapshot would tell the workspace the session is on a model it has
|
|
990
|
-
// already left, and, because every report is recorded, would write that stale
|
|
991
|
-
// list back over the newer one. The cache is preferred over it for that reason,
|
|
992
|
-
// and `known` stays as the last resort for the startup path, where the session
|
|
993
|
-
// has not reported anything yet.
|
|
994
|
-
const echo = (result) => {
|
|
995
|
-
const fallback = result ?? acpClient.lastModelsFor(sessionId) ?? known;
|
|
996
|
-
if (fallback)
|
|
997
|
-
void acpClient.sendModelsToWorkspace(sessionId, fallback);
|
|
998
|
-
};
|
|
999
|
-
// Nothing asked for, or already the current model: report and stop. Setting a
|
|
1000
|
-
// model the session is already on would be a needless round trip to the agent
|
|
1001
|
-
// for an answer nobody is waiting on.
|
|
1002
|
-
if (!requested || (known && requested === known.currentModelId)) {
|
|
1003
|
-
echo();
|
|
1004
|
-
return;
|
|
1005
|
-
}
|
|
1006
|
-
// Resolved by display name as well as by id, because --model is typed by a
|
|
1007
|
-
// human who may well have copied what the picker showed them. A selection
|
|
1008
|
-
// from the interface always carries an id and matches on the first branch.
|
|
1009
|
-
const target = known?.models.find((m) => m.id === requested || m.name === requested);
|
|
1010
|
-
if (known && !target) {
|
|
1011
|
-
console.error(`[acp] Requested model "${requested}" not found in available models: ${known.models.map((m) => m.id).join(", ")}`);
|
|
1012
|
-
echo();
|
|
1013
|
-
return;
|
|
1014
|
-
}
|
|
1015
|
-
const option = configId ?? known?.configId;
|
|
1016
|
-
if (!option) {
|
|
1017
|
-
console.error(`[acp] Cannot set model "${requested}" for session ${sessionId}: no config option to write it to`);
|
|
1018
|
-
echo();
|
|
1019
|
-
return;
|
|
1020
|
-
}
|
|
1021
|
-
const modelId = target?.id ?? requested;
|
|
1022
|
-
try {
|
|
1023
|
-
const updateRes = await setSessionModel(connection, sessionId, option, modelId);
|
|
1024
|
-
// The agent's own answer is preferred over anything assumed here — it is
|
|
1025
|
-
// what actually took effect. The constructed fallback is for agents that
|
|
1026
|
-
// answer without repeating their config, and marks the chosen model current
|
|
1027
|
-
// rather than leaving the interface with nothing selected.
|
|
1028
|
-
const updated = extractModels(updateRes.configOptions) ??
|
|
1029
|
-
(known
|
|
1030
|
-
? {
|
|
1031
|
-
...known,
|
|
1032
|
-
currentModelId: modelId,
|
|
1033
|
-
models: known.models.map((m) => ({ ...m, current: m.id === modelId })),
|
|
1034
|
-
}
|
|
1035
|
-
: undefined);
|
|
1036
|
-
echo(updated);
|
|
1037
|
-
}
|
|
1038
|
-
catch (err) {
|
|
1039
|
-
console.error(`[acp] Failed to set requested model "${requested}":`, err);
|
|
1040
|
-
echo();
|
|
1041
|
-
}
|
|
1042
|
-
}
|
|
1043
|
-
/**
|
|
1044
|
-
* Switches model on a session the workspace names, at the workspace's request.
|
|
1045
|
-
*
|
|
1046
|
-
* The session id on the wire is the agent's own, which is what activeSessions
|
|
1047
|
-
* is searched by — findActiveSession already matches on it, and on the task id
|
|
1048
|
-
* a session is filed under, so either identifies the same session.
|
|
1049
|
-
*
|
|
1050
|
-
* A set for a session that has gone still answers, and so does one that names no
|
|
1051
|
-
* model. The interface is holding a pending model and only a models notification
|
|
1052
|
-
* releases it, so staying silent about either would leave it pending forever;
|
|
1053
|
-
* echoing what was last known lets it revert to the truth. That is why the last
|
|
1054
|
-
* report outlives the session that produced it — by the time a set arrives for a
|
|
1055
|
-
* finished session, the client that served it has exited with its agent, and the
|
|
1056
|
-
* bridge is all that is left to answer through.
|
|
1057
|
-
*/
|
|
1058
|
-
export async function handleSetModel({ sessionId, configId, modelId, },
|
|
1059
|
-
/** How a session that has already gone is answered. Absent only in tests. */
|
|
1060
|
-
bridge) {
|
|
1061
|
-
const session = findActiveSession(sessionId);
|
|
1062
|
-
// Nothing to switch, but the picker is still waiting on an answer, so give it
|
|
1063
|
-
// the truth rather than nothing: a live session reports through its own client,
|
|
1064
|
-
// and a finished one through whatever was last recorded for it.
|
|
1065
|
-
const revert = async (why) => {
|
|
1066
|
-
console.error(`[bridge] ${why}; reporting the last known models instead`);
|
|
1067
|
-
if (session) {
|
|
1068
|
-
const last = session.acpClient.lastModelsFor(session.sessionId);
|
|
1069
|
-
if (last)
|
|
1070
|
-
await session.acpClient.sendModelsToWorkspace(session.sessionId, last);
|
|
1071
|
-
return;
|
|
1072
|
-
}
|
|
1073
|
-
const last = sessionId ? lastModelsForSession(sessionId) : undefined;
|
|
1074
|
-
if (bridge && sessionId && last) {
|
|
1075
|
-
await sendModelsNotification(bridge, sessionId, last);
|
|
1076
|
-
}
|
|
1077
|
-
};
|
|
1078
|
-
if (!modelId) {
|
|
1079
|
-
await revert("Received a set_model notification naming no model");
|
|
1080
|
-
return;
|
|
1081
|
-
}
|
|
1082
|
-
if (!session) {
|
|
1083
|
-
await revert(`Received set_model for session ${sessionId ?? "(unnamed)"}, but no active session matches it`);
|
|
1084
|
-
return;
|
|
1085
|
-
}
|
|
1086
|
-
debug(`[bridge] Switching session ${session.sessionId} to model "${modelId}"`);
|
|
1087
|
-
await applyModelSelection({
|
|
1088
|
-
connection: session.connection,
|
|
1089
|
-
acpClient: session.acpClient,
|
|
1090
|
-
sessionId: session.sessionId,
|
|
1091
|
-
known: session.acpClient.lastModelsFor(session.sessionId),
|
|
1092
|
-
requested: modelId,
|
|
1093
|
-
configId,
|
|
1094
|
-
});
|
|
1095
|
-
}
|
|
1096
|
-
/**
|
|
1097
|
-
* Applies a concurrency limit the workspace asked for, and reports back the one
|
|
1098
|
-
* actually in force.
|
|
1099
|
-
*
|
|
1100
|
-
* The report is unconditional, which is the whole point of it. Someone moved a
|
|
1101
|
-
* control in the interface and is watching to see where it landed; a value that
|
|
1102
|
-
* was clamped, or one that was not a number at all, has to come back as the
|
|
1103
|
-
* real limit rather than as silence — otherwise the interface goes on showing a
|
|
1104
|
-
* number this gateway never adopted.
|
|
1105
|
-
*/
|
|
1106
|
-
export async function handleSetConcurrency({ maxConcurrency }, queue,
|
|
1107
|
-
/** Absent only in tests. */
|
|
1108
|
-
bridge) {
|
|
1109
|
-
const requested = normalizeConcurrency(maxConcurrency);
|
|
1110
|
-
// In a finally, so the answer does not depend on applying the change going
|
|
1111
|
-
// well. "Always answered" is the whole design; leaving it as the last
|
|
1112
|
-
// statement made it true only while nothing above it threw.
|
|
1113
|
-
try {
|
|
1114
|
-
if (requested === undefined) {
|
|
1115
|
-
console.error(`[bridge] Received a set_concurrency notification asking for ` +
|
|
1116
|
-
`"${String(maxConcurrency)}", which is not a number of tasks; ` +
|
|
1117
|
-
`keeping the limit at ${queue.getMaxConcurrency()}`);
|
|
1118
|
-
}
|
|
1119
|
-
else {
|
|
1120
|
-
queue.setMaxConcurrency(requested);
|
|
1121
|
-
}
|
|
1122
|
-
}
|
|
1123
|
-
finally {
|
|
1124
|
-
// Often asked for while the queue's own reports are still going out —
|
|
1125
|
-
// raising the limit starts waiting tasks, and each announces itself. That
|
|
1126
|
-
// is why this is here anyway: the queue says nothing at all when a set
|
|
1127
|
-
// moves no numbers, and a set must always be answered.
|
|
1128
|
-
//
|
|
1129
|
-
// Awaiting it is what makes the answer real. Reports go out one at a time,
|
|
1130
|
-
// and this resolves only once no further report is wanted, so by the time
|
|
1131
|
-
// it returns the workspace has been told the limit that actually took
|
|
1132
|
-
// effect — after, not before, anything the raise set running.
|
|
1133
|
-
if (bridge)
|
|
1134
|
-
await reportConcurrency(bridge, queue);
|
|
1135
|
-
}
|
|
1136
|
-
}
|
|
1137
|
-
/**
|
|
1138
|
-
* The report on the wire, if one is, and whether the numbers moved while it flew.
|
|
1139
|
-
*
|
|
1140
|
-
* Each report is its own HTTP POST, and two in flight at once may be processed
|
|
1141
|
-
* in either order — so the workspace would be left showing whichever landed
|
|
1142
|
-
* last rather than whichever is true. That cost little while a report followed
|
|
1143
|
-
* a human moving a control. It costs a great deal now that one follows every
|
|
1144
|
-
* task transition, because `execute` announces a freed slot and then `next()`
|
|
1145
|
-
* immediately announces the task that took it: two reports, one tick apart,
|
|
1146
|
-
* disagreeing about the same number. Landing them the wrong way round leaves
|
|
1147
|
-
* the interface wrong until something else moves — which is the very failure
|
|
1148
|
-
* this feature exists to end.
|
|
1149
|
-
*/
|
|
1150
|
-
let reportOnTheWire = null;
|
|
1151
|
-
let numbersMovedAgain = false;
|
|
1152
|
-
/** Forgets any report in flight. For tests. */
|
|
1153
|
-
export function resetConcurrencyReports() {
|
|
1154
|
-
reportOnTheWire = null;
|
|
1155
|
-
numbersMovedAgain = false;
|
|
1156
|
-
}
|
|
1157
|
-
/**
|
|
1158
|
-
* Tells the workspace what the queue's limit is and what it is doing under it.
|
|
1159
|
-
*
|
|
1160
|
-
* One report at a time, so they arrive in the order they were asked for. A
|
|
1161
|
-
* report wanted while one is flying does not queue up behind it: the numbers
|
|
1162
|
-
* are read again when the wire is free, so a burst of transitions costs one
|
|
1163
|
-
* further report rather than one per transition, and every report carries the
|
|
1164
|
-
* state at the moment it was actually sent. Whatever the workspace hears last
|
|
1165
|
-
* is therefore the truth, which is the only property that really matters here.
|
|
1166
|
-
*
|
|
1167
|
-
* Callers may await this and know a report reflecting their change has gone
|
|
1168
|
-
* out — `handleSetConcurrency` depends on exactly that.
|
|
1169
|
-
*/
|
|
1170
|
-
export function reportConcurrency(bridge, queue) {
|
|
1171
|
-
if (reportOnTheWire) {
|
|
1172
|
-
numbersMovedAgain = true;
|
|
1173
|
-
return reportOnTheWire;
|
|
1174
|
-
}
|
|
1175
|
-
// Assigned from the call rather than after it: `drainConcurrencyReports` runs
|
|
1176
|
-
// as far as its first await before returning, and nothing else can run in
|
|
1177
|
-
// between.
|
|
1178
|
-
return (reportOnTheWire = drainConcurrencyReports(bridge, queue));
|
|
1179
|
-
}
|
|
1180
|
-
/**
|
|
1181
|
-
* Sends reports until nobody has asked for another.
|
|
1182
|
-
*
|
|
1183
|
-
* The slot is cleared in a `finally` inside this function rather than off the
|
|
1184
|
-
* returned promise, so that it happens in the same tick the loop ends. Clearing
|
|
1185
|
-
* it a microtask later would leave a window where a caller sees a report in
|
|
1186
|
-
* flight, sets the flag, and is answered by a loop that has already stopped
|
|
1187
|
-
* reading it — a report asked for and never sent.
|
|
1188
|
-
*
|
|
1189
|
-
* The bridge is whichever caller opened the slot. The gateway has exactly one
|
|
1190
|
-
* for its whole life, and a reconnect replaces what is inside it rather than
|
|
1191
|
-
* the object, so there is no second bridge for a collapsed report to miss.
|
|
1192
|
-
*/
|
|
1193
|
-
async function drainConcurrencyReports(bridge, queue) {
|
|
1194
|
-
try {
|
|
1195
|
-
do {
|
|
1196
|
-
numbersMovedAgain = false;
|
|
1197
|
-
// Read here, not at the call: a collapsed report is worth sending only
|
|
1198
|
-
// because it describes the queue now rather than when it was asked for.
|
|
1199
|
-
await sendConcurrencyNotification(bridge, {
|
|
1200
|
-
maxConcurrency: queue.getMaxConcurrency(),
|
|
1201
|
-
active: queue.getActiveCount(),
|
|
1202
|
-
queued: queue.getQueueLength(),
|
|
1203
|
-
});
|
|
1204
|
-
} while (numbersMovedAgain);
|
|
1205
|
-
}
|
|
1206
|
-
finally {
|
|
1207
|
-
reportOnTheWire = null;
|
|
1208
|
-
}
|
|
1209
|
-
}
|
|
1210
|
-
/**
|
|
1211
|
-
* Builds the task queue already able to report itself.
|
|
1212
|
-
*
|
|
1213
|
-
* Out here rather than inline in `main()` for the reason
|
|
1214
|
-
* `registerConcurrencyListeners` is: `main()` spawns processes and never
|
|
1215
|
-
* returns, so nothing written inside it can be tested, and wiring that nothing
|
|
1216
|
-
* exercises is wiring nobody finds out is wrong.
|
|
1217
|
-
*
|
|
1218
|
-
* The callback names the queue it is being handed to. That is safe because it
|
|
1219
|
-
* only ever runs later, from inside the queue's own methods, by which time the
|
|
1220
|
-
* binding exists.
|
|
1221
|
-
*/
|
|
1222
|
-
export function createTaskQueue(maxConcurrency, bridge,
|
|
1223
|
-
/**
|
|
1224
|
-
* Told when the queue may have room for another task, so the caller can go
|
|
1225
|
-
* and fetch one. Absent where nothing is fetching — the auth commands, and
|
|
1226
|
-
* tests of the reporting on its own.
|
|
1227
|
-
*/
|
|
1228
|
-
onCapacity) {
|
|
1229
|
-
const queue = new TaskQueue(maxConcurrency, () => void reportConcurrency(bridge, queue), onCapacity);
|
|
1230
|
-
return queue;
|
|
1231
|
-
}
|
|
1232
|
-
/**
|
|
1233
|
-
* Subscribes the queue to the workspace's concurrency directives.
|
|
1234
|
-
*
|
|
1235
|
-
* The reconnect subscription is the less obvious half. A reconnect mints a new
|
|
1236
|
-
* MCP session and the workspace keys this report to the connection it arrived
|
|
1237
|
-
* on — so a workspace that dropped and came back would otherwise go on showing
|
|
1238
|
-
* whatever limit it last heard about, which is the boot default for the rest of
|
|
1239
|
-
* the gateway's life.
|
|
1240
|
-
*/
|
|
1241
|
-
export function registerConcurrencyListeners(bridge, queue) {
|
|
1242
|
-
bridge.on("setConcurrency", (params) => {
|
|
1243
|
-
handleSetConcurrency(params, queue, bridge).catch((err) => {
|
|
1244
|
-
console.error("[bridge] Error handling concurrency change:", err);
|
|
1245
|
-
});
|
|
1246
|
-
});
|
|
1247
|
-
bridge.on("reconnected", () => {
|
|
1248
|
-
void reportConcurrency(bridge, queue);
|
|
1249
|
-
});
|
|
1250
|
-
}
|
|
1251
|
-
/**
|
|
1252
|
-
* Handles task cancellation events from the MCP server.
|
|
1253
|
-
* Cancels the ACP session/turn and immediately cancels any pending permissions.
|
|
1254
|
-
*/
|
|
1255
|
-
export async function handleTaskCancellation(taskId, reason) {
|
|
1256
|
-
if (taskId) {
|
|
1257
|
-
markTaskCancelled(taskId);
|
|
1258
|
-
const session = findActiveSession(taskId);
|
|
1259
|
-
if (!session) {
|
|
1260
|
-
console.error(`[bridge] Received cancellation for task ${taskId}, but no active session found (queued tasks will be skipped)`);
|
|
1261
|
-
return;
|
|
1262
|
-
}
|
|
1263
|
-
console.error(`[bridge] Cancelling session ${session.sessionId} for task ${taskId}${reason ? ` (${reason})` : ""}`);
|
|
1264
|
-
await session.acpClient.cancelTurn(session.sessionId);
|
|
1265
|
-
}
|
|
1266
|
-
else {
|
|
1267
|
-
const session = findActiveSession(undefined);
|
|
1268
|
-
if (session) {
|
|
1269
|
-
console.error(`[bridge] Received cancellation with no taskId${reason ? ` (${reason})` : ""}. Cancelling active session ${session.sessionId}...`);
|
|
1270
|
-
await session.acpClient.cancelTurn(session.sessionId);
|
|
1271
|
-
}
|
|
1272
|
-
else {
|
|
1273
|
-
console.error(`[bridge] Received cancellation with no taskId${reason ? ` (${reason})` : ""}` +
|
|
1274
|
-
(activeSessions.size === 0
|
|
1275
|
-
? ", and no sessions are active"
|
|
1276
|
-
: `, but ${activeSessions.size} sessions are active (skipping to avoid aborting unrelated tasks)`));
|
|
1277
|
-
}
|
|
1278
|
-
}
|
|
1279
|
-
}
|
|
1280
|
-
// Modes that approve tool calls without asking the user. codex-acp, for
|
|
1281
|
-
// example, defaults to an "agent" mode whose reviewer is "auto_review" — an
|
|
1282
|
-
// automated Guardian Review that approves on the human's behalf — and also
|
|
1283
|
-
// offers an "agent-full-access" mode that never asks at all.
|
|
1284
|
-
const AUTO_APPROVING_MODE = /auto|full[\s_-]?access|danger|bypass|yolo|never|always/i;
|
|
1285
|
-
// Modes that defer the decision to the human.
|
|
1286
|
-
const HUMAN_APPROVAL_MODE = /ask|approval|approve|manual|prompt|review|read[\s_-]?only/i;
|
|
1287
|
-
function describeMode(mode) {
|
|
1288
|
-
const kind = mode._meta?.kind;
|
|
1289
|
-
return `${mode.id} ${mode.name} ${typeof kind === "string" ? kind : ""}`;
|
|
1290
|
-
}
|
|
1291
|
-
/**
|
|
1292
|
-
* Picks the session mode that routes every tool-call approval to the human.
|
|
1293
|
-
*
|
|
1294
|
-
* Agents may offer modes that approve on the user's behalf and commonly
|
|
1295
|
-
* default to one. In such a mode the agent never sends a permission request,
|
|
1296
|
-
* so tool calls — including destructive ones — execute without ever reaching
|
|
1297
|
-
* agentrq. Returns the id of a mode that defers to the human, or undefined if
|
|
1298
|
-
* the agent offers none.
|
|
1299
|
-
*/
|
|
1300
|
-
export function pickHumanApprovalMode(modes) {
|
|
1301
|
-
const available = modes?.availableModes;
|
|
1302
|
-
if (!available?.length)
|
|
1303
|
-
return undefined;
|
|
1304
|
-
const candidates = available.filter((m) => !AUTO_APPROVING_MODE.test(describeMode(m)));
|
|
1305
|
-
const chosen = candidates.find((m) => HUMAN_APPROVAL_MODE.test(describeMode(m))) ?? candidates[0];
|
|
1306
|
-
return chosen?.id;
|
|
1307
|
-
}
|
|
1308
|
-
/**
|
|
1309
|
-
* Switches a freshly created session into a mode that requires human approval,
|
|
1310
|
-
* so that every non-agentrq tool call reaches the agentrq dashboard rather than
|
|
1311
|
-
* being auto-approved inside the agent.
|
|
1312
|
-
*/
|
|
1313
|
-
export async function enforceHumanApprovalMode(connection, sessionResult) {
|
|
1314
|
-
const modes = sessionResult.modes;
|
|
1315
|
-
// Agents that expose no modes have nothing to switch; they either always ask
|
|
1316
|
-
// or their policy is out of the gateway's reach.
|
|
1317
|
-
if (!modes?.availableModes?.length)
|
|
1318
|
-
return;
|
|
1319
|
-
const modeId = pickHumanApprovalMode(modes);
|
|
1320
|
-
if (!modeId) {
|
|
1321
|
-
console.error(`[acp] ⚠️ Agent offers no mode that defers approvals to the human ` +
|
|
1322
|
-
`(available: ${modes.availableModes.map((m) => m.id).join(", ")}). ` +
|
|
1323
|
-
`Tool calls may execute without agentrq approval.`);
|
|
1324
|
-
return;
|
|
1325
|
-
}
|
|
1326
|
-
if (modeId === modes.currentModeId)
|
|
1327
|
-
return;
|
|
1328
|
-
try {
|
|
1329
|
-
await connection.setSessionMode({ sessionId: sessionResult.sessionId, modeId });
|
|
1330
|
-
debug(`[acp] Session mode set to "${modeId}" (was "${modes.currentModeId}") so tool calls require agentrq approval`);
|
|
1331
|
-
}
|
|
1332
|
-
catch (err) {
|
|
1333
|
-
console.error(`[acp] ⚠️ Failed to set session mode to "${modeId}" — tool calls may execute without agentrq approval:`, err);
|
|
1334
|
-
}
|
|
1335
|
-
}
|
|
1336
|
-
/**
|
|
1337
|
-
* How many times the gateway will drag one session back into a mode that asks
|
|
1338
|
-
* the human. An agent that keeps switching back is not going to stop, and an
|
|
1339
|
-
* unbounded fight with it would be an endless stream of setSessionMode calls.
|
|
1340
|
-
*/
|
|
1341
|
-
const MAX_MODE_REENFORCEMENTS = 3;
|
|
1342
|
-
/**
|
|
1343
|
-
* sessionId → how many times its mode has already been put back. Bounded
|
|
1344
|
-
* because sessions end without telling this map.
|
|
1345
|
-
*/
|
|
1346
|
-
const modeReenforcements = new BoundedMap(256);
|
|
1347
|
-
/**
|
|
1348
|
-
* Puts a session back into a mode that asks the human, after the agent moved
|
|
1349
|
-
* itself out of one.
|
|
1350
|
-
*
|
|
1351
|
-
* Agents may change modes on their own. If one moves into a mode that approves
|
|
1352
|
-
* tool calls on the user's behalf, every later tool call — including
|
|
1353
|
-
* destructive ones — executes without ever reaching agentrq, and nothing
|
|
1354
|
-
* anywhere says so.
|
|
1355
|
-
*/
|
|
1356
|
-
export async function handleAgentModeChange(connection, sessionId, currentModeId, modes) {
|
|
1357
|
-
const available = modes?.availableModes;
|
|
1358
|
-
if (!available?.length)
|
|
1359
|
-
return;
|
|
1360
|
-
const mode = available.find((m) => m.id === currentModeId);
|
|
1361
|
-
// A mode the agent never advertised cannot be vouched for either, so it is
|
|
1362
|
-
// treated the same as one that approves on our behalf.
|
|
1363
|
-
if (mode && !AUTO_APPROVING_MODE.test(describeMode(mode))) {
|
|
1364
|
-
modeReenforcements.delete(sessionId);
|
|
1365
|
-
return;
|
|
1366
|
-
}
|
|
1367
|
-
const attempts = modeReenforcements.get(sessionId) ?? 0;
|
|
1368
|
-
if (attempts >= MAX_MODE_REENFORCEMENTS) {
|
|
1369
|
-
console.error(`[acp] ⚠️ Agent keeps returning session ${sessionId} to mode "${currentModeId}", ` +
|
|
1370
|
-
`which approves tool calls without asking. Giving up after ` +
|
|
1371
|
-
`${MAX_MODE_REENFORCEMENTS} attempts — tool calls may now execute without ` +
|
|
1372
|
-
`agentrq approval.`);
|
|
1373
|
-
return;
|
|
1374
|
-
}
|
|
1375
|
-
modeReenforcements.set(sessionId, attempts + 1);
|
|
1376
|
-
console.error(`[acp] ⚠️ Agent moved session ${sessionId} into "${currentModeId}", which approves ` +
|
|
1377
|
-
`tool calls without asking. Putting it back.`);
|
|
1378
|
-
await enforceHumanApprovalMode(connection, {
|
|
1379
|
-
sessionId,
|
|
1380
|
-
modes: { availableModes: available, currentModeId },
|
|
1381
|
-
});
|
|
1382
|
-
}
|
|
1383
|
-
export function createAcpSessionSwitcher(connection, params, initialSessionId) {
|
|
1384
|
-
let currentSessionId = initialSessionId;
|
|
1385
|
-
const taskSessionMap = new Map();
|
|
1386
|
-
const sessionTaskMap = new Map();
|
|
1387
|
-
return {
|
|
1388
|
-
getSessionId() {
|
|
1389
|
-
return currentSessionId;
|
|
1390
|
-
},
|
|
1391
|
-
getTaskIdForSession(sessionId) {
|
|
1392
|
-
return sessionTaskMap.get(sessionId);
|
|
1393
|
-
},
|
|
1394
|
-
async ensureForTask(taskId) {
|
|
1395
|
-
if (taskId === undefined) {
|
|
1396
|
-
return currentSessionId;
|
|
1397
|
-
}
|
|
1398
|
-
const existing = taskSessionMap.get(taskId);
|
|
1399
|
-
if (existing) {
|
|
1400
|
-
currentSessionId = existing;
|
|
1401
|
-
return existing;
|
|
1402
|
-
}
|
|
1403
|
-
const next = await connection.newSession(params);
|
|
1404
|
-
currentSessionId = next.sessionId;
|
|
1405
|
-
taskSessionMap.set(taskId, currentSessionId);
|
|
1406
|
-
sessionTaskMap.set(currentSessionId, taskId);
|
|
1407
|
-
debug(`[acp] New ACP session for task ${taskId} (MCP connection unchanged): ${currentSessionId}`);
|
|
1408
|
-
return currentSessionId;
|
|
1409
|
-
},
|
|
1410
|
-
};
|
|
1411
|
-
}
|
|
1412
|
-
export class TaskQueue {
|
|
1413
|
-
maxConcurrency;
|
|
1414
|
-
onChange;
|
|
1415
|
-
onCapacity;
|
|
1416
|
-
activeTasks = 0;
|
|
1417
|
-
queue = new FifoQueue();
|
|
1418
|
-
/**
|
|
1419
|
-
* @param onChange Told whenever the number running or waiting moves, so
|
|
1420
|
-
* somebody can report it. The queue has no idea who is listening — it holds
|
|
1421
|
-
* no bridge and knows nothing about notifications — because what it owes the
|
|
1422
|
-
* interface is the fact that its numbers moved, not the delivery of that
|
|
1423
|
-
* fact. Absent only in tests, matching `handleSetConcurrency`'s `bridge?`.
|
|
1424
|
-
*/
|
|
1425
|
-
constructor(maxConcurrency, onChange, onCapacity) {
|
|
1426
|
-
this.maxConcurrency = maxConcurrency;
|
|
1427
|
-
this.onChange = onChange;
|
|
1428
|
-
this.onCapacity = onCapacity;
|
|
1429
|
-
}
|
|
1430
|
-
/**
|
|
1431
|
-
* Says the numbers moved, and survives a listener that cannot take the news.
|
|
1432
|
-
*
|
|
1433
|
-
* Guarded because this is called from `execute`, including from its `finally`:
|
|
1434
|
-
* a listener that threw there would replace the task's own error with its own,
|
|
1435
|
-
* losing what actually went wrong, and one that threw on the way in would stop
|
|
1436
|
-
* the task before it started. Running tasks is this class's job; telling an
|
|
1437
|
-
* interface about them is a courtesy, and a courtesy must not be able to break
|
|
1438
|
-
* the job.
|
|
1439
|
-
*/
|
|
1440
|
-
announce() {
|
|
1441
|
-
try {
|
|
1442
|
-
this.onChange?.();
|
|
1443
|
-
}
|
|
1444
|
-
catch (err) {
|
|
1445
|
-
console.error("[queue] Error reporting the queue's state:", err);
|
|
1446
|
-
}
|
|
1447
|
-
}
|
|
1448
|
-
/**
|
|
1449
|
-
* Says there may be room for another task, and survives a listener that
|
|
1450
|
-
* cannot take the news.
|
|
1451
|
-
*
|
|
1452
|
-
* Separate from `announce` because the two answer different questions. A
|
|
1453
|
-
* report of the numbers goes out whenever they move, including when a task
|
|
1454
|
-
* *starts* and the gateway has less room than before; this one fires only
|
|
1455
|
-
* where room may have appeared — a task finished, or the limit went up — and
|
|
1456
|
-
* it is what lets the gateway go and ask the workspace for more work.
|
|
1457
|
-
*
|
|
1458
|
-
* Guarded for the same reason `announce` is: filling the queue is a courtesy
|
|
1459
|
-
* to whoever is waiting, and a courtesy must not be able to break the task
|
|
1460
|
-
* that just finished.
|
|
1461
|
-
*/
|
|
1462
|
-
offerCapacity() {
|
|
1463
|
-
// Only when there is actually room. Both callers reach here on moves that
|
|
1464
|
-
// may leave none — a task finishing into a backlog that immediately
|
|
1465
|
-
// refills its slot, a limit *lowered* under work already running — and
|
|
1466
|
-
// "there may be room" is a message about the queue, not about the move.
|
|
1467
|
-
if (this.activeTasks >= this.maxConcurrency || this.queue.length > 0)
|
|
1468
|
-
return;
|
|
1469
|
-
try {
|
|
1470
|
-
this.onCapacity?.();
|
|
1471
|
-
}
|
|
1472
|
-
catch (err) {
|
|
1473
|
-
console.error("[queue] Error offering the queue's free capacity:", err);
|
|
1474
|
-
}
|
|
1475
|
-
}
|
|
1476
|
-
async run(taskFn) {
|
|
1477
|
-
if (this.activeTasks < this.maxConcurrency) {
|
|
1478
|
-
await this.execute(taskFn);
|
|
1479
|
-
}
|
|
1480
|
-
else {
|
|
1481
|
-
await new Promise((resolve, reject) => {
|
|
1482
|
-
this.queue.push(async () => {
|
|
1483
|
-
try {
|
|
1484
|
-
await taskFn();
|
|
1485
|
-
resolve();
|
|
1486
|
-
}
|
|
1487
|
-
catch (err) {
|
|
1488
|
-
reject(err);
|
|
1489
|
-
throw err;
|
|
1490
|
-
}
|
|
1491
|
-
});
|
|
1492
|
-
// Nothing started, but something is now waiting — which is exactly the
|
|
1493
|
-
// state a full gateway is in, and the one worth seeing.
|
|
1494
|
-
this.announce();
|
|
1495
|
-
});
|
|
1496
|
-
}
|
|
1497
|
-
}
|
|
1498
|
-
async execute(taskFn) {
|
|
1499
|
-
this.activeTasks++;
|
|
1500
|
-
// Before the task is awaited rather than after, or the report would not go
|
|
1501
|
-
// out until the work it is announcing had already finished.
|
|
1502
|
-
this.announce();
|
|
1503
|
-
try {
|
|
1504
|
-
await taskFn();
|
|
1505
|
-
}
|
|
1506
|
-
finally {
|
|
1507
|
-
this.activeTasks--;
|
|
1508
|
-
// Before `next()`, so this says a slot came free; whatever `next()` then
|
|
1509
|
-
// starts announces itself. The other order would report the same settled
|
|
1510
|
-
// state twice and never show the gap.
|
|
1511
|
-
this.announce();
|
|
1512
|
-
this.next();
|
|
1513
|
-
// After `next()`, so that whatever was already waiting here has taken its
|
|
1514
|
-
// slot back before anyone is told there is one going spare.
|
|
1515
|
-
this.offerCapacity();
|
|
1516
|
-
}
|
|
1517
|
-
}
|
|
1518
|
-
/**
|
|
1519
|
-
* Starts as many waiting tasks as the limit now has room for.
|
|
1520
|
-
*
|
|
1521
|
-
* A loop rather than a single task, because this is also what runs when the
|
|
1522
|
-
* limit is raised: going from 1 to 4 with three tasks waiting has to start
|
|
1523
|
-
* all three, and starting one and waiting for it to finish would make a raise
|
|
1524
|
-
* take effect one task at a time. `execute` counts the task as active before
|
|
1525
|
-
* it yields, so the condition is re-read against a number that already
|
|
1526
|
-
* includes everything this loop has started.
|
|
1527
|
-
*/
|
|
1528
|
-
next() {
|
|
1529
|
-
while (!this.queue.isEmpty && this.activeTasks < this.maxConcurrency) {
|
|
1530
|
-
// Non-null: the loop condition has just established the queue is not empty.
|
|
1531
|
-
const nextTask = this.queue.shift();
|
|
1532
|
-
this.execute(nextTask).catch((err) => {
|
|
1533
|
-
console.log("[queue] Error executing queued task:", err);
|
|
1534
|
-
});
|
|
1535
|
-
}
|
|
1536
|
-
}
|
|
1537
|
-
getActiveCount() {
|
|
1538
|
-
return this.activeTasks;
|
|
1539
|
-
}
|
|
1540
|
-
getQueueLength() {
|
|
1541
|
-
return this.queue.length;
|
|
1542
|
-
}
|
|
1543
|
-
getMaxConcurrency() {
|
|
1544
|
-
return this.maxConcurrency;
|
|
1545
|
-
}
|
|
1546
|
-
/**
|
|
1547
|
-
* Changes how many tasks may run at once, while tasks are running.
|
|
1548
|
-
*
|
|
1549
|
-
* Lowering the limit never interrupts anything: a task that has already been
|
|
1550
|
-
* handed to the agent keeps its turn, and the queue simply stops handing out
|
|
1551
|
-
* new ones until enough have finished. So a limit lowered below the number
|
|
1552
|
-
* currently running is honoured going forward rather than retroactively —
|
|
1553
|
-
* killing work already in flight is not what "run fewer at once" means.
|
|
1554
|
-
*/
|
|
1555
|
-
setMaxConcurrency(maxConcurrency) {
|
|
1556
|
-
if (maxConcurrency === this.maxConcurrency)
|
|
1557
|
-
return;
|
|
1558
|
-
const previous = this.maxConcurrency;
|
|
1559
|
-
this.maxConcurrency = maxConcurrency;
|
|
1560
|
-
console.error(`[queue] Concurrency limit ${previous} -> ${maxConcurrency} ` +
|
|
1561
|
-
`(${this.activeTasks} running, ${this.queue.length} queued)`);
|
|
1562
|
-
this.next();
|
|
1563
|
-
// A raise with nothing waiting internally starts nothing, and used to end
|
|
1564
|
-
// there: the gateway sat at one task with room for three because the two
|
|
1565
|
-
// it could have run were still sitting in the workspace, unasked for.
|
|
1566
|
-
// (A lowered limit reaches here too, and leaves no room to offer.)
|
|
1567
|
-
this.offerCapacity();
|
|
1568
|
-
}
|
|
1569
|
-
}
|
|
1570
411
|
/** Default maximum number of concurrent tasks allowed to prompt the ACP agent at once. */
|
|
1571
412
|
export const DEFAULT_MAX_CONCURRENCY = MIN_MAX_CONCURRENCY;
|
|
1572
413
|
/**
|
|
@@ -1715,11 +556,13 @@ export function parseGatewayArgs(args) {
|
|
|
1715
556
|
}
|
|
1716
557
|
break;
|
|
1717
558
|
case "--acp-version":
|
|
1718
|
-
|
|
1719
|
-
|
|
559
|
+
// ACP v1 is the only protocol the gateway speaks. The flag is still
|
|
560
|
+
// read, so launch scripts written when it chose between modes keep
|
|
561
|
+
// working with `--acp-version 1`.
|
|
562
|
+
if (value !== "1") {
|
|
563
|
+
console.error("[acp-gateway] --acp-version must be 1, the only version supported");
|
|
1720
564
|
process.exit(1);
|
|
1721
565
|
}
|
|
1722
|
-
options.acpVersion = Number(value);
|
|
1723
566
|
i++;
|
|
1724
567
|
break;
|
|
1725
568
|
case "--acp-url":
|
|
@@ -1794,14 +637,7 @@ export async function resolveAgentCommand(options, explicitCommand, fetchImpl =
|
|
|
1794
637
|
fetchImpl,
|
|
1795
638
|
});
|
|
1796
639
|
debug(`[registry] Running "${options.agentId}" via ${spec.kind}: ${spec.command} ${spec.args.join(" ")}`);
|
|
1797
|
-
|
|
1798
|
-
// started, which is the only reason a workspace can name it while the
|
|
1799
|
-
// gateway is idle — the agent itself does not speak until a task arrives.
|
|
1800
|
-
const entry = findAgent(registry, options.agentId);
|
|
1801
|
-
const identity = entry
|
|
1802
|
-
? { name: entry.name || entry.id, version: entry.version }
|
|
1803
|
-
: undefined;
|
|
1804
|
-
return { command: [spec.command, ...spec.args], env: spec.env, identity };
|
|
640
|
+
return { command: [spec.command, ...spec.args], env: spec.env };
|
|
1805
641
|
}
|
|
1806
642
|
/**
|
|
1807
643
|
* Whether a command can actually be run.
|
|
@@ -1831,9 +667,9 @@ export function assertAgentRunnable(command, usedRegistryId) {
|
|
|
1831
667
|
}
|
|
1832
668
|
/**
|
|
1833
669
|
* Commands that only deal with the agent itself. None of them hands the agent
|
|
1834
|
-
* a workspace or reports to one, so none
|
|
1835
|
-
*
|
|
1836
|
-
*
|
|
670
|
+
* a workspace or reports to one, so none needs a .mcp.json — `--list-models` is
|
|
671
|
+
* how someone picks a model, and `--login` how someone signs the agent in,
|
|
672
|
+
* before they have set a workspace up at all.
|
|
1837
673
|
*/
|
|
1838
674
|
export const WORKSPACE_OPTIONAL_COMMANDS = new Set([
|
|
1839
675
|
"list-models",
|
|
@@ -1843,57 +679,19 @@ export const WORKSPACE_OPTIONAL_COMMANDS = new Set([
|
|
|
1843
679
|
"logout",
|
|
1844
680
|
]);
|
|
1845
681
|
/**
|
|
1846
|
-
*
|
|
1847
|
-
*
|
|
1848
|
-
* Whatever the agent asks of it fails, which the ACP client already treats as
|
|
1849
|
-
* the workspace being unreachable: a stray elicitation is cancelled rather than
|
|
1850
|
-
* left waiting on a panel nobody has. A url elicitation at a terminal still
|
|
1851
|
-
* reaches the person there, since that never goes near the workspace.
|
|
1852
|
-
*
|
|
1853
|
-
* Notifications are dropped instead. Nobody waits on them, and the agent sends
|
|
1854
|
-
* some on its own — its slash commands, its models — so failing them would only
|
|
1855
|
-
* print an error for something that was never going to arrive anywhere.
|
|
1856
|
-
*/
|
|
1857
|
-
export function createDetachedBridge() {
|
|
1858
|
-
const bridge = new EventEmitter();
|
|
1859
|
-
bridge.callTool = async () => {
|
|
1860
|
-
throw new Error("No agentrq workspace is configured");
|
|
1861
|
-
};
|
|
1862
|
-
bridge.sendNotification = async (method) => {
|
|
1863
|
-
debug(`[acp] No agentrq workspace is configured, dropping ${method}`);
|
|
1864
|
-
};
|
|
1865
|
-
bridge.getSessionId = () => undefined;
|
|
1866
|
-
bridge.getServerName = () => undefined;
|
|
1867
|
-
bridge.getAdvertisedTools = () => undefined;
|
|
1868
|
-
bridge.close = async () => { };
|
|
1869
|
-
return bridge;
|
|
1870
|
-
}
|
|
1871
|
-
/**
|
|
1872
|
-
* Finds the workspace a command needs.
|
|
1873
|
-
*
|
|
1874
|
-
* Anything that runs tasks needs one, and fails without it. A command that only
|
|
1875
|
-
* deals with the agent itself does not go looking for one: a .mcp.json that is
|
|
1876
|
-
* missing, or broken, has nothing to do with which models the agent offers or
|
|
1877
|
-
* whether it is logged in.
|
|
1878
|
-
* `--mcp-json` is still honoured there, since someone named it on purpose — to
|
|
1879
|
-
* have a login the agent asks for show up in that workspace, say.
|
|
682
|
+
* Finds the AgentRQ server a command reports to: its URL and token are where
|
|
683
|
+
* the ACP endpoint comes from.
|
|
1880
684
|
*
|
|
1881
|
-
*
|
|
1882
|
-
*
|
|
1883
|
-
*
|
|
685
|
+
* A command that only deals with the agent itself does not go looking for
|
|
686
|
+
* one: a .mcp.json that is missing, or broken, has nothing to do with which
|
|
687
|
+
* models the agent offers or whether it is logged in.
|
|
1884
688
|
*/
|
|
1885
689
|
export function loadWorkspace(command, mcpJsonPath, startDir = process.cwd()) {
|
|
1886
|
-
if (WORKSPACE_OPTIONAL_COMMANDS.has(command)
|
|
1887
|
-
return {
|
|
1888
|
-
configs: [],
|
|
1889
|
-
agentrqConfig: { name: "none", type: "http", env: {} },
|
|
1890
|
-
mcpBridge: createDetachedBridge(),
|
|
1891
|
-
};
|
|
690
|
+
if (WORKSPACE_OPTIONAL_COMMANDS.has(command)) {
|
|
691
|
+
return { configs: [], agentrqConfig: { name: "none", type: "http", env: {} } };
|
|
1892
692
|
}
|
|
1893
693
|
const configs = loadMcpConfig(startDir, mcpJsonPath);
|
|
1894
|
-
|
|
1895
|
-
const mcpBridge = command === "list-models" ? createDetachedBridge() : new MCPBridge(agentrqConfig);
|
|
1896
|
-
return { configs, agentrqConfig, mcpBridge };
|
|
694
|
+
return { configs, agentrqConfig: pickAgentrqServer(configs) };
|
|
1897
695
|
}
|
|
1898
696
|
/**
|
|
1899
697
|
* Makes an empty directory for `--list-models` to run the agent in.
|
|
@@ -1925,15 +723,14 @@ export function makeIsolatedDir() {
|
|
|
1925
723
|
* be done deliberately, before any task arrives, rather than only when a
|
|
1926
724
|
* session is refused.
|
|
1927
725
|
*/
|
|
1928
|
-
export async function runAgentCommand(command, acpCmdArgs,
|
|
726
|
+
export async function runAgentCommand(command, acpCmdArgs, env, authMethodId, json = false) {
|
|
1929
727
|
const [cmd, ...cmdArgs] = acpCmdArgs;
|
|
1930
728
|
const isolated = command === "list-models" ? makeIsolatedDir() : undefined;
|
|
1931
729
|
let agent;
|
|
1932
730
|
try {
|
|
1933
731
|
agent = await openAgentConnection({
|
|
1934
732
|
acpCmdArgs,
|
|
1935
|
-
|
|
1936
|
-
env: agentrqConfig.env,
|
|
733
|
+
env,
|
|
1937
734
|
label: command,
|
|
1938
735
|
cwd: isolated?.dir,
|
|
1939
736
|
});
|
|
@@ -1959,11 +756,11 @@ export async function runAgentCommand(command, acpCmdArgs, agentrqConfig, mcpBri
|
|
|
1959
756
|
if (command === "list-models") {
|
|
1960
757
|
const newSessionParams = {
|
|
1961
758
|
cwd: isolated.dir,
|
|
1962
|
-
mcpServers:
|
|
759
|
+
mcpServers: [],
|
|
1963
760
|
};
|
|
1964
761
|
const sessionResult = await createSessionWithAuth(agent.connection, newSessionParams, {
|
|
1965
762
|
methods: authMethods,
|
|
1966
|
-
launch: { command: cmd, args: cmdArgs, env
|
|
763
|
+
launch: { command: cmd, args: cmdArgs, env },
|
|
1967
764
|
preferredId: authMethodId,
|
|
1968
765
|
interactive: isInteractiveTerminal(),
|
|
1969
766
|
});
|
|
@@ -2035,7 +832,7 @@ export async function runAgentCommand(command, acpCmdArgs, agentrqConfig, mcpBri
|
|
|
2035
832
|
await login({
|
|
2036
833
|
connection,
|
|
2037
834
|
methods: authMethods,
|
|
2038
|
-
launch: { command: cmd, args: cmdArgs, env
|
|
835
|
+
launch: { command: cmd, args: cmdArgs, env },
|
|
2039
836
|
preferredId: authMethodId,
|
|
2040
837
|
interactive: isInteractiveTerminal(),
|
|
2041
838
|
});
|
|
@@ -2046,25 +843,24 @@ export async function runAgentCommand(command, acpCmdArgs, agentrqConfig, mcpBri
|
|
|
2046
843
|
}
|
|
2047
844
|
}
|
|
2048
845
|
/**
|
|
2049
|
-
* What
|
|
846
|
+
* What the ACP bridge runs with, from the gateway's own options and the
|
|
2050
847
|
* workspace's AgentRQ entry. A string is the reason it cannot run.
|
|
2051
848
|
*/
|
|
2052
|
-
export function nativeOptionsFor(options, acpCmdArgs, agentrqConfig, cwd = process.cwd()) {
|
|
849
|
+
export function nativeOptionsFor(options, acpCmdArgs, { configs, agentrqConfig }, cwd = process.cwd(), interactive = isInteractiveTerminal()) {
|
|
2053
850
|
const token = tokenFrom(agentrqConfig);
|
|
2054
851
|
if (!token)
|
|
2055
|
-
return "
|
|
852
|
+
return "acp-gateway needs the workspace token from .mcp.json";
|
|
2056
853
|
if (!agentrqConfig.url && !options.acpUrl) {
|
|
2057
|
-
return "
|
|
854
|
+
return "acp-gateway needs the AgentRQ URL from .mcp.json, or --acp-url";
|
|
2058
855
|
}
|
|
2059
856
|
let endpoint;
|
|
2060
857
|
try {
|
|
2061
|
-
endpoint = nativeEndpoint(agentrqConfig.url ?? "", options.
|
|
858
|
+
endpoint = nativeEndpoint(agentrqConfig.url ?? "", options.acpUrl);
|
|
2062
859
|
}
|
|
2063
860
|
catch {
|
|
2064
|
-
return `
|
|
861
|
+
return `acp-gateway cannot work out the AgentRQ endpoint from "${agentrqConfig.url}"; pass --acp-url`;
|
|
2065
862
|
}
|
|
2066
863
|
return {
|
|
2067
|
-
version: options.acpVersion ?? 1,
|
|
2068
864
|
acpCmdArgs,
|
|
2069
865
|
env: agentrqConfig.env,
|
|
2070
866
|
endpoint,
|
|
@@ -2076,11 +872,20 @@ export function nativeOptionsFor(options, acpCmdArgs, agentrqConfig, cwd = proce
|
|
|
2076
872
|
permissionTimeoutMinutes: Math.round(options.permissionTimeoutMs / 60_000),
|
|
2077
873
|
authMethodId: options.authMethodId,
|
|
2078
874
|
cwd: path.resolve(cwd),
|
|
875
|
+
// Every session the agent opens gets them, as under the MCP bridge: the
|
|
876
|
+
// agent's own tools are configured here, not in AgentRQ.
|
|
877
|
+
mcpServers: configs,
|
|
878
|
+
// AgentRQ never runs a terminal login itself. With a terminal here — a
|
|
879
|
+
// shell, or agentrqd's browser terminal — the bridge runs it instead of
|
|
880
|
+
// stopping.
|
|
881
|
+
login: interactive
|
|
882
|
+
? () => runAgentCommand("login", acpCmdArgs, agentrqConfig.env, options.authMethodId)
|
|
883
|
+
: undefined,
|
|
2079
884
|
};
|
|
2080
885
|
}
|
|
2081
|
-
/** Runs
|
|
2082
|
-
export async function startNativeMode(options, acpCmdArgs,
|
|
2083
|
-
const native = nativeOptionsFor(options, acpCmdArgs,
|
|
886
|
+
/** Runs the ACP bridge, or says why it cannot and exits 1. */
|
|
887
|
+
export async function startNativeMode(options, acpCmdArgs, workspace, run = runNative, exit = process.exit.bind(process)) {
|
|
888
|
+
const native = nativeOptionsFor(options, acpCmdArgs, workspace);
|
|
2084
889
|
if (typeof native === "string") {
|
|
2085
890
|
console.error(`[acp-gateway] ${native}`);
|
|
2086
891
|
return exit(1);
|
|
@@ -2102,7 +907,9 @@ USAGE
|
|
|
2102
907
|
acp-gateway [options] --agent <registry-id>
|
|
2103
908
|
|
|
2104
909
|
The agent is either a command you supply after \`--\`, or an id from the ACP
|
|
2105
|
-
registry. Everything after \`--\` is passed to the agent untouched.
|
|
910
|
+
registry. Everything after \`--\` is passed to the agent untouched. Its ACP
|
|
911
|
+
stream is piped to AgentRQ's ACP v1 endpoint, which speaks ACP itself.
|
|
912
|
+
Needs Node 22 or newer.
|
|
2106
913
|
|
|
2107
914
|
AGENT
|
|
2108
915
|
--agent <registry-id> Run an agent from the ACP registry, installing it
|
|
@@ -2144,21 +951,15 @@ BRIDGE
|
|
|
2144
951
|
gateway from outside its workspace. Any filename;
|
|
2145
952
|
a directory means the .mcp.json inside it. Its
|
|
2146
953
|
servers win where the names collide.
|
|
2147
|
-
--acp-
|
|
2148
|
-
which speaks ACP version 1 or 2 itself
|
|
2149
|
-
(/api/acp/v1 or /api/acp/v2), instead of
|
|
2150
|
-
translating it here. Needs Node 22 or newer.
|
|
2151
|
-
--acp-url <url> The native endpoint, when it cannot be worked out
|
|
954
|
+
--acp-url <url> The ACP endpoint, when it cannot be worked out
|
|
2152
955
|
from .mcp.json.
|
|
2153
956
|
|
|
2154
957
|
OTHER
|
|
2155
|
-
--verbose Print everything:
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
commands that print something and exit print
|
|
2161
|
-
only that.
|
|
958
|
+
--verbose Print everything: the connection to AgentRQ, the
|
|
959
|
+
agent's own logs, and what the one-shot commands
|
|
960
|
+
exchange with the agent. Without it, only
|
|
961
|
+
warnings and errors — and commands that print
|
|
962
|
+
something and exit print only that.
|
|
2162
963
|
--help, -h Show this help. Exits.
|
|
2163
964
|
|
|
2164
965
|
EXAMPLES
|
|
@@ -2171,13 +972,12 @@ EXAMPLES
|
|
|
2171
972
|
acp-gateway --login -- gemini --acp Log in before running anything
|
|
2172
973
|
acp-gateway --max-concurrency 4 -- gemini --acp
|
|
2173
974
|
acp-gateway --mcp-json ~/work/.mcp.json -- gemini --acp
|
|
2174
|
-
acp-gateway --acp-version 1 --agent codex-acp Let AgentRQ speak ACP itself
|
|
2175
975
|
|
|
2176
976
|
The workspace comes from .mcp.json, searched for in the current directory and up
|
|
2177
|
-
to three directories above it
|
|
2178
|
-
and whatever it is called.
|
|
2179
|
-
--login and --logout do not
|
|
2180
|
-
|
|
977
|
+
to three directories above it; only its AgentRQ URL and token are used.
|
|
978
|
+
--mcp-json names one directly, wherever it lives and whatever it is called.
|
|
979
|
+
--list-models, --agent-info, --list-auth-methods, --login and --logout do not
|
|
980
|
+
need a workspace.`;
|
|
2181
981
|
}
|
|
2182
982
|
export function printHelp() {
|
|
2183
983
|
console.log(helpText());
|
|
@@ -2191,7 +991,7 @@ async function main() {
|
|
|
2191
991
|
const gatewayArgs = cmdStartIndex !== -1 ? args.slice(0, cmdStartIndex) : args;
|
|
2192
992
|
const options = parseGatewayArgs(gatewayArgs);
|
|
2193
993
|
const explicitCommand = cmdStartIndex !== -1 ? args.slice(cmdStartIndex + 1) : options.rest;
|
|
2194
|
-
const {
|
|
994
|
+
const { command } = options;
|
|
2195
995
|
setVerbose(options.verbose);
|
|
2196
996
|
if (command === "help") {
|
|
2197
997
|
printHelp();
|
|
@@ -2211,468 +1011,53 @@ async function main() {
|
|
|
2211
1011
|
}
|
|
2212
1012
|
if (shouldPrintBanner(options))
|
|
2213
1013
|
console.log(`Starting [acp-gateway] ${pkg.name} v${pkg.version}`);
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
|
|
1014
|
+
await runGateway(options, explicitCommand);
|
|
1015
|
+
}
|
|
1016
|
+
/**
|
|
1017
|
+
* Everything `main` does once it knows there is an agent to deal with: find
|
|
1018
|
+
* the workspace, work out the agent's command, then either run a one-shot
|
|
1019
|
+
* command against it or bridge it to AgentRQ.
|
|
1020
|
+
*
|
|
1021
|
+
* Out here rather than in `main` so it can be tested; `main` reads the real
|
|
1022
|
+
* process arguments and never returns.
|
|
1023
|
+
*/
|
|
1024
|
+
export async function runGateway(options, explicitCommand, deps = {}) {
|
|
1025
|
+
const { resolve = resolveAgentCommand, agentCommand = runAgentCommand, bridge = startNativeMode, exit = process.exit.bind(process), startDir = process.cwd(), } = deps;
|
|
1026
|
+
// These failures are all things the user can act on — a missing .mcp.json,
|
|
1027
|
+
// an unknown registry id, no build for this platform, an unverifiable
|
|
1028
|
+
// download, a mistyped command — so they get a sentence rather than a stack
|
|
1029
|
+
// trace.
|
|
2222
1030
|
const fail = (err) => {
|
|
2223
1031
|
console.error(`[acp-gateway] ${err instanceof Error ? err.message : err}`);
|
|
2224
|
-
|
|
1032
|
+
exit(1);
|
|
2225
1033
|
};
|
|
2226
|
-
|
|
2227
|
-
|
|
1034
|
+
let workspace;
|
|
1035
|
+
let resolved;
|
|
2228
1036
|
try {
|
|
2229
|
-
|
|
1037
|
+
// Optional for the commands that only ask the agent about itself.
|
|
1038
|
+
workspace = loadWorkspace(options.command, options.mcpJsonPath, startDir);
|
|
1039
|
+
resolved = await resolve(options, explicitCommand);
|
|
1040
|
+
assertAgentRunnable(resolved.command[0], Boolean(options.agentId));
|
|
2230
1041
|
}
|
|
2231
1042
|
catch (err) {
|
|
2232
|
-
fail(err);
|
|
1043
|
+
return fail(err);
|
|
2233
1044
|
}
|
|
1045
|
+
const acpCmdArgs = resolved.command;
|
|
1046
|
+
const { agentrqConfig } = workspace;
|
|
2234
1047
|
if (resolved.env) {
|
|
2235
1048
|
// The registry entry's env is part of how that agent must be launched, so
|
|
2236
|
-
// it travels with the command
|
|
1049
|
+
// it travels with the command.
|
|
2237
1050
|
agentrqConfig.env = { ...agentrqConfig.env, ...resolved.env };
|
|
2238
1051
|
}
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
permissionConfig.timeoutMs = options.permissionTimeoutMs;
|
|
2242
|
-
// What running a task fetched from the workspace takes, in the shape the
|
|
2243
|
-
// gateway's own path uses: a command to open a session from.
|
|
2244
|
-
const taskRunDeps = {
|
|
2245
|
-
acpCmdArgsOrConnection: acpCmdArgs,
|
|
2246
|
-
configsOrSessionSwitcher: configs,
|
|
2247
|
-
agentrqConfigOrAcpClient: agentrqConfig,
|
|
2248
|
-
};
|
|
2249
|
-
// Auth commands talk to the agent and exit; they never start bridging tasks.
|
|
2250
|
-
// They run before the bridge connects, so a first-time login still works when
|
|
2251
|
-
// the workspace is unreachable — `callTool` connects on demand if the login
|
|
2252
|
-
// actually needs to reach agentrq.
|
|
2253
|
-
if (command !== "run") {
|
|
2254
|
-
try {
|
|
2255
|
-
await runAgentCommand(command, acpCmdArgs, agentrqConfig, mcpBridge, authMethodId, options.json);
|
|
2256
|
-
}
|
|
2257
|
-
finally {
|
|
2258
|
-
await mcpBridge.close();
|
|
2259
|
-
}
|
|
2260
|
-
process.exit(0);
|
|
2261
|
-
}
|
|
2262
|
-
// Native mode: AgentRQ is the ACP client, and this process only pipes bytes.
|
|
2263
|
-
// None of the MCP bridge below is used.
|
|
2264
|
-
if (options.acpVersion)
|
|
2265
|
-
return startNativeMode(options, acpCmdArgs, agentrqConfig);
|
|
2266
|
-
// After the auth commands, which must not go fetching tasks while someone
|
|
2267
|
-
// logs in. After the bridge, because the queue now reports itself to it — and
|
|
2268
|
-
// fills itself from it: the answer to having room is to go and ask the
|
|
2269
|
-
// workspace for more work, or a limit of three runs one task and waits with
|
|
2270
|
-
// the other two still sitting in the workspace because nothing ever asked.
|
|
2271
|
-
const taskQueue = createSelfFillingTaskQueue(maxConcurrency, mcpBridge, taskRunDeps);
|
|
2272
|
-
let cleanupPromise = null;
|
|
2273
|
-
const cleanup = async (signal) => {
|
|
2274
|
-
if (cleanupPromise)
|
|
2275
|
-
return cleanupPromise;
|
|
2276
|
-
cleanupPromise = (async () => {
|
|
2277
|
-
if (signal) {
|
|
2278
|
-
console.error(`\n[acp-gateway] Received ${signal}, closing active sessions and shutting down...`);
|
|
2279
|
-
}
|
|
2280
|
-
try {
|
|
2281
|
-
await closeAllSessions();
|
|
2282
|
-
}
|
|
2283
|
-
catch (err) {
|
|
2284
|
-
console.error("[acp-gateway] Error closing active sessions:", err);
|
|
2285
|
-
}
|
|
2286
|
-
try {
|
|
2287
|
-
await mcpBridge.close();
|
|
2288
|
-
}
|
|
2289
|
-
catch (err) {
|
|
2290
|
-
console.error("[acp-gateway] Error closing MCP bridge:", err);
|
|
2291
|
-
}
|
|
2292
|
-
})();
|
|
2293
|
-
return cleanupPromise;
|
|
2294
|
-
};
|
|
2295
|
-
const removeSignalHandlers = setupSignalHandlers(async (signal) => {
|
|
2296
|
-
await cleanup(signal);
|
|
2297
|
-
process.exit(0);
|
|
2298
|
-
});
|
|
2299
|
-
try {
|
|
2300
|
-
// Bridge: MCP -> ACP
|
|
2301
|
-
// When the MCP server sends a notification to 'notifications/claude/channel',
|
|
2302
|
-
// it contains a new task content.
|
|
2303
|
-
mcpBridge.on("task", ({ content, meta }) => {
|
|
2304
|
-
const taskId = extractTaskIdFromMeta(meta);
|
|
2305
|
-
if (taskId) {
|
|
2306
|
-
if (lastTaskContent.get(taskId) === content) {
|
|
2307
|
-
debug(`[bridge] Dropping repetitive task notification for ${taskId}`);
|
|
2308
|
-
return;
|
|
2309
|
-
}
|
|
2310
|
-
lastTaskContent.set(taskId, content);
|
|
2311
|
-
}
|
|
2312
|
-
announceTask(content, taskId);
|
|
2313
|
-
const queuedSeq = nextTaskSeq();
|
|
2314
|
-
// Behind any turn already running for this task, and behind it *before*
|
|
2315
|
-
// asking for a queue slot: one session takes one turn at a time, and two
|
|
2316
|
-
// messages on one chat arrive as two deliveries of one task. Waiting
|
|
2317
|
-
// inside a slot would hold a share of the concurrency limit while doing
|
|
2318
|
-
// nothing at all — enough messages on one chat would hold every slot and
|
|
2319
|
-
// stop the gateway running anything else.
|
|
2320
|
-
runTurnForTask(taskId, () => taskQueue.run(async () => {
|
|
2321
|
-
if (isTaskCancelled(taskId, queuedSeq)) {
|
|
2322
|
-
console.error(`[bridge] Task ${taskId} was cancelled before execution started, skipping`);
|
|
2323
|
-
return;
|
|
2324
|
-
}
|
|
2325
|
-
try {
|
|
2326
|
-
const sessionInfo = await getOrCreateSession(taskId, acpCmdArgs, configs, agentrqConfig, mcpBridge);
|
|
2327
|
-
// Checked again here as well as above: waiting for the turn ahead
|
|
2328
|
-
// of this one is another window in which a cancel can land.
|
|
2329
|
-
if (isTaskCancelled(taskId, queuedSeq)) {
|
|
2330
|
-
console.error(`[bridge] Task ${taskId} was cancelled during session setup, cancelling session`);
|
|
2331
|
-
await sessionInfo.acpClient.cancelTurn(sessionInfo.sessionId);
|
|
2332
|
-
return;
|
|
2333
|
-
}
|
|
2334
|
-
const result = await sessionInfo.connection.prompt({
|
|
2335
|
-
sessionId: sessionInfo.sessionId,
|
|
2336
|
-
prompt: [{ type: "text", text: content }],
|
|
2337
|
-
});
|
|
2338
|
-
await sessionInfo.acpClient.flushReply(sessionInfo.sessionId);
|
|
2339
|
-
await sessionInfo.acpClient.reportStopReason(sessionInfo.sessionId, result.stopReason);
|
|
2340
|
-
announceFinished(taskId, result.stopReason);
|
|
2341
|
-
}
|
|
2342
|
-
catch (err) {
|
|
2343
|
-
console.error("[acp] Error during prompt execution:", err);
|
|
2344
|
-
}
|
|
2345
|
-
})).catch((err) => {
|
|
2346
|
-
console.error("[bridge] Error queuing task:", err);
|
|
2347
|
-
});
|
|
2348
|
-
});
|
|
2349
|
-
// Listen for task cancellation events from the MCP bridge
|
|
2350
|
-
mcpBridge.on("cancel", ({ taskId, reason }) => {
|
|
2351
|
-
handleTaskCancellation(taskId, reason).catch((err) => {
|
|
2352
|
-
console.error("[bridge] Error handling task cancellation:", err);
|
|
2353
|
-
});
|
|
2354
|
-
});
|
|
2355
|
-
mcpBridge.on("setModel", (params) => {
|
|
2356
|
-
handleSetModel(params, mcpBridge).catch((err) => {
|
|
2357
|
-
console.error("[bridge] Error handling model selection:", err);
|
|
2358
|
-
});
|
|
2359
|
-
});
|
|
2360
|
-
registerConcurrencyListeners(mcpBridge, taskQueue);
|
|
2361
|
-
// Everything above is listening; nothing below can be missed.
|
|
2362
|
-
//
|
|
2363
|
-
// The agent comes up before the workspace is told anything, so a task can
|
|
2364
|
-
// never be handed to a gateway whose agent is not ready — or, if it needs a
|
|
2365
|
-
// login nobody can give it, to one that will never be ready. Awaited for
|
|
2366
|
-
// that reason: whatever the workspace learns next, it learns about an agent
|
|
2367
|
-
// that already exists.
|
|
2368
|
-
//
|
|
2369
|
-
// The handlers above are registered first because opening that session
|
|
2370
|
-
// sends notifications, and sending one opens the connection. A task pushed
|
|
2371
|
-
// between the connection opening and something listening for it is a task
|
|
2372
|
-
// dropped on the floor.
|
|
2373
|
-
const idle = await openIdleSession(acpCmdArgs, configs, agentrqConfig, mcpBridge, loginCommandFor(options.agentId, explicitCommand));
|
|
2374
|
-
if (idle === "unauthenticated") {
|
|
2375
|
-
// Nothing to unwind: the agent was terminated where it was spawned, and
|
|
2376
|
-
// the workspace connection below has not been opened yet.
|
|
2377
|
-
removeSignalHandlers();
|
|
2378
|
-
process.exit(1);
|
|
2379
|
-
}
|
|
2380
|
-
await mcpBridge.connect();
|
|
2381
|
-
// Said before any task runs, because that is when a human looking at the
|
|
2382
|
-
// workspace wants to know how much work it will take at once — and because
|
|
2383
|
-
// the control cannot be rendered at all until the workspace knows both the
|
|
2384
|
-
// current limit and that this gateway is one that will act on a change.
|
|
2385
|
-
void reportConcurrency(mcpBridge, taskQueue);
|
|
2386
|
-
// Only when the agent has not spoken for itself. A session that came up
|
|
2387
|
-
// already reported the agent's own name, title and version from its
|
|
2388
|
-
// handshake, and the registry's entry is a coarser answer to the same
|
|
2389
|
-
// question — sending it after would replace what the agent said about
|
|
2390
|
-
// itself with what an index says about it, dropping the title and swapping
|
|
2391
|
-
// the running version for a published one.
|
|
2392
|
-
if (idle !== "ready" && resolved.identity) {
|
|
2393
|
-
void sendAgentIdentity(mcpBridge, resolved.identity);
|
|
2394
|
-
}
|
|
2395
|
-
// Initial fill: every slot the limit allows, not just the first. A gateway
|
|
2396
|
-
// that comes up to a workspace with work waiting should start as much of it
|
|
2397
|
-
// as it is allowed to run.
|
|
2398
|
-
//
|
|
2399
|
-
// Not awaited for the work itself — this resolves once the slots are filled,
|
|
2400
|
-
// and the tasks in them run on past it.
|
|
2401
|
-
await drainPendingTasks(mcpBridge, taskQueue, { ...taskRunDeps, taskQueue });
|
|
2402
|
-
// Keep the process alive
|
|
2403
|
-
await new Promise(() => { });
|
|
2404
|
-
}
|
|
2405
|
-
catch (error) {
|
|
2406
|
-
console.error("[acp-gateway] Error:", error);
|
|
2407
|
-
}
|
|
2408
|
-
finally {
|
|
2409
|
-
removeSignalHandlers();
|
|
2410
|
-
await cleanup();
|
|
2411
|
-
process.exit(0);
|
|
2412
|
-
}
|
|
2413
|
-
}
|
|
2414
|
-
/**
|
|
2415
|
-
* Takes the next not-started task off the workspace.
|
|
2416
|
-
*
|
|
2417
|
-
* `getTask` with no task id dequeues one task, so this is one task per call —
|
|
2418
|
-
* which is exactly why the gateway has to call it again to fill a second slot.
|
|
2419
|
-
*
|
|
2420
|
-
* Never throws: a workspace that cannot be reached is an outcome like any
|
|
2421
|
-
* other here, and the caller is in the middle of filling slots.
|
|
2422
|
-
*/
|
|
2423
|
-
export async function fetchNextTask(mcpBridge) {
|
|
2424
|
-
debug("[bridge] Checking for next task via MCP server...");
|
|
2425
|
-
// Stamped before the fetch, so a cancel that arrives while `getTask` is in
|
|
2426
|
-
// flight (or while the session is being opened) still stops the task.
|
|
2427
|
-
const queuedSeq = nextTaskSeq();
|
|
2428
|
-
try {
|
|
2429
|
-
const result = await callTaskAction(mcpBridge, "get");
|
|
2430
|
-
if (result.isError) {
|
|
2431
|
-
console.error("[mcp] Error getting next task:", result.content);
|
|
2432
|
-
return { status: "failed" };
|
|
2433
|
-
}
|
|
2434
|
-
const contentBlock = result.content;
|
|
2435
|
-
const content = contentBlock[0];
|
|
2436
|
-
if (!content ||
|
|
2437
|
-
!content.text ||
|
|
2438
|
-
content.text.includes("no pending tasks exist")) {
|
|
2439
|
-
debug("[bridge] No pending tasks available.");
|
|
2440
|
-
return { status: "empty" };
|
|
2441
|
-
}
|
|
2442
|
-
const text = content.text;
|
|
2443
|
-
const taskId = extractTaskIdFromText(text);
|
|
2444
|
-
if (taskId) {
|
|
2445
|
-
if (lastTaskContent.get(taskId) === text) {
|
|
2446
|
-
debug(`[bridge] Dropping repetitive checked task for ${taskId}`);
|
|
2447
|
-
return { status: "skipped" };
|
|
2448
|
-
}
|
|
2449
|
-
lastTaskContent.set(taskId, text);
|
|
2450
|
-
}
|
|
2451
|
-
announceTask(text, taskId);
|
|
2452
|
-
return { status: "task", task: { text, taskId, queuedSeq } };
|
|
1052
|
+
if (options.command === "run") {
|
|
1053
|
+
return bridge(options, acpCmdArgs, workspace);
|
|
2453
1054
|
}
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
}
|
|
2458
|
-
}
|
|
2459
|
-
/**
|
|
2460
|
-
* Hands a fetched task to the agent, through the queue and behind any turn the
|
|
2461
|
-
* task already has running.
|
|
2462
|
-
*
|
|
2463
|
-
* Resolves when the agent is done with it, so a caller that wants to fill the
|
|
2464
|
-
* *next* slot must not wait for this one.
|
|
2465
|
-
*/
|
|
2466
|
-
export async function startPendingTask(task, mcpBridge, deps) {
|
|
2467
|
-
const { text, taskId, queuedSeq } = task;
|
|
2468
|
-
const runFn = async () => {
|
|
2469
|
-
if (isTaskCancelled(taskId, queuedSeq)) {
|
|
2470
|
-
console.error(`[bridge] Task ${taskId} was cancelled before execution started, skipping`);
|
|
2471
|
-
return;
|
|
2472
|
-
}
|
|
2473
|
-
let connectionToUse;
|
|
2474
|
-
let acpClientToUse;
|
|
2475
|
-
let sessionIdToUse;
|
|
2476
|
-
let actualAcpCmdArgs = [];
|
|
2477
|
-
let actualConfigs = [];
|
|
2478
|
-
let actualAgentrqConfig;
|
|
2479
|
-
if (Array.isArray(deps.acpCmdArgsOrConnection)) {
|
|
2480
|
-
actualAcpCmdArgs = deps.acpCmdArgsOrConnection;
|
|
2481
|
-
actualConfigs = deps.configsOrSessionSwitcher;
|
|
2482
|
-
actualAgentrqConfig = deps.agentrqConfigOrAcpClient;
|
|
2483
|
-
}
|
|
2484
|
-
else {
|
|
2485
|
-
connectionToUse = deps.acpCmdArgsOrConnection;
|
|
2486
|
-
acpClientToUse = deps.agentrqConfigOrAcpClient;
|
|
2487
|
-
const switcher = deps.configsOrSessionSwitcher;
|
|
2488
|
-
if (switcher && typeof switcher.ensureForTask === "function") {
|
|
2489
|
-
sessionIdToUse = await switcher.ensureForTask(taskId);
|
|
2490
|
-
}
|
|
2491
|
-
actualAcpCmdArgs = deps.acpCmdArgs || [];
|
|
2492
|
-
actualConfigs = deps.configs || [];
|
|
2493
|
-
actualAgentrqConfig = deps.agentrqConfig;
|
|
2494
|
-
}
|
|
2495
|
-
if (!connectionToUse) {
|
|
2496
|
-
const sessionInfo = await getOrCreateSession(taskId, actualAcpCmdArgs, actualConfigs, actualAgentrqConfig, mcpBridge);
|
|
2497
|
-
connectionToUse = sessionInfo.connection;
|
|
2498
|
-
sessionIdToUse = sessionInfo.sessionId;
|
|
2499
|
-
acpClientToUse = sessionInfo.acpClient;
|
|
2500
|
-
}
|
|
2501
|
-
// Spawning the agent and opening the session takes seconds; a cancel
|
|
2502
|
-
// that lands in that window has no turn to stop yet, so check again
|
|
2503
|
-
// before handing the agent the work.
|
|
2504
|
-
if (isTaskCancelled(taskId, queuedSeq)) {
|
|
2505
|
-
console.error(`[bridge] Task ${taskId} was cancelled during session setup, cancelling session`);
|
|
2506
|
-
await acpClientToUse?.cancelTurn(sessionIdToUse);
|
|
2507
|
-
return;
|
|
2508
|
-
}
|
|
2509
|
-
const promptResult = await connectionToUse.prompt({
|
|
2510
|
-
sessionId: sessionIdToUse,
|
|
2511
|
-
prompt: [{ type: "text", text }],
|
|
2512
|
-
});
|
|
2513
|
-
await acpClientToUse.flushReply(sessionIdToUse);
|
|
2514
|
-
await acpClientToUse.reportStopReason(sessionIdToUse, promptResult.stopReason);
|
|
2515
|
-
announceFinished(taskId, promptResult.stopReason);
|
|
2516
|
-
};
|
|
2517
|
-
// Serialised against any turn already running for this task, for the
|
|
2518
|
-
// reason runTurnForTask records: this path and the push notification can
|
|
2519
|
-
// both be handed the same task, and word it differently enough that the
|
|
2520
|
-
// repetition guard drops neither.
|
|
2521
|
-
//
|
|
2522
|
-
// Outside the queue slot rather than inside it, so a delivery that is
|
|
2523
|
-
// only waiting for the turn ahead of it is not also holding a share of
|
|
2524
|
-
// the concurrency limit while it waits.
|
|
2525
|
-
await runTurnForTask(taskId, () => deps.taskQueue ? deps.taskQueue.run(runFn) : runFn());
|
|
2526
|
-
}
|
|
2527
|
-
/** How many more tasks the queue could start right now. */
|
|
2528
|
-
export function freeSlots(queue) {
|
|
2529
|
-
return Math.max(0, queue.getMaxConcurrency() - queue.getActiveCount() - queue.getQueueLength());
|
|
2530
|
-
}
|
|
2531
|
-
/**
|
|
2532
|
-
* The drain in progress, if one is, and whether room appeared while it ran.
|
|
2533
|
-
*
|
|
2534
|
-
* One drain at a time, for the same reason there is one concurrency report at
|
|
2535
|
-
* a time: every trigger for this — a task finishing, a limit being raised —
|
|
2536
|
-
* can land while a drain is already waiting on `getTask`, and a second drain
|
|
2537
|
-
* started there would be asking the workspace for the task the first one is
|
|
2538
|
-
* about to be handed.
|
|
2539
|
-
*
|
|
2540
|
-
* The flag is what keeps collapsing them from losing one. A slot that came
|
|
2541
|
-
* free during a fetch is real, and the drain that swallowed the news may
|
|
2542
|
-
* already have decided the workspace was empty — so the news is answered once
|
|
2543
|
-
* that drain finishes rather than dropped.
|
|
2544
|
-
*/
|
|
2545
|
-
let drainOnTheWire = null;
|
|
2546
|
-
let capacityMovedAgain = false;
|
|
2547
|
-
/** Forgets any drain in flight. For tests. */
|
|
2548
|
-
export function resetPendingTaskDrain() {
|
|
2549
|
-
drainOnTheWire = null;
|
|
2550
|
-
capacityMovedAgain = false;
|
|
2551
|
-
}
|
|
2552
|
-
/**
|
|
2553
|
-
* How many repeats in a row the drain will take before it stops asking.
|
|
2554
|
-
*
|
|
2555
|
-
* A repeat has been dequeued and dropped, so the slot it should have filled is
|
|
2556
|
-
* still free and the task behind it may well fill it — but a workspace handing
|
|
2557
|
-
* back the same task forever must not hold the gateway in a fetch loop.
|
|
2558
|
-
*/
|
|
2559
|
-
export const MAX_SKIPPED_FETCHES = 3;
|
|
2560
|
-
/**
|
|
2561
|
-
* How often the self-filling queue checks for work on its own while idle.
|
|
2562
|
-
*
|
|
2563
|
-
* The event-driven path above covers a task finishing and freeing a slot, but
|
|
2564
|
-
* a queue with nothing active has no such event to wait for — a workspace
|
|
2565
|
-
* empty at startup, or one that drained to empty and stayed there, would
|
|
2566
|
-
* otherwise never be asked again. This is the fallback for exactly that gap,
|
|
2567
|
-
* not a replacement for the event-driven check.
|
|
2568
|
-
*/
|
|
2569
|
-
export const IDLE_TASK_POLL_INTERVAL_MS = 40_000;
|
|
2570
|
-
/**
|
|
2571
|
-
* Fills every free slot the queue has with work from the workspace.
|
|
2572
|
-
*
|
|
2573
|
-
* The gateway used to ask for exactly one task, once, at startup — which was
|
|
2574
|
-
* the whole story while it could only run one. Above that, three tasks waiting
|
|
2575
|
-
* in a workspace and three slots here meant one task running and two slots
|
|
2576
|
-
* idle, because nothing ever went back to ask for the second and third.
|
|
2577
|
-
*
|
|
2578
|
-
* Fetches are sequential and the runs are not: `getTask` dequeues a task, so
|
|
2579
|
-
* two fetches in flight at once are two chances to be handed the same one,
|
|
2580
|
-
* while waiting for a task to *finish* before fetching the next would defeat
|
|
2581
|
-
* the point entirely. So each task is started and left to run, and the next
|
|
2582
|
-
* fetch goes out immediately behind it.
|
|
2583
|
-
*
|
|
2584
|
-
* Stops as soon as the workspace says it has nothing — the run that frees the
|
|
2585
|
-
* next slot brings us back here anyway.
|
|
2586
|
-
*/
|
|
2587
|
-
export function drainPendingTasks(mcpBridge, queue, deps) {
|
|
2588
|
-
if (drainOnTheWire) {
|
|
2589
|
-
capacityMovedAgain = true;
|
|
2590
|
-
return drainOnTheWire;
|
|
2591
|
-
}
|
|
2592
|
-
// The slot is cleared from a `.finally` on the promise rather than from
|
|
2593
|
-
// inside `pullUntilFull`. An async function that never reaches an `await` —
|
|
2594
|
-
// which is exactly what a drain with no free slot is — runs to completion
|
|
2595
|
-
// before its promise is ever handed back, so a clear written inside it would
|
|
2596
|
-
// happen *before* the assignment below and leave a settled promise sitting
|
|
2597
|
-
// in the slot for the rest of the process. Every later drain would then find
|
|
2598
|
-
// the slot occupied and quietly fetch nothing, which is this whole feature
|
|
2599
|
-
// switching itself off. `.finally` cannot beat the assignment: it settles a
|
|
2600
|
-
// microtask later at the earliest.
|
|
2601
|
-
const drain = pullUntilFull(mcpBridge, queue, deps).finally(() => {
|
|
2602
|
-
drainOnTheWire = null;
|
|
2603
|
-
});
|
|
2604
|
-
drainOnTheWire = drain;
|
|
2605
|
-
return drain;
|
|
2606
|
-
}
|
|
2607
|
-
/** Fetches and starts tasks until the queue is full or the workspace is empty. */
|
|
2608
|
-
async function pullUntilFull(mcpBridge, queue, deps) {
|
|
2609
|
-
do {
|
|
2610
|
-
// Read at the top of each pass: room that appears while this one is
|
|
2611
|
-
// mid-fetch is answered by the next pass rather than lost, and joining a
|
|
2612
|
-
// drain already running is what set it.
|
|
2613
|
-
capacityMovedAgain = false;
|
|
2614
|
-
// Tasks started but waiting on an earlier turn for their own chat. They
|
|
2615
|
-
// have taken no slot and will not until that turn ends, so the queue still
|
|
2616
|
-
// reads as having room — and without counting them the loop fetches
|
|
2617
|
-
// against that same room over and over, emptying the workspace into this
|
|
2618
|
-
// process where nothing else can hand the work to anyone else.
|
|
2619
|
-
let parked = 0;
|
|
2620
|
-
let skipped = 0;
|
|
2621
|
-
while (freeSlots(queue) - parked > 0) {
|
|
2622
|
-
const outcome = await fetchNextTask(mcpBridge);
|
|
2623
|
-
if (outcome.status === "empty" || outcome.status === "failed")
|
|
2624
|
-
break;
|
|
2625
|
-
if (outcome.status === "skipped") {
|
|
2626
|
-
// Dropped as a repeat of something already running: the slot is still
|
|
2627
|
-
// free, so try what is behind it rather than abandoning the slot.
|
|
2628
|
-
if (++skipped >= MAX_SKIPPED_FETCHES)
|
|
2629
|
-
break;
|
|
2630
|
-
continue;
|
|
2631
|
-
}
|
|
2632
|
-
skipped = 0;
|
|
2633
|
-
const { task } = outcome;
|
|
2634
|
-
const heldBefore = queue.getActiveCount() + queue.getQueueLength();
|
|
2635
|
-
// Deliberately not awaited: this task is running now, and the slot
|
|
2636
|
-
// beside it is what this loop is here to fill.
|
|
2637
|
-
void startPendingTask(task, mcpBridge, { ...deps, taskQueue: queue }).catch((err) => {
|
|
2638
|
-
console.error(`[bridge] Error running task ${task.taskId ?? "(unnamed)"}:`, err);
|
|
2639
|
-
});
|
|
2640
|
-
// `run` takes its slot before it yields, so a queue that did not move is
|
|
2641
|
-
// a task parked behind a turn rather than one holding a slot.
|
|
2642
|
-
if (queue.getActiveCount() + queue.getQueueLength() === heldBefore)
|
|
2643
|
-
parked++;
|
|
2644
|
-
}
|
|
2645
|
-
} while (capacityMovedAgain);
|
|
2646
|
-
}
|
|
2647
|
-
/**
|
|
2648
|
-
* Builds a queue that goes and fetches its own work.
|
|
2649
|
-
*
|
|
2650
|
-
* Out here rather than inline in `main()` for the reason `createTaskQueue`
|
|
2651
|
-
* records: `main()` spawns processes and never returns, so wiring written
|
|
2652
|
-
* inside it is wiring nothing exercises. And this is wiring worth exercising —
|
|
2653
|
-
* it is the whole of "a gateway with room for three tasks runs three tasks".
|
|
2654
|
-
*
|
|
2655
|
-
* The callback names the queue it is being handed to, which is safe for the
|
|
2656
|
-
* same reason `createTaskQueue`'s is: it only ever runs later, from inside the
|
|
2657
|
-
* queue's own methods.
|
|
2658
|
-
*/
|
|
2659
|
-
export function createSelfFillingTaskQueue(maxConcurrency, mcpBridge, deps) {
|
|
2660
|
-
const queue = createTaskQueue(maxConcurrency, mcpBridge, () => {
|
|
2661
|
-
void drainPendingTasks(mcpBridge, queue, { ...deps, taskQueue: queue });
|
|
2662
|
-
});
|
|
2663
|
-
// Only while idle: a task running (or waiting) will itself free a slot and
|
|
2664
|
-
// trigger the check above, so a tick that found active work would just be
|
|
2665
|
-
// asking the workspace something the event-driven path already has covered.
|
|
2666
|
-
setInterval(() => {
|
|
2667
|
-
if (queue.getActiveCount() > 0)
|
|
2668
|
-
return;
|
|
2669
|
-
void drainPendingTasks(mcpBridge, queue, { ...deps, taskQueue: queue });
|
|
2670
|
-
}, IDLE_TASK_POLL_INTERVAL_MS).unref();
|
|
2671
|
-
return queue;
|
|
1055
|
+
// One-shot commands talk to the agent and exit.
|
|
1056
|
+
await agentCommand(options.command, acpCmdArgs, agentrqConfig.env, options.authMethodId, options.json);
|
|
1057
|
+
exit(0);
|
|
2672
1058
|
}
|
|
2673
1059
|
if (process.env.NODE_ENV !== "test") {
|
|
2674
|
-
//
|
|
2675
|
-
// own reconnect logic (mcpClient.ts), so a stray rejected promise or async
|
|
1060
|
+
// The bridge reconnects on its own, so a stray rejected promise or async
|
|
2676
1061
|
// error from a dropped connection should be logged, not fatal. Without these
|
|
2677
1062
|
// nets, Node terminates the process on the first unhandled rejection.
|
|
2678
1063
|
process.on("unhandledRejection", (reason) => {
|
|
@@ -2681,8 +1066,8 @@ if (process.env.NODE_ENV !== "test") {
|
|
|
2681
1066
|
process.on("uncaughtException", (err) => {
|
|
2682
1067
|
console.error("[acp-gateway] Uncaught exception (continuing):", err);
|
|
2683
1068
|
});
|
|
2684
|
-
// A rejection from main() itself means startup failed
|
|
2685
|
-
//
|
|
1069
|
+
// A rejection from main() itself means startup failed — that is genuinely
|
|
1070
|
+
// fatal, so exit.
|
|
2686
1071
|
main().catch((err) => {
|
|
2687
1072
|
console.error("[fatal]", err);
|
|
2688
1073
|
process.exit(1);
|