agy-delegate-mcp 1.4.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,36 @@ 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
+
9
39
  ## [1.4.0] - 2026-11-22
10
40
 
11
41
  ### Added
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agy-delegate-mcp",
3
- "version": "1.4.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,33 +1,35 @@
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
15
  // How long a graceful stop gives agy to exit by itself before the kill. agy took 200–400 ms.
16
16
  export const GRACEFUL_STOP_MS = 2000;
17
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
+ }
25
+
18
26
  export class AcpClient extends EventEmitter {
19
- /**
20
- * @param {{
21
- * spawnSpec?: { command: string, args: string[], options?: object },
22
- * }} [opts]
23
- */
24
27
  /** @param {{ spawnSpec?: any, cwd?: string }} [opts] */
25
28
  constructor({ spawnSpec, cwd } = {}) {
26
29
  super();
27
30
  this.spawnSpec = spawnSpec || resolveAcpSpawn();
28
- // agy treats its process directory as part of the workspace, not only the session's cwd:
29
- // started from the MCP server's directory it listed that directory and ran git status and
30
- // 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).
31
33
  this.cwd = cwd;
32
34
  this._stderrChunks = [];
33
35
  this._stderrLength = 0;
@@ -36,17 +38,15 @@ export class AcpClient extends EventEmitter {
36
38
  // Sessions opened on this process, which a graceful stop closes.
37
39
  /** @type {Set<string>} */
38
40
  this._sessions = new Set();
39
- this._steerable = false;
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";
40
44
  /** @type {Promise<any>[]} */
41
45
  this._steers = [];
42
46
  }
43
47
 
44
- // stderr is captured but does not count as activity: the supervisor measures ACP frames, and
45
- // an agent writing diagnostics is not the same fact as a turn making progress.
46
- // The tail of stderr, which is what an exit error quotes. Kept as chunks and joined on read:
47
- // rebuilding a 64KB string per chunk was the whole cost of a noisy agent. A StringDecoder
48
- // holds partial UTF-8 across chunk boundaries, so a multi-byte character split by the pipe
49
- // 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.
50
50
  get stderrBuffer() {
51
51
  const joined = this._stderrChunks.join("");
52
52
  return joined.length > STDERR_CAP ? joined.slice(-STDERR_CAP) : joined;
@@ -61,20 +61,18 @@ export class AcpClient extends EventEmitter {
61
61
  this._stderrLength = 0;
62
62
  const stderrDecoder = new StringDecoder("utf8");
63
63
  this._exitEmitted = false;
64
- 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"] });
65
66
  this.child.stderr.on("data", (chunk) => {
66
67
  const text = stderrDecoder.write(chunk);
67
68
  if (text) {
68
69
  this._stderrChunks.push(text);
69
70
  this._stderrLength += text.length;
70
- // Drop whole chunks from the front only once well past the cap, so the common case
71
- // 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.
72
72
  while (this._stderrChunks.length > 1 && this._stderrLength - this._stderrChunks[0].length >= STDERR_CAP) {
73
73
  this._stderrLength -= this._stderrChunks.shift().length;
74
74
  }
75
- // Whole-chunk drops leave a remainder when one pipe read is itself larger than the cap
76
- // (observed on GitHub Windows runners). Slice that first chunk so retained memory cannot
77
- // 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.
78
76
  const overflow = this._stderrLength - STDERR_CAP;
79
77
  if (overflow > 0) {
80
78
  this._stderrChunks[0] = this._stderrChunks[0].slice(overflow);
@@ -83,22 +81,18 @@ export class AcpClient extends EventEmitter {
83
81
  }
84
82
  });
85
83
  this.child.stderr.on("error", () => {});
86
- // A supervisor trip writes session/cancel, which can land after the agent is already gone.
87
- // Without a handler that surfaces as an unhandled 'error' event on some platforms, taking
88
- // 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.
89
85
  this.child.stdin.on("error", () => {});
90
86
  this.child.stdout.on("error", () => {});
91
87
  const emitExit = (code, signal) => {
92
88
  if (this._exitEmitted) return;
93
89
  this._exitEmitted = true;
94
90
  // A steer to an exited agent has nowhere to go.
95
- this._steerable = false;
91
+ this._steerWindow = "closed";
96
92
  const stderr = this.stderrBuffer;
97
93
  const err = makeError(
98
94
  "agent-exit",
99
- // stderr kept whole. This is the one string that says why the agent died — the model
100
- // that was rejected, the quota that ran out, the login that expired — and the part that
101
- // 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.
102
96
  `agent exited (code=${code}${signal ? ", signal=" + signal : ""})${stderr ? ": " + String(stderr) : ""}`
103
97
  );
104
98
  // exit + rejectAllPending both settle the same Promise.race; second rejection is intentional.
@@ -112,8 +106,7 @@ export class AcpClient extends EventEmitter {
112
106
  onNotification: (method, params) => {
113
107
  if (method === "session/update") this.emit("update", params);
114
108
  },
115
- // The router is async and its result discarded, so a throw from its own catch would reject
116
- // 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.
117
110
  onRequest: (id, method, params) => {
118
111
  if (this.router) Promise.resolve(this.router(id, method, params)).catch(() => {});
119
112
  },
@@ -125,8 +118,6 @@ export class AcpClient extends EventEmitter {
125
118
  });
126
119
  return /** @type {Promise<void>} */ (new Promise((resolve, reject) => {
127
120
  this.child.once("error", (e) => {
128
- // Tagged like every other failure class so the caller gets
129
- // "delegate failed [spawn-failed]: ..." instead of the one untagged prose error.
130
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.`);
131
122
  reject(err);
132
123
  });
@@ -134,8 +125,7 @@ export class AcpClient extends EventEmitter {
134
125
  }));
135
126
  }
136
127
 
137
- // Stashed so the unknown-model pre-flight and doctor --deep can read the agent's real
138
- // capability and model lists without paying for a second handshake.
128
+ // Kept for the model check and doctor, without a second handshake.
139
129
  async initialize() {
140
130
  const res = await this.peer.request("initialize", { protocolVersion: 1, clientInfo: { name: "agy-delegate-mcp", version: VERSION }, clientCapabilities: {} });
141
131
  this.protocolVersion = res?.protocolVersion;
@@ -150,9 +140,8 @@ export class AcpClient extends EventEmitter {
150
140
  this.sessionMeta = res?._meta;
151
141
  return res;
152
142
  }
153
- // appendSystemPrompt goes in _meta.antigravity.systemPrompt.append, which agy advertises at
154
- // initialize. agy stores it with the session: it holds across session/resume in a new process,
155
- // and a _meta sent on resume is ignored (measured, agy 1.5.14).
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).
156
145
  /** @param {string} cwd @param {{ appendSystemPrompt?: string }} [opts] */
157
146
  async newSession(cwd, { appendSystemPrompt } = {}) {
158
147
  const params = { cwd, mcpServers: [] };
@@ -174,37 +163,54 @@ export class AcpClient extends EventEmitter {
174
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
175
164
  setMode(sessionId, modeId) { return this.peer.request("session/set_mode", { sessionId, modeId }); }
176
165
  prompt(sessionId, blocks) { return this.peer.request("session/prompt", { sessionId, prompt: blocks }); }
177
- // agy takes a session/prompt sent while a turn runs as a redirect of that turn: the prompt in
178
- // flight settles at once with end_turn, and the new one settles when the redirected turn ends
179
- // (measured, agy 1.5.14). The delegation opens this window only while its prompt runs, so a
180
- // steer can neither precede the task nor land after the delegation has read its result.
181
- // prefix goes ahead of every steer's text, as ask mode's instruction goes ahead of the spec.
182
- acceptSteers(on, prefix) { this._steerable = on; this._steerPrefix = prefix; }
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"} */
183
178
  steer(sessionId, text) {
184
- if (!this._steerable || !this.peer) return false;
179
+ if (this._steerWindow === "setup") return "not-ready";
180
+ if (this._steerWindow !== "open" || !this.peer) return "not-running";
185
181
  const body = this._steerPrefix ? `${this._steerPrefix}\n\n${text}` : text;
186
- const reply = this.peer.request("session/prompt", { sessionId, prompt: [{ type: "text", text: body }] });
187
- // The delegation awaits it; this keeps a rejection it never reaches from going unhandled.
188
- reply.catch(() => {});
189
- this._steers.push(reply);
190
- return true;
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";
191
185
  }
192
186
  hasSteer() { return this._steers.length > 0; }
193
187
  takeSteer() { return this._steers.shift(); }
194
- // Recorded so a delegation waiting on a backgrounded command can stop waiting: after a cancel
195
- // agy closes the call without the usage_update that ends a continuation.
196
- // A cancel also closes the steer window: a steer accepted after it restarted the cancelled turn.
197
- cancel(sessionId) { this.cancelRequested = true; this._steerable = false; this.peer.notify("session/cancel", { sessionId }); return Promise.resolve(); }
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
+ }
198
207
 
199
208
  getTranscript(n) { return this.peer ? this.peer.formatLog(n) : ""; }
200
209
 
201
- // Idempotent while teardown is in flight and after a confirmed exit. A missed exit is not
202
- // memoized — force retries with a new treeKill. A confirmed exit stays so later callers join.
203
- // graceMs > 0 first closes agy's sessions and its stdin and gives it that long to exit by
204
- // itself; the tree kill follows either way. agy exits 0 in 200–400 ms that way and closes its
205
- // conversation database, where a kill leaves its -shm and -wal files (measured, agy 1.5.14).
206
- // A force stop (graceMs 0) that finds a graceful one in progress ends its grace now rather than
207
- // waiting it out: force cancel and shutdown mean "kill".
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.
208
214
  stop({ timeoutMs = STOP_EXIT_TIMEOUT_MS, graceMs = 0 } = {}) {
209
215
  if (this._stopping && graceMs <= 0) this._endGrace?.();
210
216
  if (!this._stopping) {
@@ -219,8 +225,8 @@ export class AcpClient extends EventEmitter {
219
225
  return this._stopping;
220
226
  }
221
227
 
222
- // session/close stops the session's background commands and subagents, which a cancel leaves
223
- // running (agy 1.5.10 changelog); closing stdin then ends agy. Bounded as a whole by graceMs.
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.
224
230
  async _closeGracefully(child, graceMs) {
225
231
  /** @type {NodeJS.Timeout | undefined} */
226
232
  let timer;
@@ -251,25 +257,24 @@ export class AcpClient extends EventEmitter {
251
257
  }
252
258
  if (graceMs > 0 && isChildAlive(child)) await this._closeGracefully(child, graceMs);
253
259
  const alive = isChildAlive(child);
254
- // Subscribed before the kill is dispatched. A child that dies immediately would otherwise
255
- // 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.
256
261
  const exited = alive
257
262
  ? /** @type {Promise<boolean>} */ (new Promise((resolve) => child.once("exit", () => resolve(true))))
258
263
  : Promise.resolve(true);
259
- // Runs for an exited child too: the agent can be gone while the commands it spawned are still
260
- // running, and on POSIX they stay in its process group, which is the only handle left on them.
261
- 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(() => {});
262
266
  /** @type {NodeJS.Timeout | undefined} */
263
267
  let timer;
264
268
  const bounded = /** @type {Promise<boolean>} */ (new Promise((resolve) => {
265
269
  timer = setTimeout(() => resolve(false), timeoutMs);
266
270
  }));
267
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]);
268
275
  clearTimeout(timer);
269
- // The exit handler rejects in-flight RPCs with stderr. Doing that here on a confirmed
270
- // exit would race it and the first settlement would drop the forensics. A stop that
271
- // did not see the child die never gets that handler, so settle those RPCs only when
272
- // 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.
273
278
  if (!observed && !this._exitEmitted && isChildAlive(child)) {
274
279
  try {
275
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
  }