agy-delegate-mcp 0.0.0 → 1.0.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/CHANGELOG.md +25 -0
- package/LICENSE +21 -0
- package/PRIVACY.md +11 -0
- package/README.md +75 -2
- package/SECURITY.md +35 -0
- package/TERMS.md +9 -0
- package/package.json +59 -3
- package/src/acp-client.js +198 -0
- package/src/agent-reported-files.js +24 -0
- package/src/delegate.js +533 -0
- package/src/doctor.js +202 -0
- package/src/errors.js +20 -0
- package/src/jsonrpc.js +145 -0
- package/src/model-options.js +76 -0
- package/src/proc.js +36 -0
- package/src/request-router.js +33 -0
- package/src/server.js +432 -0
- package/src/session-supervisor.js +125 -0
- package/src/spawn.js +29 -0
- package/src/turn-state.js +159 -0
- package/src/version.js +24 -0
package/src/server.js
ADDED
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import process from "node:process";
|
|
3
|
+
import { realpathSync } from "node:fs";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
6
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
import { runDelegate as runDelegateDefault } from "./delegate.js";
|
|
9
|
+
import { runDoctor as runDoctorDefault } from "./doctor.js";
|
|
10
|
+
import { VERSION, readPackageVersion } from "./version.js";
|
|
11
|
+
import { DETACHED } from "./proc.js";
|
|
12
|
+
|
|
13
|
+
const ICON_BASE = `https://raw.githubusercontent.com/andreilungeanu/agy-delegate-mcp/v${VERSION}/assets`;
|
|
14
|
+
/** @type {Array<{ src: string, mimeType: string, sizes: string[], theme: "light" | "dark" }>} */
|
|
15
|
+
const SERVER_ICONS = [
|
|
16
|
+
{ src: `${ICON_BASE}/logo-light.png`, mimeType: "image/png", sizes: ["1024x1024"], theme: "light" },
|
|
17
|
+
{ src: `${ICON_BASE}/logo-dark.png`, mimeType: "image/png", sizes: ["1024x1024"], theme: "dark" },
|
|
18
|
+
];
|
|
19
|
+
|
|
20
|
+
const nodeMajor = Number(process.versions.node.split(".")[0]);
|
|
21
|
+
if (nodeMajor < 20) {
|
|
22
|
+
console.error(`agy-delegate-mcp requires Node 20+ (found ${process.versions.node})`);
|
|
23
|
+
process.exit(1);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// sessionId -> the set of delegations currently running on it. A set, not a single handle,
|
|
27
|
+
// because a resume can race the turn it resumes: both are live, both are cancellable, and
|
|
28
|
+
// keying one handle per id let whichever finished first deregister the other — after which
|
|
29
|
+
// cancel reported a running session as already ended.
|
|
30
|
+
const inFlight = new Map();
|
|
31
|
+
function registerInFlight(map, sessionId, handle) {
|
|
32
|
+
const handles = map.get(sessionId);
|
|
33
|
+
if (handles) handles.add(handle);
|
|
34
|
+
else map.set(sessionId, new Set([handle]));
|
|
35
|
+
}
|
|
36
|
+
/** @returns {import("@modelcontextprotocol/sdk/types.js").CallToolResult} */
|
|
37
|
+
function cancelResult(status, sessionId) {
|
|
38
|
+
return { content: [{ type: "text", text: JSON.stringify({ status, sessionId }) }] };
|
|
39
|
+
}
|
|
40
|
+
function unregisterInFlight(map, sessionId, handle) {
|
|
41
|
+
const handles = map.get(sessionId);
|
|
42
|
+
if (!handles) return;
|
|
43
|
+
handles.delete(handle);
|
|
44
|
+
if (handles.size === 0) map.delete(sessionId);
|
|
45
|
+
}
|
|
46
|
+
// Delegations whose session has not opened yet. inFlight is keyed by session id, and that id
|
|
47
|
+
// arrives about 3.4s after the agent process does — so between client.start() and session/new
|
|
48
|
+
// there is a live, auto-approved agent that the map cannot name. Shutdown walks this too.
|
|
49
|
+
// cancel deliberately does not: an id the caller has never been given is not one it can pass.
|
|
50
|
+
const pendingDelegations = new Set();
|
|
51
|
+
|
|
52
|
+
// Session ids seen this process, kept after the turn ends so cancel can tell a finished
|
|
53
|
+
// session (resumable, only the turn is over) from an id that never existed. Bounded so a
|
|
54
|
+
// long-lived server does not grow without limit.
|
|
55
|
+
const seenSessions = new Set();
|
|
56
|
+
const SEEN_SESSIONS_CAP = 500;
|
|
57
|
+
function rememberSession(set, id) {
|
|
58
|
+
if (id == null) return;
|
|
59
|
+
// Set iteration order makes the delete-then-add a small LRU: a session that is still being
|
|
60
|
+
// resumed moves back to the recent end, so it outlives an equally old id that was seen once
|
|
61
|
+
// and never again. Without it the id a caller is actually working with ages out on insertion
|
|
62
|
+
// order alone, and cancel then calls a live, resumable session one that never existed.
|
|
63
|
+
if (set.has(id)) set.delete(id);
|
|
64
|
+
set.add(id);
|
|
65
|
+
if (set.size > SEEN_SESSIONS_CAP) set.delete(set.values().next().value);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Loaded at connect, before any tool schema is, so this carries only pre-call facts: what a
|
|
69
|
+
// caller needs to decide whether to delegate at all. Call-time facts belong on the parameter
|
|
70
|
+
// descriptions, read while the call is being written.
|
|
71
|
+
export const SERVER_INSTRUCTIONS = `Delegate coding work to Antigravity (agy) through the delegate tool. Every permission the agent requests is auto-approved, in every mode: agent/plan/ask reach any file the user account can, and mode instructs the agent rather than limiting it. Scope workspace tightly and review the git diff after every run — filesReportedByEditTools carries only what the agent's edit tools reported; the diff is authoritative.`;
|
|
72
|
+
|
|
73
|
+
// No outputSchema: that also requires structuredContent, and a host that reads both (Codex)
|
|
74
|
+
// puts the payload in context twice. One JSON text block; the .strict() copy is in
|
|
75
|
+
// delegate.test.js. Field meanings: skills/delegate/reference.md. cancel status lives on
|
|
76
|
+
// its tool description.
|
|
77
|
+
export const delegateOutputShape = {
|
|
78
|
+
result: z.string(),
|
|
79
|
+
resultSource: z.enum(["pre-tool-fallback", "none"]).optional(),
|
|
80
|
+
effectiveModel: z.string().optional(),
|
|
81
|
+
effectiveEffort: z.record(z.string(), z.string()).optional(),
|
|
82
|
+
stopReason: z.string().optional(),
|
|
83
|
+
sessionId: z.string(),
|
|
84
|
+
filesReportedByEditTools: z.array(z.string()).optional(),
|
|
85
|
+
resumed: z.boolean().optional(),
|
|
86
|
+
cancelRequested: z.boolean().optional(),
|
|
87
|
+
protocolWarnings: z.array(z.string()).optional(),
|
|
88
|
+
plan: z.object({
|
|
89
|
+
path: z.string(),
|
|
90
|
+
overview: z.string().optional(),
|
|
91
|
+
detail: z.string().optional(),
|
|
92
|
+
}).optional(),
|
|
93
|
+
artifacts: z.array(z.object({
|
|
94
|
+
path: z.string(),
|
|
95
|
+
summary: z.string().optional(),
|
|
96
|
+
})).optional(),
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
// Same in-repo contract as delegateOutputShape. Relayed agent fields stay unknown so a
|
|
100
|
+
// weird protocolVersion is a diagnostic, not a failed call. doctor.test.js holds the
|
|
101
|
+
// strict copy. Handshake is its own shape: a .strict() on agent does not look inside it.
|
|
102
|
+
export const doctorHandshakeShape = {
|
|
103
|
+
ok: z.boolean(),
|
|
104
|
+
error: z.string().optional(),
|
|
105
|
+
protocolVersion: z.unknown().optional(),
|
|
106
|
+
agentCapabilities: z.unknown().optional(),
|
|
107
|
+
models: z.array(z.unknown()).optional(),
|
|
108
|
+
currentModel: z.unknown().optional(),
|
|
109
|
+
modes: z.array(z.unknown()).optional(),
|
|
110
|
+
tier: z.unknown().optional(),
|
|
111
|
+
// Built here rather than relayed, so it gets a real type where its neighbours get z.unknown().
|
|
112
|
+
currentModelOptions: z.array(z.object({
|
|
113
|
+
id: z.string(),
|
|
114
|
+
name: z.string().optional(),
|
|
115
|
+
category: z.string().optional(),
|
|
116
|
+
values: z.array(z.string()),
|
|
117
|
+
currentValue: z.string().optional(),
|
|
118
|
+
})).optional(),
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
export const doctorAgentShape = {
|
|
122
|
+
found: z.boolean(),
|
|
123
|
+
command: z.string(),
|
|
124
|
+
version: z.string().nullable(),
|
|
125
|
+
error: z.string().optional(),
|
|
126
|
+
handshake: z.object(doctorHandshakeShape).passthrough().optional(),
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
// agent is split out because a top-level .strict() does not look inside a nested object.
|
|
130
|
+
export const doctorOutputShape = {
|
|
131
|
+
plugin: z.object({ version: z.string() }).passthrough(),
|
|
132
|
+
client: z.object({
|
|
133
|
+
name: z.string().nullable(),
|
|
134
|
+
version: z.string().nullable(),
|
|
135
|
+
capabilities: z.record(z.string(), z.unknown()),
|
|
136
|
+
}).passthrough(),
|
|
137
|
+
agent: z.object(doctorAgentShape).passthrough(),
|
|
138
|
+
runtime: z.object({
|
|
139
|
+
node: z.string(),
|
|
140
|
+
platform: z.string(),
|
|
141
|
+
arch: z.string(),
|
|
142
|
+
cwd: z.string(),
|
|
143
|
+
transport: z.literal("stdio"),
|
|
144
|
+
}),
|
|
145
|
+
env: z.record(z.string(), z.unknown()),
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
export const delegateInputSchema = z.object({
|
|
149
|
+
spec: z.string().trim().min(1, "spec must not be blank").describe("Task brief: goal, scope, fixed decisions quoted exactly, acceptance criteria. Sent as written. Point at files to read rather than pasting code, or attach them with contextFiles."),
|
|
150
|
+
mode: z.enum(["agent", "plan", "ask"]).default("agent").describe("agent implements; plan writes a plan, returned as plan; ask answers. plan and ask are instructions to the agent, not limits."),
|
|
151
|
+
resumeSessionId: z.string().optional().describe("Continue an existing agy session."),
|
|
152
|
+
workspace: z.string().trim().min(1, "workspace must not be blank").describe("The agent's working directory, not a limit. Smallest directory holding the task's files; with no such directory the project root is the floor. Must already exist; never create one for the call."),
|
|
153
|
+
model: z.string().trim().min(1, "model must be a non-empty string").optional().describe("agy base model id, no level suffix: gemini-4-neon, gemini-3.8-flash. Omitted, agy's default runs and effectiveModel names it. doctor deep:true lists every id."),
|
|
154
|
+
// Which values a model offers is only knowable after selecting it, so this stays an open
|
|
155
|
+
// string and the bridge validates the exact token against the live option list.
|
|
156
|
+
effort: z.string().trim().min(1).optional().describe("agy thinking level for the selected model (low, medium, high, xhigh). Levels differ per model; invalid values fail before the prompt and name the accepted set. Pass only when the user asks for agy effort — the host's own reasoning setting is unrelated."),
|
|
157
|
+
contextFiles: z.array(z.string()).optional().describe("Paths to attach instead of pasting contents into spec. Text becomes references the agent may open; images (png/jpg/gif/webp, <5MB) are sent inline. Relative paths resolve against workspace but are not limited to it. Skips are reported in protocolWarnings, never fatal."),
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* @param {{
|
|
162
|
+
* args: any, extra?: any,
|
|
163
|
+
* runDelegate: (opts: any) => Promise<any>,
|
|
164
|
+
* inFlight: Map<string, Set<any>>,
|
|
165
|
+
* pending?: Set<any>,
|
|
166
|
+
* seenSessions?: Set<string>,
|
|
167
|
+
* }} deps
|
|
168
|
+
* @returns {Promise<import("@modelcontextprotocol/sdk/types.js").CallToolResult>}
|
|
169
|
+
*/
|
|
170
|
+
export async function runDelegateTool({ args, extra, runDelegate, inFlight, pending = new Set(), seenSessions = new Set() }) {
|
|
171
|
+
const { spec, mode, resumeSessionId, workspace, model, effort, contextFiles } = args;
|
|
172
|
+
|
|
173
|
+
const progressToken = extra?._meta?.progressToken;
|
|
174
|
+
/** @type {(message: string) => void} */
|
|
175
|
+
let onProgress = () => {};
|
|
176
|
+
if (progressToken != null) {
|
|
177
|
+
let progress = 0;
|
|
178
|
+
onProgress = (message) => {
|
|
179
|
+
// sendNotification is async: its rejection settles outside this try and would exit the
|
|
180
|
+
// server. The try stays for a sync throw, which lands before Promise.resolve can wrap it.
|
|
181
|
+
try {
|
|
182
|
+
Promise.resolve(extra.sendNotification({
|
|
183
|
+
method: "notifications/progress",
|
|
184
|
+
params: { progressToken, progress: ++progress, message },
|
|
185
|
+
})).catch(() => {});
|
|
186
|
+
} catch {}
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
let capturedSessionId;
|
|
191
|
+
let handle;
|
|
192
|
+
try {
|
|
193
|
+
const out = await runDelegate({
|
|
194
|
+
spec,
|
|
195
|
+
mode,
|
|
196
|
+
resumeSessionId,
|
|
197
|
+
workspace,
|
|
198
|
+
model,
|
|
199
|
+
effort,
|
|
200
|
+
contextFiles,
|
|
201
|
+
onProgress,
|
|
202
|
+
signal: extra?.signal,
|
|
203
|
+
onClientReady: (client) => {
|
|
204
|
+
handle = { client, cancelRequested: false };
|
|
205
|
+
pending.add(handle);
|
|
206
|
+
},
|
|
207
|
+
onSessionReady: (sessionId, client) => {
|
|
208
|
+
capturedSessionId = sessionId;
|
|
209
|
+
// The same handle moves across, so a shutdown racing this boundary finds it on exactly
|
|
210
|
+
// one side of it rather than on neither.
|
|
211
|
+
handle ??= { client, cancelRequested: false };
|
|
212
|
+
pending.delete(handle);
|
|
213
|
+
registerInFlight(inFlight, sessionId, handle);
|
|
214
|
+
rememberSession(seenSessions, sessionId);
|
|
215
|
+
// Emit the id the moment the session opens, before the turn finishes, so a host that
|
|
216
|
+
// can call tools concurrently has something to pass to cancel mid-run — otherwise the
|
|
217
|
+
// id only arrives when delegate returns, by which point there is nothing to cancel.
|
|
218
|
+
// (Hosts that serialize tool calls still cannot cancel in flight; that is a host limit.)
|
|
219
|
+
onProgress(`session ready: ${sessionId}`);
|
|
220
|
+
},
|
|
221
|
+
});
|
|
222
|
+
if (handle?.cancelRequested) out.cancelRequested = true;
|
|
223
|
+
return { content: [{ type: "text", text: JSON.stringify(out) }] };
|
|
224
|
+
} catch (err) {
|
|
225
|
+
return {
|
|
226
|
+
// The reason is already decided upstream; naming it here saves the caller parsing
|
|
227
|
+
// prose to tell a timeout from a rejected argument.
|
|
228
|
+
content: [{ type: "text", text: `delegate failed${err?.reason ? ` [${err.reason}]` : ""}: ` + (err?.message || String(err)) }],
|
|
229
|
+
isError: true,
|
|
230
|
+
};
|
|
231
|
+
} finally {
|
|
232
|
+
// Drops only this delegation's own handle; the id stays registered while another turn
|
|
233
|
+
// is still running on it. A delegation that failed before its session opened is only ever
|
|
234
|
+
// in pending, and one that opened is only ever in the map — the delete covers both.
|
|
235
|
+
if (handle) pending.delete(handle);
|
|
236
|
+
if (capturedSessionId) unregisterInFlight(inFlight, capturedSessionId, handle);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* @param {{
|
|
242
|
+
* runDelegate?: (opts: any) => Promise<any>,
|
|
243
|
+
* runDoctor?: (opts: any) => Promise<any>,
|
|
244
|
+
* forceGraceMs?: number,
|
|
245
|
+
* }} [opts]
|
|
246
|
+
*/
|
|
247
|
+
export function buildServer({ runDelegate: runDelegateInjected, runDoctor: runDoctorInjected, forceGraceMs = 5000 } = {}) {
|
|
248
|
+
const runDelegate = runDelegateInjected || runDelegateDefault;
|
|
249
|
+
const runDoctor = runDoctorInjected || runDoctorDefault;
|
|
250
|
+
const server = new McpServer(
|
|
251
|
+
{ name: "agy-delegate-mcp", version: VERSION, icons: SERVER_ICONS },
|
|
252
|
+
{ instructions: SERVER_INSTRUCTIONS }
|
|
253
|
+
);
|
|
254
|
+
|
|
255
|
+
server.registerTool(
|
|
256
|
+
"delegate",
|
|
257
|
+
{
|
|
258
|
+
description:
|
|
259
|
+
"Delegate a coding task to Antigravity's agy over ACP. Never shell out to agy — use this tool only. Auto-approves every permission the agent requests, in any mode and anywhere on disk. Clarifying questions arrive as prose in result — resume with resumeSessionId to answer. Leave model and effort unset unless the user explicitly asks. See the delegate skill.",
|
|
260
|
+
inputSchema: delegateInputSchema,
|
|
261
|
+
annotations: {
|
|
262
|
+
title: "Delegate coding task to Antigravity",
|
|
263
|
+
readOnlyHint: false,
|
|
264
|
+
destructiveHint: true,
|
|
265
|
+
idempotentHint: false,
|
|
266
|
+
openWorldHint: true,
|
|
267
|
+
},
|
|
268
|
+
},
|
|
269
|
+
async (args, extra) => runDelegateTool({ args, extra, runDelegate, inFlight, pending: pendingDelegations, seenSessions })
|
|
270
|
+
);
|
|
271
|
+
|
|
272
|
+
server.registerTool(
|
|
273
|
+
"cancel",
|
|
274
|
+
{
|
|
275
|
+
description:
|
|
276
|
+
"Best-effort cancel of an in-flight delegation by sessionId. session/cancel is advisory — the agent may finish the turn anyway, and the delegate result then carries cancelRequested. Status: cancelled, killed (agent process observed to exit), not-running (turn already ended, still resumable), not-found (id not in this process's recent session history).",
|
|
277
|
+
inputSchema: {
|
|
278
|
+
sessionId: z.string(),
|
|
279
|
+
force: z.boolean().default(false).describe("Kill the agent process if the turn is still running after a short grace period."),
|
|
280
|
+
},
|
|
281
|
+
annotations: {
|
|
282
|
+
title: "Cancel Antigravity delegation",
|
|
283
|
+
readOnlyHint: false,
|
|
284
|
+
destructiveHint: true,
|
|
285
|
+
idempotentHint: true,
|
|
286
|
+
openWorldHint: false,
|
|
287
|
+
},
|
|
288
|
+
},
|
|
289
|
+
async ({ sessionId, force }) => {
|
|
290
|
+
const handles = inFlight.get(sessionId);
|
|
291
|
+
if (!handles || handles.size === 0) {
|
|
292
|
+
// A finished session and a garbage id are both "not in flight". Reporting them alike
|
|
293
|
+
// would read as "bad id" for a session that ran and is still resumable.
|
|
294
|
+
const known = seenSessions.has(sessionId);
|
|
295
|
+
return cancelResult(known ? "not-running" : "not-found", sessionId);
|
|
296
|
+
}
|
|
297
|
+
// Cancel every turn running on the id: the caller named a session, not one of the
|
|
298
|
+
// turns that happen to share it.
|
|
299
|
+
for (const handle of handles) handle.cancelRequested = true;
|
|
300
|
+
await Promise.all([...handles].map((handle) => handle.client.cancel(sessionId).catch(() => {})));
|
|
301
|
+
if (!force) {
|
|
302
|
+
// The handles stay registered: session/cancel is best-effort, so the turn may still
|
|
303
|
+
// be running. Dropping them here made the natural escalation — cancel, wait, cancel
|
|
304
|
+
// with force — report not-found while the agent was alive. Each delegation's own
|
|
305
|
+
// finally removes its handle when the turn actually settles.
|
|
306
|
+
return cancelResult("cancelled", sessionId);
|
|
307
|
+
}
|
|
308
|
+
await new Promise((r) => setTimeout(r, forceGraceMs));
|
|
309
|
+
const stillRunning = inFlight.get(sessionId);
|
|
310
|
+
if (!stillRunning || stillRunning.size === 0) return cancelResult("cancelled", sessionId);
|
|
311
|
+
// Snapshot before awaiting stop. A resume that registers during teardown must not be
|
|
312
|
+
// swept out of the map — it was never killed, and inFlight.delete(sessionId) would
|
|
313
|
+
// hide it from cancel and shutdown.
|
|
314
|
+
const toKill = [...stillRunning];
|
|
315
|
+
const observed = await Promise.all(
|
|
316
|
+
toKill.map((handle) => Promise.resolve(handle.client.stop()).catch(() => false))
|
|
317
|
+
);
|
|
318
|
+
// "killed" claims the process is gone, so it needs the exit, not just a dispatched signal.
|
|
319
|
+
// When one does not follow, the handles stay registered and force can be tried again.
|
|
320
|
+
if (!observed.every(Boolean)) return cancelResult("cancelled", sessionId);
|
|
321
|
+
for (const handle of toKill) unregisterInFlight(inFlight, sessionId, handle);
|
|
322
|
+
return cancelResult("killed", sessionId);
|
|
323
|
+
}
|
|
324
|
+
);
|
|
325
|
+
|
|
326
|
+
server.registerTool(
|
|
327
|
+
"doctor",
|
|
328
|
+
{
|
|
329
|
+
description:
|
|
330
|
+
"Setup diagnostics: plugin version, MCP client capabilities, agy launcher resolution. Run when delegation fails or agent.found is false.",
|
|
331
|
+
inputSchema: {
|
|
332
|
+
deep: z
|
|
333
|
+
.boolean()
|
|
334
|
+
.default(false)
|
|
335
|
+
.describe("Run an ACP handshake (start → initialize → newSession) to verify the agent is usable and signed in; adds models, modes, the current model's options and the account tier."),
|
|
336
|
+
},
|
|
337
|
+
annotations: {
|
|
338
|
+
title: "Diagnose Antigravity delegation setup",
|
|
339
|
+
readOnlyHint: true,
|
|
340
|
+
destructiveHint: false,
|
|
341
|
+
idempotentHint: true,
|
|
342
|
+
openWorldHint: false,
|
|
343
|
+
},
|
|
344
|
+
},
|
|
345
|
+
async ({ deep }) => {
|
|
346
|
+
const out = await runDoctor({
|
|
347
|
+
deep,
|
|
348
|
+
getClientInfo: () => ({
|
|
349
|
+
capabilities: server.server.getClientCapabilities(),
|
|
350
|
+
version: server.server.getClientVersion(),
|
|
351
|
+
}),
|
|
352
|
+
});
|
|
353
|
+
return { content: [{ type: "text", text: JSON.stringify(out) }] };
|
|
354
|
+
}
|
|
355
|
+
);
|
|
356
|
+
|
|
357
|
+
return server;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
361
|
+
let isMain = false;
|
|
362
|
+
if (process.argv[1]) {
|
|
363
|
+
try {
|
|
364
|
+
isMain = realpathSync(process.argv[1]) === realpathSync(__filename);
|
|
365
|
+
} catch {
|
|
366
|
+
// An imported module must not fail just because argv[1] is not a file.
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// Kill what is still running, then exit, on any way the host has of going away.
|
|
371
|
+
export function installSignalCleanup(map, {
|
|
372
|
+
pending = new Set(),
|
|
373
|
+
exit = (code) => process.exit(code),
|
|
374
|
+
setExitCode = (code) => { process.exitCode = code; },
|
|
375
|
+
schedule = (fn) => setImmediate(fn),
|
|
376
|
+
stdin = process.stdin,
|
|
377
|
+
} = {}) {
|
|
378
|
+
let shuttingDown = false;
|
|
379
|
+
const shutdown = (code) => {
|
|
380
|
+
// A second trigger skips the wait below: the kills are already dispatched, and a caller
|
|
381
|
+
// that has asked twice wants out now.
|
|
382
|
+
if (shuttingDown) return exit(code);
|
|
383
|
+
shuttingDown = true;
|
|
384
|
+
// Set in the handler, not left to the exit below: a loop that runs dry on its own still
|
|
385
|
+
// has to die with the code the signal asked for, and the scheduled exit may never get a
|
|
386
|
+
// turn to run.
|
|
387
|
+
setExitCode(code);
|
|
388
|
+
const stops = [];
|
|
389
|
+
const dispatch = (handle) => {
|
|
390
|
+
try { stops.push(Promise.resolve(handle.client.stop()).catch(() => {})); } catch {}
|
|
391
|
+
};
|
|
392
|
+
for (const handles of map.values()) for (const handle of handles) dispatch(handle);
|
|
393
|
+
// Delegations still inside their handshake. The agent is already running for these, and this
|
|
394
|
+
// is the only place it is reachable from — they have no session id to be keyed under yet.
|
|
395
|
+
for (const handle of pending) dispatch(handle);
|
|
396
|
+
// On Windows the kill is a separate taskkill process: exiting before it walks the tree
|
|
397
|
+
// orphans everything below the shell wrapper — the ps1 launcher and the versioned agent
|
|
398
|
+
// were measured surviving the server's exit. stop() bounds itself (observed exit or its
|
|
399
|
+
// own deadline), so this wait is short and finite on every platform.
|
|
400
|
+
// Scheduled rather than called from the kill's own continuation, so the exit runs on a
|
|
401
|
+
// clean loop turn instead of on the settlement stack.
|
|
402
|
+
const leave = () => schedule(() => exit(code));
|
|
403
|
+
Promise.all(stops).then(leave, leave);
|
|
404
|
+
};
|
|
405
|
+
// Each agent runs in its own process group on POSIX, so a signal aimed at this process no
|
|
406
|
+
// longer reaches it. Installing a handler replaces Node's default; swallowing Ctrl-C would
|
|
407
|
+
// leak the agent. shutdown() already walks pending, so this covers spawn through session/new.
|
|
408
|
+
if (DETACHED) {
|
|
409
|
+
const signals = /** @type {[NodeJS.Signals, number][]} */ ([["SIGINT", 130], ["SIGTERM", 143]]);
|
|
410
|
+
for (const [signal, code] of signals) process.on(signal, () => shutdown(code));
|
|
411
|
+
}
|
|
412
|
+
// Closing the server's stdin is how a stdio host shuts the transport down, and it is what a
|
|
413
|
+
// host reaches for before it resorts to a signal. The SDK transport does not listen for it —
|
|
414
|
+
// it subscribes to `data` and `error` only — so EOF leaves this process up with a delegation
|
|
415
|
+
// still running and nobody left to hand it to.
|
|
416
|
+
stdin.on("end", () => shutdown(0));
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
if (isMain) {
|
|
420
|
+
// Without this the flag falls through to the transport, which owns stdout and waits on stdin —
|
|
421
|
+
// so confirming an install meant wiring the server into a host first. Reads the package.json
|
|
422
|
+
// beside this file, so it reports the code that is actually running rather than what a
|
|
423
|
+
// manifest pinned. stdout is free here because the transport never starts.
|
|
424
|
+
const argv = process.argv.slice(2);
|
|
425
|
+
if (argv.includes("--version") || argv.includes("-v")) {
|
|
426
|
+
console.log(readPackageVersion());
|
|
427
|
+
} else {
|
|
428
|
+
const server = buildServer();
|
|
429
|
+
installSignalCleanup(inFlight, { pending: pendingDelegations });
|
|
430
|
+
await server.connect(new StdioServerTransport());
|
|
431
|
+
}
|
|
432
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { makeError } from "./errors.js";
|
|
2
|
+
|
|
3
|
+
export const DEFAULT_HARD_CAP_MS = 6 * 60 * 60 * 1000;
|
|
4
|
+
|
|
5
|
+
export class SessionSupervisor {
|
|
6
|
+
constructor(client, {
|
|
7
|
+
handshakeMs = 60000,
|
|
8
|
+
hardCapMs = DEFAULT_HARD_CAP_MS,
|
|
9
|
+
idleMs = 0,
|
|
10
|
+
} = {}) {
|
|
11
|
+
this.client = client;
|
|
12
|
+
this.handshakeMs = handshakeMs;
|
|
13
|
+
this.hardCapMs = hardCapMs;
|
|
14
|
+
// Mid-turn idle detection is opt-in and off by default. agy emits no ACP frames while a
|
|
15
|
+
// shell command runs, so silence during a prompt turn says nothing about liveness: a
|
|
16
|
+
// running `ping -n 60` produced no frame between its tool_call and the cancel 7s later.
|
|
17
|
+
this.idleMs = idleMs > 0 ? idleMs : 0;
|
|
18
|
+
this.sessionId = null;
|
|
19
|
+
this.lastActivityAt = Date.now();
|
|
20
|
+
this._idleTimer = null;
|
|
21
|
+
this._handshakeTimer = null;
|
|
22
|
+
this._hardCapTimer = null;
|
|
23
|
+
this._armed = false;
|
|
24
|
+
this._settled = false;
|
|
25
|
+
this._promptStarted = false;
|
|
26
|
+
this._guardReject = null;
|
|
27
|
+
this._onActivity = () => {
|
|
28
|
+
this.lastActivityAt = Date.now();
|
|
29
|
+
this._resetIdle();
|
|
30
|
+
};
|
|
31
|
+
this._onExit = (info) => {
|
|
32
|
+
this._trip(
|
|
33
|
+
"agent-exit",
|
|
34
|
+
// Kept whole, for the reason acp-client.js states where it builds the same message.
|
|
35
|
+
`agent exited (code=${info.code}${info.signal ? ", signal=" + info.signal : ""})${info.stderr ? ": " + String(info.stderr) : ""}`
|
|
36
|
+
);
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
setSessionId(sessionId) {
|
|
41
|
+
this.sessionId = sessionId;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
msSinceActivity() {
|
|
45
|
+
return Date.now() - this.lastActivityAt;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
arm() {
|
|
49
|
+
if (this._armed) return;
|
|
50
|
+
this._armed = true;
|
|
51
|
+
this.client.on("activity", this._onActivity);
|
|
52
|
+
this.client.on("exit", this._onExit);
|
|
53
|
+
this._hardCapTimer = setTimeout(() => {
|
|
54
|
+
this._trip("hard-cap", `Session hard-cap exceeded after ${this.hardCapMs}ms`);
|
|
55
|
+
}, this.hardCapMs);
|
|
56
|
+
this._handshakeTimer = setTimeout(() => {
|
|
57
|
+
this._trip("handshake-timeout", `Agent handshake timeout after ${this.handshakeMs}ms (no prompt in flight)`);
|
|
58
|
+
}, this.handshakeMs);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// The handshake is strict request/response, so silence there is real evidence of a
|
|
62
|
+
// wedged agent. Once the prompt is in flight that stops being true, and the deadline
|
|
63
|
+
// must come off.
|
|
64
|
+
promptStarted() {
|
|
65
|
+
if (this._promptStarted) return;
|
|
66
|
+
this._promptStarted = true;
|
|
67
|
+
clearTimeout(this._handshakeTimer);
|
|
68
|
+
this._handshakeTimer = null;
|
|
69
|
+
this._resetIdle();
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
disarm() {
|
|
73
|
+
if (!this._armed) return;
|
|
74
|
+
this._armed = false;
|
|
75
|
+
this.client.off("activity", this._onActivity);
|
|
76
|
+
this.client.off("exit", this._onExit);
|
|
77
|
+
clearTimeout(this._idleTimer);
|
|
78
|
+
clearTimeout(this._handshakeTimer);
|
|
79
|
+
clearTimeout(this._hardCapTimer);
|
|
80
|
+
this._idleTimer = null;
|
|
81
|
+
this._handshakeTimer = null;
|
|
82
|
+
this._hardCapTimer = null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
_resetIdle() {
|
|
86
|
+
clearTimeout(this._idleTimer);
|
|
87
|
+
this._idleTimer = null;
|
|
88
|
+
if (!this.idleMs || !this._promptStarted || !this._armed || this._settled) return;
|
|
89
|
+
this._idleTimer = setTimeout(() => {
|
|
90
|
+
this._trip("idle-timeout", `Session idle timeout after ${this.idleMs}ms`);
|
|
91
|
+
}, this.idleMs);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
abort() {
|
|
95
|
+
this._trip("aborted", "delegation aborted by MCP host");
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
_trip(reason, message) {
|
|
99
|
+
if (this._settled) return;
|
|
100
|
+
this._settled = true;
|
|
101
|
+
this.disarm();
|
|
102
|
+
const err = makeError(reason, message);
|
|
103
|
+
if (reason === "idle-timeout" || reason === "handshake-timeout" || reason === "hard-cap" || reason === "aborted") {
|
|
104
|
+
if (this.sessionId) { try { this.client.cancel(this.sessionId); } catch {} }
|
|
105
|
+
}
|
|
106
|
+
this._guardReject?.(err);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
finish() {
|
|
110
|
+
this.disarm();
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
supervise(work) {
|
|
114
|
+
this.arm();
|
|
115
|
+
const guard = new Promise((_, reject) => { this._guardReject = reject; });
|
|
116
|
+
const run = Promise.resolve().then(work);
|
|
117
|
+
return Promise.race([run, guard]).finally(() => {
|
|
118
|
+
this._guardReject = null;
|
|
119
|
+
if (!this._settled) {
|
|
120
|
+
this._settled = true;
|
|
121
|
+
this.disarm();
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
}
|
package/src/spawn.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import process from "node:process";
|
|
2
|
+
|
|
3
|
+
export function splitArgs(raw) {
|
|
4
|
+
const args = [];
|
|
5
|
+
const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
|
|
6
|
+
for (const m of String(raw || "").matchAll(re)) {
|
|
7
|
+
args.push(m[1] ?? m[2] ?? m[3]);
|
|
8
|
+
}
|
|
9
|
+
return args;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// --dangerously-skip-permissions makes agy approve its own tool calls instead of asking. The
|
|
13
|
+
// request router still approves any session/request_permission that arrives, but agy issue
|
|
14
|
+
// #1658 reports a subagent's command raising none and waiting for an approval that cannot come,
|
|
15
|
+
// which only the flag reaches. With the flag, a probe turn raised no permission request at all.
|
|
16
|
+
export const DEFAULT_AGENT_ARGS = Object.freeze(["acp", "--dangerously-skip-permissions"]);
|
|
17
|
+
|
|
18
|
+
// shell:true on win32 is what lets a .cmd/.ps1 launcher resolve at all, and it means the
|
|
19
|
+
// command and args are parsed by cmd.exe. Safe only because both come from the environment,
|
|
20
|
+
// which is already as trusted as this process: anything that can set them can run code here
|
|
21
|
+
// anyway. Routing host- or caller-supplied values into either variable would turn this into a
|
|
22
|
+
// command-injection path, so don't.
|
|
23
|
+
export function resolveAcpSpawn() {
|
|
24
|
+
const command = process.env.ACP_AGENT_COMMAND || "agy";
|
|
25
|
+
const args = process.env.ACP_AGENT_ARGS
|
|
26
|
+
? splitArgs(process.env.ACP_AGENT_ARGS)
|
|
27
|
+
: [...DEFAULT_AGENT_ARGS];
|
|
28
|
+
return { command, args, options: { shell: process.platform === "win32" } };
|
|
29
|
+
}
|