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/spawn.js CHANGED
@@ -1,27 +1,37 @@
1
1
  import process from "node:process";
2
- import { existsSync, statSync } from "node:fs";
2
+ import { lstatSync, statSync } from "node:fs";
3
3
  import path from "node:path";
4
4
 
5
+ // Splits on whitespace outside quotes. A quote opens a section only at the start of an argument or
6
+ // right after "=", and only when it closes: --log-file="C:\a b\x.log" is one argument, quotes
7
+ // removed, while the apostrophe in O'Brien stays a character. Backslashes are literal.
5
8
  export function splitArgs(raw) {
9
+ const s = String(raw || "");
6
10
  const args = [];
7
- const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
8
- for (const m of String(raw || "").matchAll(re)) {
9
- args.push(m[1] ?? m[2] ?? m[3]);
11
+ let i = 0;
12
+ for (;;) {
13
+ while (i < s.length && /\s/.test(s[i])) i++;
14
+ if (i >= s.length) return args;
15
+ let arg = "";
16
+ while (i < s.length && !/\s/.test(s[i])) {
17
+ const end = (s[i] === '"' || s[i] === "'") && (arg === "" || arg.endsWith("=")) ? s.indexOf(s[i], i + 1) : -1;
18
+ if (end === -1) { arg += s[i++]; continue; }
19
+ arg += s.slice(i + 1, end);
20
+ i = end + 1;
21
+ }
22
+ args.push(arg);
10
23
  }
11
- return args;
12
24
  }
13
25
 
14
- // --dangerously-skip-permissions makes agy approve its own tool calls instead of asking. The
15
- // request router still approves any session/request_permission that arrives, but agy issue
16
- // #1658 reports a subagent's command raising none and waiting for an approval that cannot come,
17
- // which only the flag reaches. With the flag, a probe turn raised no permission request at all.
26
+ // --dangerously-skip-permissions makes agy approve its own tool calls. The request router approves
27
+ // any permission request too, but a subagent's command can wait without raising one (agy #1658),
28
+ // which only the flag covers.
18
29
  export const DEFAULT_AGENT_ARGS = Object.freeze(["acp", "--dangerously-skip-permissions"]);
19
30
 
20
- // shell:true on win32 is what lets a .cmd/.ps1 launcher resolve at all, and it means the
21
- // command and args are parsed by cmd.exe. Safe only because both come from the environment,
22
- // which is already as trusted as this process: anything that can set them can run code here
23
- // anyway. Routing host- or caller-supplied values into either variable would turn this into a
24
- // command-injection path, so don't.
31
+ // shell:true on win32 marks the spec for the Windows launch at each spawn site (spawnArgv): the
32
+ // command is found first and started by file type, and only a .cmd or .bat reaches cmd.exe, which
33
+ // parses its line. Safe because both values come from the environment, as trusted as this process.
34
+ // Never route host or caller input into them: that would be command injection.
25
35
  export function resolveAcpSpawn() {
26
36
  const command = process.env.ACP_AGENT_COMMAND || "agy";
27
37
  const args = process.env.ACP_AGENT_ARGS
@@ -30,20 +40,99 @@ export function resolveAcpSpawn() {
30
40
  return { command, args, options: { shell: process.platform === "win32" } };
31
41
  }
32
42
 
33
- // Through a shell the spawn itself always succeeds: cmd.exe starts, fails to find the launcher and
34
- // exits 1 with a localized "is not recognized" line, so Node's spawn 'error' event never fires and
35
- // a missing agy reads as an agent crash. Resolving the launcher first is what lets that case be
36
- // reported as not installed. Mirrors cmd's lookup: a path is checked as given, a bare name against
37
- // each PATH entry, both with and without each PATHEXT extension.
43
+ // Under shell: true Node hands cmd.exe one joined line and quotes nothing, so a launcher path or an
44
+ // argument with a space or a cmd metacharacter split there. A value already holding a quote passes
45
+ // as given: cmd cannot nest them, and a pre-quoted path is how one with a space had to be written.
46
+ // %VAR% still expands, inside quotes too.
47
+ function cmdQuote(value) {
48
+ const s = String(value);
49
+ if (s.includes('"') || (s !== "" && !/[\s&|<>^(),;=]/.test(s))) return s;
50
+ // Doubled so the child's argv parser does not read a trailing backslash as escaping the quote.
51
+ return `"${s.replace(/(\\+)$/, "$1$1")}"`;
52
+ }
53
+
54
+ // The line is built here, quoted for cmd.exe, and passed alone: Node 24 warns (DEP0190) on args
55
+ // passed with shell: true.
56
+ /** @returns {[string, string[]]} */
57
+ export function spawnCommandLine(command, args, options) {
58
+ const argv = args ?? [];
59
+ if (!options?.shell) return [command, argv];
60
+ const quote = process.platform === "win32" ? cmdQuote : String;
61
+ return [[command, ...argv].map(quote).join(" "), []];
62
+ }
63
+
64
+ /**
65
+ * What to hand spawn() for a spec, or null when the launcher is not found. Applied at each spawn
66
+ * site, after doctor has built its --version args from the spec as configured. On win32 the command
67
+ * is looked up on every spawn (an update can move it) and started by the type of the file found:
68
+ * an .exe or .com directly, a .ps1 through PowerShell, anything else through cmd.exe.
69
+ * @param {string} command @param {string[] | undefined} args
70
+ * @param {{ shell?: boolean, env?: NodeJS.ProcessEnv } | undefined} options
71
+ * @returns {{ command: string, args: string[], options: any } | null}
72
+ */
73
+ export function spawnArgv(command, args, options) {
74
+ const argv = args ?? [];
75
+ if (!options?.shell) return { command, args: argv, options };
76
+ const env = options.env || process.env;
77
+ if (process.platform !== "win32") return commandExists(command, env) ? { command, args: argv, options } : null;
78
+ const file = findCommand(command, env);
79
+ if (!file) return null;
80
+ const ext = path.extname(file).toLowerCase();
81
+ // Exact arguments: cmd.exe would expand %VAR% and strip quotes and carets.
82
+ if (ext === ".exe" || ext === ".com") return { command: file, args: argv, options: { ...options, shell: false } };
83
+ // cmd.exe hands a .ps1 to its file association (an editor or an "open with" dialog) instead of
84
+ // running it.
85
+ if (ext === ".ps1") {
86
+ const rootKey = Object.keys(env).find((k) => k.toUpperCase() === "SYSTEMROOT");
87
+ const powershell = rootKey && env[rootKey]
88
+ ? path.win32.join(env[rootKey], "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
89
+ : "powershell.exe";
90
+ return {
91
+ command: powershell,
92
+ args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", file, ...argv],
93
+ options: { ...options, shell: false },
94
+ };
95
+ }
96
+ return { command: file, args: argv, options };
97
+ }
98
+
38
99
  export function commandExists(command, env = process.env) {
100
+ return findCommand(command, env) !== null;
101
+ }
102
+
103
+ // The file cmd's lookup lands on, as an absolute path (the spawn may run in another directory), or
104
+ // null: a path as given, a bare name in each PATH entry, each with and without every PATHEXT
105
+ // extension. On win32 a file with no extension never matches: cmd reports it "not recognized"
106
+ // (measured), and npm installs an sh script of that name beside the .cmd.
107
+ function findCommand(command, env) {
39
108
  const name = String(command || "").replace(/^["']|["']$/g, "");
40
- if (!name) return false;
109
+ if (!name) return null;
41
110
  const pathKey = Object.keys(env).find((k) => k.toUpperCase() === "PATH");
42
111
  const extKey = Object.keys(env).find((k) => k.toUpperCase() === "PATHEXT");
43
112
  const exts = ["", ...String((extKey && env[extKey]) || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)];
44
- const isFile = (p) => { try { return existsSync(p) && statSync(p).isFile(); } catch { return false; } };
45
- const hit = (base) => exts.some((ext) => isFile(base + ext) || isFile(base + ext.toLowerCase()));
113
+ const win32 = process.platform === "win32";
114
+ const isFile = (p) => {
115
+ if (win32 && !path.extname(p)) return false;
116
+ try {
117
+ return statSync(p).isFile();
118
+ } catch (e) {
119
+ // A Store app's alias (WindowsApps\pwsh.exe) is a link into a folder this user cannot stat,
120
+ // so stat fails with EACCES, yet cmd runs it. A link to a missing file fails with ENOENT.
121
+ if (!win32 || (e.code !== "EACCES" && e.code !== "EPERM")) return false;
122
+ try { return lstatSync(p).isSymbolicLink(); } catch { return false; }
123
+ }
124
+ };
125
+ const hit = (base) => {
126
+ for (const ext of exts) {
127
+ for (const p of [base + ext.toLowerCase(), base + ext]) if (isFile(p)) return path.resolve(p);
128
+ }
129
+ return null;
130
+ };
46
131
  if (/[\\/]/.test(name)) return hit(name);
47
132
  const dirs = String((pathKey && env[pathKey]) || "").split(path.delimiter).filter(Boolean);
48
- return dirs.some((dir) => hit(path.join(dir.replace(/^"|"$/g, ""), name)));
133
+ for (const dir of dirs) {
134
+ const found = hit(path.join(dir.replace(/^"|"$/g, ""), name));
135
+ if (found) return found;
136
+ }
137
+ return null;
49
138
  }
package/src/turn-state.js CHANGED
@@ -1,8 +1,5 @@
1
- // Everything describing the turn in progress, in one object because it has to be wiped as one:
2
- // session/load replays the previous turn as ordinary update frames, so anything left behind
3
- // leaks into the next result. Fields are declared in exactly one place, freshFields(), which is
4
- // also what reset() applies — a field added there is reset for free, and one that is missed is a
5
- // silent stale-data bug on resume.
1
+ // Everything describing the turn in progress, reset as one before the prompt. freshFields() is the
2
+ // single declaration reset() applies, so a field added there is reset too.
6
3
 
7
4
  const isTerminalToolStatus = (status) =>
8
5
  status === "completed" || status === "failed" || status === "cancelled";
@@ -46,36 +43,30 @@ function progressStream(prefix, onProgress, throttleMs) {
46
43
  function freshFields() {
47
44
  return {
48
45
  resultChunks: [],
49
- // Text superseded by a later tool call is normally a preamble ("Inspecting the
50
- // implementation."), but the rule cannot tell a preamble from the whole answer: an agent
51
- // that replies and then runs one more command has its entire reply discarded, leaving the
52
- // caller "" with stopReason end_turn and no error. Kept so it can be handed back when
53
- // nothing survived — labelled, never blended with a real final message.
46
+ // Text a later tool call superseded: usually a preamble, but it can be the whole answer when
47
+ // agy replies and then runs one more command. Handed back, labelled, only when nothing else is.
54
48
  discardedResult: "",
55
- // Message text sent while a tool call was still running, since that call started. Not part of
56
- // the result: it is handed back only when the turn ends with the call still unfinished, which
57
- // is how agy reports moving a long shell command to the background.
49
+ // Message text sent since a still-running tool call started; handed back only when the turn
50
+ // ends with the call unfinished (a backgrounded command or ask_question).
58
51
  unfinishedToolText: "",
59
52
  sawToolCall: false,
60
53
  collectingPostToolResult: false,
61
54
  activeToolCalls: new Set(),
62
- // Tool name per call id (agy's `name`, else its title), so an unfinished ask_question, which
63
- // waits on the caller, can be told from a backgrounded command, which finishes by itself.
55
+ // Tool name per call id, to tell an ask_question (waits on the caller) from a backgrounded
56
+ // command (finishes by itself).
64
57
  toolNames: new Map(),
65
- // Set by a usage_update and cleared by any other frame: agy closes a turn, prompted or not,
66
- // with a usage_update after its last message.
58
+ // The one-line label per call id, so a warning names the call still open, not the newest one.
59
+ toolLabels: new Map(),
60
+ // Set by a usage_update, cleared by any other frame: agy closes a completed turn, prompted or
61
+ // not, with one.
67
62
  usageAfterActivity: false,
68
- // The newest usage_update's { used, size }: the conversation's context in tokens and the
69
- // model's window. Unlike the prompt reply's usage it covers a background continuation too.
63
+ // The newest usage_update's { used, size }; unlike the reply's usage it covers a continuation.
70
64
  contextUsage: undefined,
71
65
  lastFrameAt: 0,
72
- // Ids observed terminal, so a stale non-terminal re-send for one is recognized and dropped
73
- // instead of restarting collection — which would demote an already-collected final message
74
- // to discardedResult and mislabel it pre-tool-fallback.
66
+ // Ids seen terminal, so a stale non-terminal re-send cannot discard a collected final message.
75
67
  finishedToolCalls: new Set(),
76
- // agy writes its plan as an artifact: a write_file call carrying ArtifactMetadata, saved
77
- // under ~/.gemini/antigravity-cli/brain/<sessionId>/. Keyed by path, so a rewrite of the
78
- // same artifact replaces the earlier entry.
68
+ // agy's artifacts (the plan): write_file calls carrying ArtifactMetadata, under
69
+ // ~/.gemini/antigravity-cli/brain/<sessionId>/. Keyed by path, so a rewrite replaces.
79
70
  artifacts: new Map(),
80
71
  touched: new Set(),
81
72
  lastToolLabel: null,
@@ -107,8 +98,7 @@ export function makeTurnState({ onProgress, progressThrottleMs = 2000 } = {}) {
107
98
  state.resultChunks.length = 0;
108
99
  },
109
100
 
110
- // The stream is the model's own message, bounded by its output limit; a byte cap
111
- // here would hand back a partial answer as if it were the whole one.
101
+ // Uncapped: a cap would return a partial answer as the whole one.
112
102
  appendResult(text) {
113
103
  state.resultChunks.push(text);
114
104
  },
@@ -141,8 +131,8 @@ export function makeTurnState({ onProgress, progressThrottleMs = 2000 } = {}) {
141
131
  state.finishedToolCalls.add(toolCallId);
142
132
  }
143
133
  if (state.activeToolCalls.size === 0 && !state.collectingPostToolResult) {
144
- // Discard any message text emitted while tools were still running.
145
- // A duplicate or late terminal update must not wipe an already-collected final message.
134
+ // Drop text sent while tools ran; the guard above keeps a late duplicate from wiping a
135
+ // collected final message.
146
136
  state.resetResult();
147
137
  state.collectingPostToolResult = true;
148
138
  }
package/src/version.js CHANGED
@@ -8,13 +8,12 @@ function readVersion() {
8
8
  return JSON.parse(readFileSync(PKG_PATH, "utf8")).version;
9
9
  }
10
10
 
11
- // Captured once, for the ACP/MCP identity handshake that is sent at connect and never re-read.
11
+ // Captured once, for the ACP and MCP identity sent at connect.
12
12
  export const VERSION = readVersion();
13
13
 
14
- // doctor reads fresh rather than using the constant: the MCP child is long-lived and
15
- // /reload-plugins does not restart it, so a version captured at process start goes stale after
16
- // an in-place upgrade — exactly when doctor is run to confirm the new version shipped. An
17
- // un-restarted child running old code stays a gap, but no in-process value can close that.
14
+ // Read fresh for doctor: /reload-plugins does not restart the server, so after an in-place upgrade
15
+ // the constant is stale. doctor then reports the installed version; the running server still runs
16
+ // the old code until restarted.
18
17
  export function readPackageVersion() {
19
18
  try {
20
19
  return readVersion();