agy-delegate-mcp 1.3.0 → 1.5.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 CHANGED
@@ -6,6 +6,52 @@ All notable changes to this project are documented here. The format follows
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [1.5.0] - 2026-11-22
10
+
11
+ ### Changed
12
+
13
+ - A resume that leaves out `model` or `effort` uses what this server last set on that session; agy
14
+ reopens a resumed session at its defaults.
15
+ - `cancel` and `steer` reject a blank `sessionId`. `resumeSessionId` is trimmed, and a blank one
16
+ means no resume.
17
+
18
+ ### Fixed
19
+
20
+ - A cancel during session setup sends no prompt and returns `stopReason: "cancelled"` at once, even
21
+ if a config call hangs or fails. The prompt still ran in full.
22
+ - `steer` reports `not-running` once the turn has ended, been cancelled or lost its agent; it said
23
+ `not-ready`. A steer agy accepted that then fails fails the delegation, and a steer queued behind a
24
+ failed one supplies the result.
25
+ - `cancel` after the turn ended reports `not-running` and leaves the result alone; `force` cuts
26
+ agy's close short as each turn settles.
27
+ - A host abort during agy's close, or during `doctor`'s probe, handshake or close, ends it at once.
28
+ Shutdown stops `doctor`'s agent.
29
+ - The background wait runs only after `end_turn`, on one clock per delegation. A refusal or output
30
+ cap that leaves a command open names the command, not a question.
31
+ - `usage` keeps a cached or thought count one reply left out. `context` ignores other sessions'
32
+ frames, and frames sent while attachments are read stay out of the result.
33
+ - A delegation returns only once agy's descendants are killed. An exit the bridge does not see is
34
+ retried and reported in `protocolWarnings`.
35
+ - No DEP0190 warning under Node 24 on Windows.
36
+ - On Linux and macOS, SIGHUP stops the agents, and only a second signal cuts shutdown short, killing
37
+ their process groups first.
38
+
39
+ ## [1.4.0] - 2026-11-22
40
+
41
+ ### Added
42
+
43
+ - **`steer`** tool: sends a new instruction into a running delegation; the pending `delegate` call
44
+ returns the redirected turn. Needs a host that can call a tool while `delegate` runs.
45
+ - `usage` (the turn's token counts) and `context` (`{used, size}` of the context window) in the
46
+ result.
47
+
48
+ ### Changed
49
+
50
+ - A delegation returns once agy has exited. agy first gets up to 2 s to close its session and exit
51
+ by itself (about 0.4 s in practice), so its conversation database closes cleanly and the
52
+ workspace is free when the result arrives. A stall, abort, agent exit, `force` cancel or shutdown
53
+ still kills it at once.
54
+
9
55
  ## [1.3.0] - 2026-11-22
10
56
 
11
57
  ### Added
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agy-delegate-mcp",
3
- "version": "1.3.0",
3
+ "version": "1.5.0",
4
4
  "mcpName": "io.github.andreilungeanu/agy-delegate-mcp",
5
5
  "type": "module",
6
6
  "description": "Delegate multi-file coding work from Claude Code, Codex, Copilot, or any MCP client to Google's Antigravity CLI (agy) — structured results, plan mode, and changed files.",
package/src/acp-client.js CHANGED
@@ -1,44 +1,52 @@
1
+ import process from "node:process";
1
2
  import { spawn } from "node:child_process";
2
3
  import { EventEmitter } from "node:events";
3
4
  import { StringDecoder } from "node:string_decoder";
4
5
  import { JsonRpcPeer } from "./jsonrpc.js";
5
6
  import { createRequestRouter } from "./request-router.js";
6
- import { commandExists, resolveAcpSpawn } from "./spawn.js";
7
+ import { commandExists, resolveAcpSpawn, spawnCommandLine } from "./spawn.js";
7
8
  import { DETACHED, isChildAlive, treeKill } from "./proc.js";
8
9
  import { VERSION } from "./version.js";
9
10
  import { makeError } from "./errors.js";
10
11
 
11
12
  const STDERR_CAP = 64 * 1024;
12
- // How long stop() waits for the child to actually exit after the kill is dispatched. SIGKILL and
13
- // taskkill /F land in milliseconds, so this only ever elapses when the kill did not work.
13
+ // How long stop() waits for the exit after the kill; it elapses only when the kill failed.
14
14
  const STOP_EXIT_TIMEOUT_MS = 2000;
15
+ // How long a graceful stop gives agy to exit by itself before the kill. agy took 200–400 ms.
16
+ export const GRACEFUL_STOP_MS = 2000;
17
+
18
+ // Settlement order of prompt replies: a refused steer settles before the turn it targets, one agy
19
+ // took over settles after it. Attached at request time, so it records when the reply came.
20
+ let settleSeq = 0;
21
+ /** @returns {Promise<{ ok: true, value: any, seq: number } | { ok: false, error: any, seq: number }>} */
22
+ export function stampSettlement(promise) {
23
+ return promise.then((value) => ({ ok: true, value, seq: ++settleSeq }), (error) => ({ ok: false, error, seq: ++settleSeq }));
24
+ }
15
25
 
16
26
  export class AcpClient extends EventEmitter {
17
- /**
18
- * @param {{
19
- * spawnSpec?: { command: string, args: string[], options?: object },
20
- * }} [opts]
21
- */
22
27
  /** @param {{ spawnSpec?: any, cwd?: string }} [opts] */
23
28
  constructor({ spawnSpec, cwd } = {}) {
24
29
  super();
25
30
  this.spawnSpec = spawnSpec || resolveAcpSpawn();
26
- // agy treats its process directory as part of the workspace, not only the session's cwd:
27
- // started from the MCP server's directory it listed that directory and ran git status and
28
- // git diff there (measured, agy 1.5.14). Started in the workspace, there is nothing else to see.
31
+ // agy treats its process directory as part of the workspace: started elsewhere, it ran git
32
+ // status there (measured, agy 1.5.14).
29
33
  this.cwd = cwd;
30
34
  this._stderrChunks = [];
31
35
  this._stderrLength = 0;
32
36
  /** @type {Promise<boolean> | null} */
33
37
  this._stopping = null;
38
+ // Sessions opened on this process, which a graceful stop closes.
39
+ /** @type {Set<string>} */
40
+ this._sessions = new Set();
41
+ // setup until the prompt is on the wire, open while the turn runs, then closed for good.
42
+ /** @type {"setup" | "open" | "closed"} */
43
+ this._steerWindow = "setup";
44
+ /** @type {Promise<any>[]} */
45
+ this._steers = [];
34
46
  }
35
47
 
36
- // stderr is captured but does not count as activity: the supervisor measures ACP frames, and
37
- // an agent writing diagnostics is not the same fact as a turn making progress.
38
- // The tail of stderr, which is what an exit error quotes. Kept as chunks and joined on read:
39
- // rebuilding a 64KB string per chunk was the whole cost of a noisy agent. A StringDecoder
40
- // holds partial UTF-8 across chunk boundaries, so a multi-byte character split by the pipe
41
- // does not land in the error message as a replacement char.
48
+ // The stderr tail an exit error quotes; not counted as activity. Kept as chunks and joined on
49
+ // read, which is cheap for a noisy agent; the StringDecoder keeps split UTF-8 characters whole.
42
50
  get stderrBuffer() {
43
51
  const joined = this._stderrChunks.join("");
44
52
  return joined.length > STDERR_CAP ? joined.slice(-STDERR_CAP) : joined;
@@ -53,20 +61,18 @@ export class AcpClient extends EventEmitter {
53
61
  this._stderrLength = 0;
54
62
  const stderrDecoder = new StringDecoder("utf8");
55
63
  this._exitEmitted = false;
56
- this.child = spawn(command, args, { ...options, ...(this.cwd ? { cwd: this.cwd } : {}), detached: DETACHED, stdio: ["pipe", "pipe", "pipe"] });
64
+ const [file, argv] = spawnCommandLine(command, args, options);
65
+ this.child = spawn(file, argv, { ...options, ...(this.cwd ? { cwd: this.cwd } : {}), detached: DETACHED, stdio: ["pipe", "pipe", "pipe"] });
57
66
  this.child.stderr.on("data", (chunk) => {
58
67
  const text = stderrDecoder.write(chunk);
59
68
  if (text) {
60
69
  this._stderrChunks.push(text);
61
70
  this._stderrLength += text.length;
62
- // Drop whole chunks from the front only once well past the cap, so the common case
63
- // costs one push. The joined tail is trimmed exactly on read.
71
+ // Whole chunks are dropped once past the cap; the tail is trimmed exactly on read.
64
72
  while (this._stderrChunks.length > 1 && this._stderrLength - this._stderrChunks[0].length >= STDERR_CAP) {
65
73
  this._stderrLength -= this._stderrChunks.shift().length;
66
74
  }
67
- // Whole-chunk drops leave a remainder when one pipe read is itself larger than the cap
68
- // (observed on GitHub Windows runners). Slice that first chunk so retained memory cannot
69
- // grow with the flood; the public tail is still exactly one cap on read.
75
+ // A single read larger than the cap (seen on GitHub Windows runners) is sliced.
70
76
  const overflow = this._stderrLength - STDERR_CAP;
71
77
  if (overflow > 0) {
72
78
  this._stderrChunks[0] = this._stderrChunks[0].slice(overflow);
@@ -75,20 +81,18 @@ export class AcpClient extends EventEmitter {
75
81
  }
76
82
  });
77
83
  this.child.stderr.on("error", () => {});
78
- // A supervisor trip writes session/cancel, which can land after the agent is already gone.
79
- // Without a handler that surfaces as an unhandled 'error' event on some platforms, taking
80
- // the whole MCP server down with it. stdout needs the same guard; readline adds none.
84
+ // A write after the agent is gone raises 'error'; unhandled, it takes down the server.
81
85
  this.child.stdin.on("error", () => {});
82
86
  this.child.stdout.on("error", () => {});
83
87
  const emitExit = (code, signal) => {
84
88
  if (this._exitEmitted) return;
85
89
  this._exitEmitted = true;
90
+ // A steer to an exited agent has nowhere to go.
91
+ this._steerWindow = "closed";
86
92
  const stderr = this.stderrBuffer;
87
93
  const err = makeError(
88
94
  "agent-exit",
89
- // stderr kept whole. This is the one string that says why the agent died — the model
90
- // that was rejected, the quota that ran out, the login that expired — and the part that
91
- // names it can sit anywhere in it. The 64KB ring buffer above is the bound.
95
+ // All of the (capped) stderr: the reason the agent died can sit anywhere in it.
92
96
  `agent exited (code=${code}${signal ? ", signal=" + signal : ""})${stderr ? ": " + String(stderr) : ""}`
93
97
  );
94
98
  // exit + rejectAllPending both settle the same Promise.race; second rejection is intentional.
@@ -102,8 +106,7 @@ export class AcpClient extends EventEmitter {
102
106
  onNotification: (method, params) => {
103
107
  if (method === "session/update") this.emit("update", params);
104
108
  },
105
- // The router is async and its result discarded, so a throw from its own catch would reject
106
- // unobserved and exit the process. Promise.resolve covers a sync router in tests.
109
+ // Caught: an unobserved rejection would exit the process. Promise.resolve covers a sync router.
107
110
  onRequest: (id, method, params) => {
108
111
  if (this.router) Promise.resolve(this.router(id, method, params)).catch(() => {});
109
112
  },
@@ -115,8 +118,6 @@ export class AcpClient extends EventEmitter {
115
118
  });
116
119
  return /** @type {Promise<void>} */ (new Promise((resolve, reject) => {
117
120
  this.child.once("error", (e) => {
118
- // Tagged like every other failure class so the caller gets
119
- // "delegate failed [spawn-failed]: ..." instead of the one untagged prose error.
120
121
  const err = makeError("spawn-failed", `Failed to spawn agent (${command}): ${e.message}. Install the Antigravity CLI (agy) and sign in by running agy once.`);
121
122
  reject(err);
122
123
  });
@@ -124,8 +125,7 @@ export class AcpClient extends EventEmitter {
124
125
  }));
125
126
  }
126
127
 
127
- // Stashed so the unknown-model pre-flight and doctor --deep can read the agent's real
128
- // capability and model lists without paying for a second handshake.
128
+ // Kept for the model check and doctor, without a second handshake.
129
129
  async initialize() {
130
130
  const res = await this.peer.request("initialize", { protocolVersion: 1, clientInfo: { name: "agy-delegate-mcp", version: VERSION }, clientCapabilities: {} });
131
131
  this.protocolVersion = res?.protocolVersion;
@@ -140,27 +140,81 @@ export class AcpClient extends EventEmitter {
140
140
  this.sessionMeta = res?._meta;
141
141
  return res;
142
142
  }
143
- async newSession(cwd) { return this._captureSession(await this.peer.request("session/new", { cwd, mcpServers: [] })); }
143
+ // appendSystemPrompt goes in _meta.antigravity.systemPrompt.append. agy stores it with the session
144
+ // and ignores a _meta sent on resume (measured, agy 1.5.14).
145
+ /** @param {string} cwd @param {{ appendSystemPrompt?: string }} [opts] */
146
+ async newSession(cwd, { appendSystemPrompt } = {}) {
147
+ const params = { cwd, mcpServers: [] };
148
+ if (appendSystemPrompt) params._meta = { antigravity: { systemPrompt: { append: appendSystemPrompt } } };
149
+ const res = this._captureSession(await this.peer.request("session/new", params));
150
+ if (typeof res?.sessionId === "string") this._sessions.add(res.sessionId);
151
+ return res;
152
+ }
144
153
  // resume reopens a session without replaying it. Unlike session/load, which agy answers with a
145
154
  // fresh session for an id it has never seen, resume rejects an unknown id.
146
- async resumeSession(sessionId, cwd) { return this._captureSession(await this.peer.request("session/resume", { sessionId, cwd, mcpServers: [] })); }
155
+ async resumeSession(sessionId, cwd) {
156
+ const res = this._captureSession(await this.peer.request("session/resume", { sessionId, cwd, mcpServers: [] }));
157
+ this._sessions.add(sessionId);
158
+ return res;
159
+ }
147
160
  // agy returns every session the account has, ignoring cwd, in one page.
148
161
  listSessions(params = {}) { return this.peer.request("session/list", params); }
149
162
  setModel(sessionId, modelId) { return this.peer.request("session/set_model", { sessionId, modelId }); }
150
163
  setConfigOption(sessionId, configId, value) { return this.peer.request("session/set_config_option", { sessionId, configId, value: String(value) }); } // configId, not optionId; ACP wants a string value
151
164
  setMode(sessionId, modeId) { return this.peer.request("session/set_mode", { sessionId, modeId }); }
152
165
  prompt(sessionId, blocks) { return this.peer.request("session/prompt", { sessionId, prompt: blocks }); }
153
- // Recorded so a delegation waiting on a backgrounded command can stop waiting: after a cancel
154
- // agy closes the call without the usage_update that ends a continuation.
155
- cancel(sessionId) { this.cancelRequested = true; this.peer.notify("session/cancel", { sessionId }); return Promise.resolve(); }
166
+ // agy takes a session/prompt sent mid-turn as a redirect: the prompt in flight settles at once
167
+ // with end_turn, the new one when the redirected turn ends (measured, agy 1.5.14). The window is
168
+ // open only while the delegation's prompt runs, and a cancel or exit closes it for good. prefix
169
+ // goes ahead of each steer, as ask mode's instruction goes ahead of the spec.
170
+ acceptSteers(on, prefix) {
171
+ if (!on) { this._steerWindow = "closed"; return; }
172
+ if (this._steerWindow === "setup" && !this.cancelRequested && !this._exitEmitted) {
173
+ this._steerWindow = "open";
174
+ this._steerPrefix = prefix;
175
+ }
176
+ }
177
+ /** @returns {"steered" | "not-ready" | "not-running"} */
178
+ steer(sessionId, text) {
179
+ if (this._steerWindow === "setup") return "not-ready";
180
+ if (this._steerWindow !== "open" || !this.peer) return "not-running";
181
+ const body = this._steerPrefix ? `${this._steerPrefix}\n\n${text}` : text;
182
+ // Stamped, so it never rejects unobserved.
183
+ this._steers.push(stampSettlement(this.peer.request("session/prompt", { sessionId, prompt: [{ type: "text", text: body }] })));
184
+ return "steered";
185
+ }
186
+ hasSteer() { return this._steers.length > 0; }
187
+ takeSteer() { return this._steers.shift(); }
188
+ // Read by the background wait, which a cancelled turn's usage_update would not end, and closes
189
+ // the steer window: a later steer would restart the cancelled turn. delegate listens for the
190
+ // event to end its setup when no prompt has gone out.
191
+ cancel(sessionId) {
192
+ this.cancelRequested = true;
193
+ this._steerWindow = "closed";
194
+ this.peer.notify("session/cancel", { sessionId });
195
+ this.emit("cancel");
196
+ return Promise.resolve();
197
+ }
198
+
199
+ // Last resort for a process about to exit: SIGKILL to the group and the agent, no ps walk. POSIX
200
+ // only; on win32 the kill is taskkill, which stop() runs.
201
+ killNow() {
202
+ const pid = this.child?.pid;
203
+ if (!pid || process.platform === "win32") return;
204
+ try { process.kill(-pid, "SIGKILL"); } catch {}
205
+ if (isChildAlive(this.child)) { try { process.kill(pid, "SIGKILL"); } catch {} }
206
+ }
156
207
 
157
208
  getTranscript(n) { return this.peer ? this.peer.formatLog(n) : ""; }
158
209
 
159
- // Idempotent while teardown is in flight and after a confirmed exit. A missed exit is not
160
- // memoized — force retries with a new treeKill. A confirmed exit stays so later callers join.
161
- stop({ timeoutMs = STOP_EXIT_TIMEOUT_MS } = {}) {
210
+ // Memoized while in flight and after a confirmed exit; a missed exit is not, so a retry kills
211
+ // again. graceMs > 0 first closes the sessions and stdin and waits that long: agy then exits 0 in
212
+ // 200–400 ms with its database closed, where a kill leaves -shm and -wal files (measured, agy
213
+ // 1.5.14). The tree kill follows either way. A force stop ends a grace in progress.
214
+ stop({ timeoutMs = STOP_EXIT_TIMEOUT_MS, graceMs = 0 } = {}) {
215
+ if (this._stopping && graceMs <= 0) this._endGrace?.();
162
216
  if (!this._stopping) {
163
- this._stopping = this._teardown(timeoutMs).then((observed) => {
217
+ this._stopping = this._teardown(timeoutMs, graceMs).then((observed) => {
164
218
  if (!observed) this._stopping = null;
165
219
  return observed;
166
220
  }, (err) => {
@@ -171,32 +225,56 @@ export class AcpClient extends EventEmitter {
171
225
  return this._stopping;
172
226
  }
173
227
 
174
- async _teardown(timeoutMs) {
228
+ // session/close stops background commands and subagents a cancel leaves running (agy 1.5.10
229
+ // changelog); stdin EOF then ends agy. Bounded by graceMs.
230
+ async _closeGracefully(child, graceMs) {
231
+ /** @type {NodeJS.Timeout | undefined} */
232
+ let timer;
233
+ const deadline = new Promise((resolve) => {
234
+ timer = setTimeout(resolve, graceMs);
235
+ /** @type {(() => void) | null} */
236
+ this._endGrace = () => resolve(undefined);
237
+ });
238
+ const exited = new Promise((resolve) => child.once("exit", resolve));
239
+ try {
240
+ if (this.agentCapabilities?.sessionCapabilities?.close && this.peer) {
241
+ const closes = [...this._sessions].map((sessionId) => this.peer.request("session/close", { sessionId }).catch(() => {}));
242
+ await Promise.race([Promise.all(closes), deadline, exited]);
243
+ }
244
+ try { child.stdin.end(); } catch {}
245
+ await Promise.race([deadline, exited]);
246
+ } finally {
247
+ clearTimeout(timer);
248
+ this._endGrace = null;
249
+ }
250
+ }
251
+
252
+ async _teardown(timeoutMs, graceMs = 0) {
175
253
  const child = this.child;
176
254
  if (!child?.pid) {
177
255
  try { this.peer?.close(); } catch {}
178
256
  return true;
179
257
  }
258
+ if (graceMs > 0 && isChildAlive(child)) await this._closeGracefully(child, graceMs);
180
259
  const alive = isChildAlive(child);
181
- // Subscribed before the kill is dispatched. A child that dies immediately would otherwise
182
- // exit in the gap and leave this waiting on an event that has already fired.
260
+ // Subscribed before the kill, so an immediate exit is not missed.
183
261
  const exited = alive
184
262
  ? /** @type {Promise<boolean>} */ (new Promise((resolve) => child.once("exit", () => resolve(true))))
185
263
  : Promise.resolve(true);
186
- // Runs for an exited child too: the agent can be gone while the commands it spawned are still
187
- // running, and on POSIX they stay in its process group, which is the only handle left on them.
188
- treeKill(child.pid, { childAlive: alive }).catch(() => {});
264
+ // Also for an exited child: on POSIX its commands can outlive it in its process group.
265
+ const killed = treeKill(child.pid, { childAlive: alive }).catch(() => {});
189
266
  /** @type {NodeJS.Timeout | undefined} */
190
267
  let timer;
191
268
  const bounded = /** @type {Promise<boolean>} */ (new Promise((resolve) => {
192
269
  timer = setTimeout(() => resolve(false), timeoutMs);
193
270
  }));
194
271
  const observed = await Promise.race([exited, bounded]);
272
+ // The tree kill too, on the same deadline: on POSIX it walks the tree with ps first, and an agent
273
+ // exiting meanwhile would resolve stop() before its commands were killed.
274
+ await Promise.race([killed, bounded]);
195
275
  clearTimeout(timer);
196
- // The exit handler rejects in-flight RPCs with stderr. Doing that here on a confirmed
197
- // exit would race it and the first settlement would drop the forensics. A stop that
198
- // did not see the child die never gets that handler, so settle those RPCs only when
199
- // the process is still alive and emitExit has not run.
276
+ // On an exit, emitExit rejects pending RPCs with stderr; rejecting here first would lose it.
277
+ // Only an unobserved exit settles them here.
200
278
  if (!observed && !this._exitEmitted && isChildAlive(child)) {
201
279
  try {
202
280
  this.peer?.rejectAllPending(makeError("agent-exit", "agent process did not exit after stop"));
@@ -1,12 +1,10 @@
1
1
  import path from "node:path";
2
2
 
3
- // Attribution rule: a path is agent-reported only via a native ACP diff event.
4
- // Never add paths from git, the final message, or shell output — the orchestrator
5
- // owns workspace diff review.
3
+ // A path is agent-reported only via an ACP diff event, never from git, the message or shell output:
4
+ // the orchestrator owns diff review.
6
5
 
7
- // agy reports a finished edit's diff path as /C:/Users/… on Windows (leading slash, forward
8
- // slashes) while the same call's args carry C:\Users\…. The slash before the drive letter makes
9
- // path.resolve read it as rooted on the current drive, so it is stripped before resolving.
6
+ // agy writes diff paths as /C:/Users/… on Windows; path.resolve would read the leading slash as
7
+ // the current drive's root, so it is stripped.
10
8
  export function fromAgentPath(p) {
11
9
  return /^\/[A-Za-z]:[\\/]/.test(p) ? p.slice(1) : p;
12
10
  }