agy-delegate-mcp 1.4.0 → 1.6.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/src/doctor.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import process from "node:process";
2
2
  import { spawn } from "node:child_process";
3
+ import { existsSync } from "node:fs";
3
4
  import { AcpClient, GRACEFUL_STOP_MS } from "./acp-client.js";
4
- import { commandExists, resolveAcpSpawn } from "./spawn.js";
5
+ import { commandExists, resolveAcpSpawn, spawnArgv, spawnCommandLine } from "./spawn.js";
5
6
  import { DETACHED, treeKill } from "./proc.js";
6
7
  import { readPackageVersion } from "./version.js";
7
8
  import { allowedValues, describeOptions } from "./model-options.js";
@@ -9,6 +10,7 @@ import { allowedValues, describeOptions } from "./model-options.js";
9
10
  const HANDSHAKE_TIMEOUT_MS = 15_000;
10
11
  const VERSION_PROBE_TIMEOUT_MS = 10_000;
11
12
  const PROBE_STDOUT_CAP = 64 * 1024;
13
+ const PROBE_KILL_WAIT_MS = 2000;
12
14
  const DEFAULT_LOG_SIZE = "2000";
13
15
 
14
16
  function formatArg(value) {
@@ -31,40 +33,47 @@ function envReport(name, fallback = null) {
31
33
  return process.env[name] !== undefined ? process.env[name] : fallback;
32
34
  }
33
35
 
34
- // Time-boxed because a launcher that accepts --version and then never answers would hang doctor
35
- // forever — and doctor is what you run when delegation is already broken, so a wedged agent is
36
- // exactly the case it must survive. Same guard the deep handshake has.
37
- export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_MS) {
36
+ // Time-boxed: doctor runs when delegation is already broken, so it must survive a wedged launcher.
37
+ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_MS, signal) {
38
38
  const { command, options } = spawnSpec;
39
39
  const launcher = String(command || "").replace(/^["']|["']$/g, "");
40
40
  const isJsScript = isJsLauncher(launcher);
41
41
  const execCommand = isJsScript ? process.execPath : command;
42
42
  const execArgs = isJsScript ? [launcher, "--version"] : ["--version"];
43
- // Through a shell, a missing launcher still spawns (the shell does) and would read as found.
44
- if (options?.shell && !isJsScript && !commandExists(launcher)) return Promise.resolve({ found: false, version: null });
43
+ // Found before the spawn: through cmd.exe a missing launcher still spawns and would read as found.
44
+ const launch = spawnArgv(execCommand, execArgs, options);
45
+ if (!launch) return Promise.resolve({ found: false, version: null });
46
+ const aborted = { version: null, error: "version probe aborted by MCP host" };
47
+ // Interrupted already: nothing is spawned, and found comes from the lookup alone.
48
+ if (signal?.aborted) {
49
+ return Promise.resolve({ found: isJsScript ? existsSync(launcher) : commandExists(launcher, options?.env), ...aborted });
50
+ }
45
51
  return new Promise((resolve) => {
46
52
  let settled = false;
47
53
  let stdout = "";
48
54
  let timer;
55
+ let onAbort;
56
+ let abortRequested = false;
49
57
  const finish = (result) => {
50
58
  if (settled) return;
51
59
  settled = true;
52
60
  clearTimeout(timer);
61
+ if (onAbort) signal?.removeEventListener("abort", onAbort);
53
62
  resolve(result);
54
63
  };
55
- const child = spawn(execCommand, execArgs, { ...options, detached: DETACHED, stdio: ["ignore", "pipe", "pipe"] });
56
- // Capped: a version string is a line, and a launcher that streams instead should not be
57
- // accumulated whole while the probe waits out its timeout.
64
+ const [file, argv] = spawnCommandLine(launch.command, launch.args, launch.options);
65
+ const child = spawn(file, argv, { ...launch.options, detached: DETACHED, stdio: ["ignore", "pipe", "pipe"] });
66
+ // Capped: a version is one line.
58
67
  child.stdout?.on("data", (chunk) => {
59
68
  if (stdout.length < PROBE_STDOUT_CAP) stdout += chunk.toString();
60
69
  });
61
- // Drained, not merely piped. An unread pipe fills, the launcher blocks writing to it and so
62
- // never exits, and the probe can only report that as a timeout — a healthy but noisy
63
- // launcher reads out identically to a wedged one. Nothing consumes the bytes.
70
+ // Drained: a full pipe blocks a noisy launcher, which would then read as a timeout.
64
71
  child.stderr?.on("data", () => {});
65
72
  child.stderr?.on("error", () => {});
66
73
  child.on("error", () => finish({ found: false, version: null }));
74
+ const closed = new Promise((r) => child.once("close", r));
67
75
  child.on("close", (code) => {
76
+ if (abortRequested) return;
68
77
  const version = code === 0 ? stdout.trim() || null : null;
69
78
  finish({
70
79
  found: true,
@@ -73,21 +82,33 @@ export function probeAgentVersion(spawnSpec, timeoutMs = VERSION_PROBE_TIMEOUT_M
73
82
  });
74
83
  });
75
84
  timer = setTimeout(() => {
76
- // treeKill, not child.kill: the spawn spec carries shell:true on win32, where a plain
77
- // kill only reaches the wrapper and leaves the launcher running.
85
+ // treeKill: on win32 a plain kill reaches only the launcher, not what a .cmd or .ps1 started.
78
86
  if (child.pid) treeKill(child.pid).catch(() => {});
79
- // The launcher exists — it spawned — it just never answered, which is a different
80
- // diagnosis from "not installed" and has to read that way.
87
+ // It spawned, so it is installed; it did not answer.
81
88
  finish({ found: true, version: null, error: `version probe timed out after ${timeoutMs}ms` });
82
89
  }, timeoutMs);
83
90
  timer.unref?.();
91
+ // A host interrupt ends the probe at once rather than at its timeout.
92
+ // Returns once the probe has closed, so doctor does not leave it running; bounded like stop().
93
+ onAbort = () => {
94
+ // The timeout would otherwise still fire during the kill and return first.
95
+ clearTimeout(timer);
96
+ abortRequested = true;
97
+ const killed = child.pid ? treeKill(child.pid).catch(() => {}) : Promise.resolve();
98
+ const bound = new Promise((r) => setTimeout(r, PROBE_KILL_WAIT_MS).unref?.());
99
+ Promise.race([Promise.all([killed, closed]), bound]).then(() => finish({ found: true, ...aborted }));
100
+ };
101
+ signal?.addEventListener("abort", onAbort, { once: true });
84
102
  });
85
103
  }
86
104
 
87
- async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs }) {
105
+ async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs, signal, onClientReady }) {
88
106
  const workspaceDir = workspace || process.cwd();
89
107
  const client = clientFactory({ spawnSpec, cwd: workspaceDir });
108
+ // Handed out before the spawn, so shutdown can stop it.
109
+ onClientReady?.(client);
90
110
  let timer;
111
+ let onAbort;
91
112
  try {
92
113
  const details = {};
93
114
  const work = (async () => {
@@ -96,9 +117,8 @@ async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs
96
117
  await client.newSession(workspaceDir);
97
118
  details.protocolVersion = client.protocolVersion ?? null;
98
119
  details.agentCapabilities = client.agentCapabilities ?? {};
99
- // The ids delegate's model accepts: the model config option's values, base ids such as
100
- // gemini-4-neon. availableModels repeats each with a level suffix, which delegate does not
101
- // take, so it is the fallback only for an agent that reports no model option.
120
+ // The base ids delegate accepts, from the model option. availableModels carries level
121
+ // suffixes delegate does not take, so it is only the fallback.
102
122
  const modelOption = (client.configOptions ?? []).find((o) => o?.id === "model");
103
123
  const baseIds = allowedValues(modelOption);
104
124
  details.models = baseIds.length
@@ -107,32 +127,37 @@ async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs
107
127
  details.currentModel = (typeof modelOption?.currentValue === "string" ? modelOption.currentValue : null)
108
128
  ?? client.sessionModels?.currentModelId ?? null;
109
129
  details.modes = (client.sessionModes?.availableModes ?? []).map((m) => m?.id).filter(Boolean);
110
- // session/new already returned these. currentModel only — any other model needs a model
111
- // switch first, which this handshake does not send. name and category are what tell an
112
- // effort option apart when its id is unfamiliar; currentValue is the level in force.
130
+ // The current model's options only: another model's need a model switch first.
113
131
  details.currentModelOptions = describeOptions(client.configOptions);
114
- // The plan the signed-in account is on, as agy reports it.
115
132
  details.tier = client.sessionMeta?.antigravity?.tier ?? null;
116
133
  })();
117
134
  const timeout = new Promise((_, reject) => {
118
135
  timer = setTimeout(() => {
119
- // Not awaited, so the timeout still rejects at its stated deadline rather than at the
120
- // deadline plus teardown. The finally below awaits the same idempotent promise.
136
+ // Not awaited, so the timeout rejects on time; the finally awaits the same stop.
121
137
  try { Promise.resolve(client.stop()).catch(() => {}); } catch {}
122
138
  reject(new Error(`Handshake timed out after ${timeoutMs}ms`));
123
139
  }, timeoutMs);
124
140
  });
125
- await Promise.race([work, timeout]);
141
+ // A host interrupt stops the agent at once rather than leaving it to the handshake timeout.
142
+ const aborted = new Promise((_, reject) => {
143
+ onAbort = () => {
144
+ try { Promise.resolve(client.stop()).catch(() => {}); } catch {}
145
+ reject(new Error("Handshake aborted by MCP host"));
146
+ };
147
+ if (signal?.aborted) onAbort();
148
+ else signal?.addEventListener("abort", onAbort, { once: true });
149
+ });
150
+ await Promise.race([work, timeout, aborted]);
126
151
  return { ok: true, ...details };
127
152
  } catch (err) {
128
153
  return { ok: false, error: err?.message || String(err) };
129
154
  } finally {
130
155
  clearTimeout(timer);
131
- // Awaited so doctor does not return while the agent it spawned is still being torn down.
132
- // A killed child exits in milliseconds; only one that ignores the kill costs the full bound.
133
- // Graceful, so the session the handshake opened is closed; a timed-out handshake already
134
- // started the kill above, and stop() joins it.
135
- try { await Promise.resolve(client.stop({ graceMs: GRACEFUL_STOP_MS })); } catch {}
156
+ // Awaited, so doctor returns once its agent is stopped or the stop's deadline passed. Graceful,
157
+ // closing the handshake's session; after a timeout or abort it joins the kill already started.
158
+ // The abort listener stays on through the close, so an abort there forces the kill.
159
+ try { await Promise.resolve(client.stop({ graceMs: signal?.aborted ? 0 : GRACEFUL_STOP_MS })); } catch {}
160
+ if (onAbort) signal?.removeEventListener("abort", onAbort);
136
161
  }
137
162
  }
138
163
 
@@ -146,6 +171,8 @@ async function runDeepHandshake({ spawnSpec, clientFactory, workspace, timeoutMs
146
171
  * handshakeTimeoutMs?: number,
147
172
  * versionTimeoutMs?: number,
148
173
  * readVersion?: () => string,
174
+ * signal?: AbortSignal,
175
+ * onClientReady?: (client: any) => void,
149
176
  * }} [opts]
150
177
  */
151
178
  export async function runDoctor({
@@ -157,9 +184,11 @@ export async function runDoctor({
157
184
  handshakeTimeoutMs = HANDSHAKE_TIMEOUT_MS,
158
185
  versionTimeoutMs = VERSION_PROBE_TIMEOUT_MS,
159
186
  readVersion = readPackageVersion,
187
+ signal,
188
+ onClientReady,
160
189
  } = {}) {
161
190
  const { capabilities, version } = getClientInfo();
162
- const agentProbe = await probeAgentVersion(spawnSpec, versionTimeoutMs);
191
+ const agentProbe = await probeAgentVersion(spawnSpec, versionTimeoutMs, signal);
163
192
 
164
193
  /** @type {{ plugin: any, client: any, agent: any & { handshake?: any }, runtime: any, env: any }} */
165
194
  const out = {
@@ -194,12 +223,17 @@ export async function runDoctor({
194
223
  },
195
224
  };
196
225
 
197
- if (deep) {
226
+ if (deep && signal?.aborted) {
227
+ // Already interrupted: no agent is started.
228
+ out.agent.handshake = { ok: false, error: "Handshake aborted by MCP host" };
229
+ } else if (deep) {
198
230
  out.agent.handshake = await runDeepHandshake({
199
231
  spawnSpec,
200
232
  clientFactory,
201
233
  workspace,
202
234
  timeoutMs: handshakeTimeoutMs,
235
+ signal,
236
+ onClientReady,
203
237
  });
204
238
  }
205
239
 
package/src/errors.js CHANGED
@@ -1,8 +1,6 @@
1
1
  /**
2
- * Every failure this bridge raises carries a `reason`, which is what lets a caller tell
3
- * "fix your arguments" from "retry" without parsing prose. Errors that came off the wire also
4
- * carry the agent's JSON-RPC `code`. One shape, one constructor, so the tag is never forgotten
5
- * and the type checker has something to check against.
2
+ * Every failure carries a `reason`, so a caller can tell "fix your arguments" from "retry" without
3
+ * parsing prose. Errors off the wire also carry the agent's JSON-RPC `code`.
6
4
  *
7
5
  * @typedef {Error & { reason?: string, code?: number }} DelegateError
8
6
  */
package/src/jsonrpc.js CHANGED
@@ -10,16 +10,11 @@ function readLogSize(raw) {
10
10
  return Math.floor(n);
11
11
  }
12
12
 
13
- // Depth an unparseable AGY_DELEGATE_TRANSCRIPT reads as. Deliberately not DEFAULT_LOG_SIZE:
14
- // that one bounds what the log retains in memory, this one is how much lands in the caller's
15
- // context. 1.10.0 removed a 40-frame always-on dump from failure text; opt-in is what buys this
16
- // budget, so keep it in that neighbourhood.
13
+ // Depth for an unparseable AGY_DELEGATE_TRANSCRIPT. Not DEFAULT_LOG_SIZE: that bounds memory, this
14
+ // bounds what lands in the caller's context.
17
15
  const TRANSCRIPT_DEFAULT_FRAMES = 50;
18
16
 
19
- // Frames of transcript AGY_DELEGATE_TRANSCRIPT asks for. Unset or blank means none and a
20
- // number is the count (0 = none); anything unparseable reads as on at the default depth —
21
- // "true" and "yes" are natural things to set, and silently disabling the transcript on them is
22
- // the opposite of what the setter wanted.
17
+ // Unset or blank is none, a number is the count; anything else ("true", "yes") is the default depth.
23
18
  export function transcriptFrames(raw = process.env.AGY_DELEGATE_TRANSCRIPT) {
24
19
  if (raw === undefined || raw.trim() === "") return 0;
25
20
  const n = Number(raw);
@@ -44,25 +39,18 @@ export class JsonRpcPeer {
44
39
  this.onActivity = onActivity || (() => {});
45
40
  this.nextId = 1;
46
41
  this.pending = new Map();
47
- // 0 disables recording and is documented; anything unparseable is a typo, and silently
48
- // disabling the transcript on a typo is the opposite of what the setter wanted.
42
+ // 0 disables recording; a typo keeps the default rather than disabling it.
49
43
  this._logSize = readLogSize(process.env.ACP_LOG_SIZE);
50
- // The failure transcript is the only thing that reads these frames, and it is opt-in, so
51
- // recording by default retained up to _logSize × FRAME_CAP bytes per delegation that nothing
52
- // would ever ask for. ACP_LOG_SIZE still bounds retention and still disables at 0.
44
+ // Only the opt-in failure transcript reads these frames, so they are recorded only when it is on.
53
45
  this._recording = this._logSize > 0 && transcriptFrames() > 0;
54
46
  this._log = [];
55
47
  this.rl = readline.createInterface({ input });
56
- // The interface re-emits the input stream's error as its own, so the handler acp-client.js
57
- // puts on the child's stdout does not cover this one: an unhandled 'error' here is an
58
- // uncaught exception, which takes down the server and every concurrent delegation with it.
48
+ // readline re-emits the stream's error; unhandled, it takes down the server.
59
49
  this.rl.on("error", () => {});
60
50
  this.rl.on("line", (line) => this._onLine(line));
61
51
  }
62
52
 
63
- // Trimming to the cap on every frame meant shifting a 2000-entry array per frame, which on a
64
- // chatty turn cost more than parsing the frames. Let the array overshoot by a quarter and trim
65
- // in one batch; readers below take the last _logSize, so what the log reports is unchanged.
53
+ // Trimmed in batches once a quarter over the cap; readers take the last _logSize.
66
54
  _record(dir, line) {
67
55
  if (!this._recording) return;
68
56
  const truncated = line.length > FRAME_CAP ? line.slice(0, FRAME_CAP) : line;
@@ -89,20 +77,16 @@ export class JsonRpcPeer {
89
77
  let msg;
90
78
  try { msg = JSON.parse(line); } catch { return; }
91
79
  if (msg === null || typeof msg !== "object" || Array.isArray(msg)) return;
92
- // Only a parsed frame counts. A blank line, a launcher banner or anything else the agent
93
- // prints is not the protocol advancing, and treating it as such is what let a chatty
94
- // launcher hold the idle guard open and made "Last ACP frame Ns ago" report a stderr byte.
80
+ // Only a parsed frame counts as activity, not a banner or blank line.
95
81
  this.onActivity();
96
82
  const hasId = msg.id !== undefined && msg.id !== null;
97
83
  if (hasId && (msg.result !== undefined || msg.error !== undefined)) {
98
- // Keyed by string: a peer that echoes "1" for the id 1 is still answering that request,
99
- // and matching by identity left it pending until a timeout fired an hour later.
84
+ // Keyed by string: a peer may echo the id 1 as "1".
100
85
  const key = String(msg.id);
101
86
  const p = this.pending.get(key);
102
87
  if (p) {
103
88
  this.pending.delete(key);
104
- // An agent can put the actual reason in error.data.message; error.message alone
105
- // is a bare "Invalid params".
89
+ // The reason can be in error.data.message; error.message may be a bare "Invalid params".
106
90
  if (msg.error) {
107
91
  /** @type {import("./errors.js").DelegateError} */
108
92
  const err = new Error([msg.error.message || "rpc error", msg.error.data?.message].filter(Boolean).join(": "));
@@ -1,13 +1,10 @@
1
- // Config option ids differ per model, and a model rejects any id it does not declare. The set is
2
- // knowable only once a model is selected, from the configOptions the agent echoes back.
1
+ // Config option ids differ per model and are known only once a model is selected.
3
2
 
4
- // ACP marks a thought/reasoning level selector with category "thought_level" — agy declares
5
- // thought_level ("Thinking Level") that way. Categories are optional in ACP, so the ids and names
6
- // below still classify options from an agent that sends none. A match only nominates an option:
7
- // the requested value must still appear exactly among the values it advertises.
3
+ // ACP marks a thinking-level selector with category "thought_level", as agy does. Categories are
4
+ // optional, so ids and names also classify. A match only nominates an option: the value must still
5
+ // be one it advertises.
8
6
  const THOUGHT_LEVEL_IDS = new Set(["thinking", "reasoning", "effort", "reasoning_effort", "thought_level"]);
9
- // Never an effort setting, and doctor reports them as currentModel and modes, so a list of what a
10
- // model offers leaves them out.
7
+ // Never effort; doctor reports them separately, so option lists leave them out.
11
8
  const SELECTOR_IDS = new Set(["model", "mode"]);
12
9
 
13
10
  export function isThoughtLevel(opt) {
@@ -28,8 +25,7 @@ export function allowedValues(opt) {
28
25
  .filter((v) => typeof v === "string");
29
26
  }
30
27
 
31
- // What a model offers besides the model and mode selectors, as doctor reports it and as an
32
- // unrecognized effort names it. Optional metadata appears only when the agent sent a string.
28
+ // A model's options besides model and mode, for doctor and the unrecognized-effort error.
33
29
  export function describeOptions(options) {
34
30
  return (Array.isArray(options) ? options : [])
35
31
  .filter((o) => typeof o?.id === "string" && !SELECTOR_IDS.has(o.id))
@@ -42,9 +38,8 @@ export function describeOptions(options) {
42
38
  }));
43
39
  }
44
40
 
45
- // The current value of every recognized effort option, keyed by id. All of them rather than one
46
- // picked: a model can declare a thinking toggle beside a level, and either alone can mislead.
47
- // Undefined when no recognized option reports a string value.
41
+ // Every recognized effort option's current value, keyed by id: a model can declare a thinking toggle
42
+ // beside a level, and either alone can mislead.
48
43
  export function effortSettings(options) {
49
44
  const settings = {};
50
45
  for (const o of Array.isArray(options) ? options : []) {
@@ -55,11 +50,8 @@ export function effortSettings(options) {
55
50
  return Object.keys(settings).length > 0 ? settings : undefined;
56
51
  }
57
52
 
58
- // Resolve only values the selected model advertised. This keeps future vocabularies working
59
- // without aliases or a ranking table: xhigh, extra-high, max and ultra are just exact tokens.
60
- // No list, an empty list, or a thought-level option with no usable id/values is unavailable. A
61
- // list with nothing classified as thought-level is unrecognized — not proof the model has no
62
- // effort setting: categories are optional and ids get renamed, so the caller is shown the list.
53
+ // Exact advertised values only, so new level names need no aliases. No usable list is unavailable;
54
+ // a list with no recognized effort option is unrecognized, and the caller is shown the list.
63
55
  export function resolveEffort(options, value) {
64
56
  if (!Array.isArray(options) || options.length === 0) return { status: "unavailable" };
65
57
 
package/src/proc.js CHANGED
@@ -5,10 +5,9 @@ export function isChildAlive(child) {
5
5
  return child && child.exitCode === null && child.signalCode === null;
6
6
  }
7
7
 
8
- // POSIX only: detached makes the child a process group leader (setsid), which is what lets
9
- // treeKill reach the agent's own children. On win32 it would mean a separate console instead,
10
- // and taskkill /T already walks the tree. Every spawn site applies it, not resolveAcpSpawn —
11
- // an injected spawnSpec has to become a group leader too or the group kill finds nothing.
8
+ // POSIX only: detached makes the child a process group leader, so treeKill reaches its children.
9
+ // On win32 it would open a separate console, and taskkill /T walks the tree. Applied at every
10
+ // spawn site, so an injected spawnSpec gets it too.
12
11
  export const DETACHED = process.platform !== "win32";
13
12
 
14
13
  // Every process below pid, from one `ps` snapshot (Linux and macOS both have -A -o pid=,ppid=).
@@ -36,35 +35,27 @@ function descendantPids(pid) {
36
35
  }));
37
36
  }
38
37
 
39
- // On win32 a plain child.kill() only reaches the shell wrapper (spawn uses shell: true);
40
- // taskkill /T takes the whole tree so the agent itself dies too.
38
+ // On win32 a plain kill reaches only the launched process (agy.exe, or the cmd.exe or PowerShell
39
+ // running a script); taskkill /T takes the tree, agy's commands included.
41
40
  export async function treeKill(pid, { childAlive = true } = {}) {
42
41
  if (!pid) return;
43
42
  if (process.platform === "win32") {
44
- // taskkill /T walks parent links, which an exited leader no longer has: what it started is
45
- // either gone with it or detached and out of reach. So a post-exit kill has nothing left to
46
- // reach, and a reaped pid can already belong to somebody else — which makes the gate the
47
- // whole of it here, where POSIX still has the group to aim at.
43
+ // An exited leader has no tree left for taskkill to walk, and its pid may be reused.
48
44
  if (!childAlive) return;
49
45
  await /** @type {Promise<void>} */ (new Promise((resolve) => {
50
46
  execFile("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true }, () => resolve());
51
47
  }));
52
48
  return;
53
49
  }
54
- // agy runs each shell command in its own session, outside the agent's group, so the group kill
55
- // alone left a command running (a sleep outlived a hard-cap teardown in WSL). Walk the parent
56
- // links first, while the agent is still there to hold them, and kill each descendant and its
57
- // group too. Only while the child is alive: after a reap its pid can belong to someone else.
50
+ // agy runs each shell command in its own session, outside its group (measured in WSL), so
51
+ // descendants are walked and killed with their groups too, while the child is alive to hold them.
58
52
  const descendants = childAlive ? await descendantPids(pid) : [];
59
- // Negative pid signals the whole group, so the agent's descendants go with it. A group outlives
60
- // its leader while any member is left, which is why this runs even for an exited child: that is
61
- // the case where descendants are the only thing still running.
53
+ // The group, even after the leader exited: members can outlive it.
62
54
  try { process.kill(-pid, "SIGKILL"); } catch {}
63
55
  for (const d of descendants) {
64
56
  try { process.kill(-d, "SIGKILL"); } catch {}
65
57
  try { process.kill(d, "SIGKILL"); } catch {}
66
58
  }
67
- // Reaches a child that is not a group leader, where the group kill raised ESRCH. Skipped once
68
- // the child is gone, since a reaped pid can already belong to something else.
59
+ // A child that is not a group leader; skipped once reaped, as its pid may be reused.
69
60
  if (childAlive) { try { process.kill(pid, "SIGKILL"); } catch {} }
70
61
  }
@@ -9,24 +9,18 @@ export function createRequestRouter({ respond, respondError }) {
9
9
  try {
10
10
  if (method === "session/request_permission") {
11
11
  const opts = params?.options || [];
12
- // The two allow kinds only. Taking opts[0] when neither is offered returned a reject
13
- // id under a `selected` outcome, which the agent reads as an approval of the denial —
14
- // a silent skip from a bridge that advertises auto-approval. agy offers allow_once
15
- // ("allow") and reject_once ("deny").
12
+ // The allow kinds only: selecting a reject option would read as approving the denial.
13
+ // agy offers allow_once and reject_once.
16
14
  const pick =
17
15
  opts.find((o) => o.kind === "allow_always") ||
18
16
  opts.find((o) => o.kind === "allow_once");
19
- // Selecting nothing is not a selection: an options-less request answered with
20
- // optionId undefined is a malformed ACP response, and a request offering no allow
21
- // option is one this bridge can approve nothing in. Say cancelled to both and let the
22
- // agent decide what to do about it.
17
+ // No allow option: answered cancelled rather than a selection with no optionId.
23
18
  if (!pick?.optionId) return respond(id, { outcome: { outcome: "cancelled" } });
24
19
  return respond(id, { outcome: { outcome: "selected", optionId: pick.optionId } });
25
20
  }
26
21
  return respondError(id, -32601, `Unhandled method: ${method}`);
27
22
  } catch (err) {
28
- // -32603, not -32000: ACP assigns -32000 to auth_required, and a bug on this side
29
- // reported as "authenticate" sends the agent down a recovery path that cannot work.
23
+ // -32603, not -32000, which ACP reserves for auth_required.
30
24
  if (id != null) return respondError(id, -32603, `Router error: ${err?.message || err}`);
31
25
  }
32
26
  };