grok-delegate-mcp 0.0.0-stage โ†’ 4.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Andrei Lungeanu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/PRIVACY.md ADDED
@@ -0,0 +1,11 @@
1
+ # Privacy
2
+
3
+ Grok Delegate runs as a local stdio MCP server. The project author does not operate a backend for the plugin and does not receive your code, prompts, workspace contents, session identifiers, diagnostics, or usage telemetry.
4
+
5
+ Claude Code installs run the server bundled in the plugin cache. On first session, the plugin may run `npm install --omit=dev` inside that cache to fetch its open-source runtime dependencies; it does not install them into your project. Codex, Copilot, VS Code, and standalone MCP configurations start the published package through `npx`, so npm may apply its own registry logging under npm's policies.
6
+
7
+ When you delegate, the local server starts `grok`. Task prompts, selected workspace content, model requests, and Grok account usage are handled by Grok under [Grok's terms and privacy policy](https://x.ai/legal). Your MCP host may separately process the prompt and tool results under its own terms.
8
+
9
+ The MCP response can contain file paths, agent output, plan text, diagnostic information, and session identifiers. Review that output before sharing logs or bug reports. The plugin does not redact secrets found in prompts, files, agent output, or diagnostics.
10
+
11
+ For security issues, see [SECURITY.md](SECURITY.md) or open a [GitHub Security Advisory](https://github.com/andreilungeanu/grok-delegate-mcp/security/advisories/new).
package/README.md CHANGED
@@ -1,3 +1,230 @@
1
- # Temporary Holding Version
1
+ # Grok Delegate
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Turn your coding agent into a council. Bring Composer and Grok into the conversation, then hand them the work.**
4
+
5
+ [![npm version](https://img.shields.io/npm/v/grok-delegate-mcp)](https://www.npmjs.com/package/grok-delegate-mcp)
6
+ [![npm downloads](https://img.shields.io/npm/dt/grok-delegate-mcp)](https://www.npmjs.com/package/grok-delegate-mcp)
7
+ [![MCP Registry](https://img.shields.io/badge/MCP%20Registry-listed-blue)](https://registry.modelcontextprotocol.io/v0.1/servers?search=grok-delegate&version=latest)
8
+ [![grok-delegate-mcp MCP server](https://glama.ai/mcp/servers/andreilungeanu/grok-delegate-mcp/badges/score.svg)](https://glama.ai/mcp/servers/andreilungeanu/grok-delegate-mcp)
9
+ [![node](https://img.shields.io/node/v/grok-delegate-mcp)](https://nodejs.org)
10
+ [![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
11
+ [![tests](https://github.com/andreilungeanu/grok-delegate-mcp/actions/workflows/test.yml/badge.svg)](https://github.com/andreilungeanu/grok-delegate-mcp/actions/workflows/test.yml)
12
+
13
+ <img src="assets/logo-light.png" alt="Grok Delegate logo" width="105" align="left" hspace="15">
14
+
15
+ Grok Delegate is the MCP bridge to **the Grok Build CLI**. From Claude Code, ChatGPT/Codex, Copilot or any MCP client, your agent can ask Composer or Grok for a second opinion, put one question to several models at once, or hand Grok a plan to build, and get a structured result back from each call.
16
+
17
+ <br clear="left">
18
+
19
+ ![A terminal recording of Claude Code asking Grok 4.7 why a repo prints "today 0": in ask mode Grok finds that commits are bucketed by UTC while the grid uses local dates; Grok then builds the fix with a test that fails on the old code, and Claude checks the result, sees all four tests pass, and flags that the new test would pass on the old code on a machine set to UTC](assets/demo.gif)
20
+
21
+ ## ๐Ÿง  Get a second opinion
22
+
23
+ > Ask Grok what it thinks about moving the session store to SQLite.
24
+
25
+ Grok reads the repo and answers in `ask` mode, and your agent sets that answer beside its own. You see where the two disagree before you choose a direction.
26
+
27
+ Ask several at once, and your agent sends each the same brief in parallel, compares the answers, and checks the claims that matter:
28
+
29
+ > Ask Composer and Grok whether we should split this service, and tell me where they disagree.
30
+
31
+ With [Codex Delegate](https://github.com/andreilungeanu/codex-delegate-mcp) or [Antigravity Delegate](https://github.com/andreilungeanu/agy-delegate-mcp) installed too, the same prompt reaches GPT or Gemini models.
32
+
33
+ ## ๐Ÿ› ๏ธ Hand off the work
34
+
35
+ > Delegate to Grok: migrate src/api from callbacks to async/await and update the tests. Plan it first.
36
+
37
+ Your agent writes the brief, Grok edits the files, and your agent reads the diff and runs the tests before it reports back.
38
+
39
+ - ๐Ÿ“‹ **Plan, approve, build** โ€” `plan` mode returns Grok's plan; once you approve, the same session implements it.
40
+ - ๐Ÿ’ฌ **No stalled runs** โ€” when Grok needs a decision, it ends the turn and returns the question as a normal result. Your agent answers by resuming the same session.
41
+ - ๐Ÿงต **Resume, even on another model** โ€” follow up in the same session with `resumeSessionId`; `effectiveModel` tells you when a different model served the turn.
42
+
43
+ ![You and your agent plan and review; the MCP delegate tool hands the brief to Grok Build (Grok models), which implements and edits your workspace; a clean result comes back with what changed, which files, and the plan, for your agent to review](assets/flow.png)
44
+
45
+ ## Features
46
+
47
+ - ๐Ÿ“ฆ **Clean, named results** โ€” final answer and session id, plus the files the edit tools reported, and todo progress when work is left unfinished, returned as one compact JSON payload. Nothing to scrape.
48
+ - โณ **Runs in the background, with MCP Tasks** โ€” `delegate` serves the MCP Tasks extension (`io.modelcontextprotocol/tasks`), so a host that speaks it gets a task back once Grok has the prompt and the result when Grok finishes. In the main session of the interactive Claude Code CLI, you keep working and the result arrives as a task notification; calls from subagents wait for the result.
49
+ - ๐Ÿ–ผ๏ธ **Attach what prose can't point at** โ€” `contextFiles` sends screenshots, mockups and other files along with the brief.
50
+ - ๐Ÿ”‹ **Runs on Grok's usage pool** โ€” Grok models draw from your **Grok plan's weekly usage** ([plans and usage](https://docs.x.ai/x-subscription/usage-limits)), separate from your host's chat quota.
51
+ - ๐Ÿค **Native plugins** โ€” install into Claude Code, ChatGPT/Codex, Google Antigravity, or GitHub Copilot CLI and just say *"ask Grok"* or *"delegate this to Grok"*. The shared skill teaches your agent to write the brief and review the result.
52
+ - ๐Ÿฉบ **Self-diagnosing** โ€” a `doctor` tool that tells you exactly what's missing if setup isn't right.
53
+ - ๐Ÿ”Œ **Portable** โ€” plain stdio MCP, so it runs anywhere: VS Code, JetBrains, Windsurf, Visual Studio, OpenCode, Antigravity, and more.
54
+
55
+ `workspace` is the agent's working directory, not a limit, and the CLI narrows what `ask` and `plan` may do โ€” [Security](SECURITY.md) and the [delegate reference](skills/delegate/reference.md) spell out what the bridge enforces and what it reports back.
56
+
57
+ ![Delegate result payload](assets/result-json.png)
58
+
59
+ ## Your agent and its peers
60
+
61
+ Each plugin works on its own, and they are built to work together. Install the ones your subscriptions cover, and the agent you already use can bring Gemini 4 Neon, Carbon or Hydrogen, GPT-6.2 Sol or Astra, and Grok 4.7 or Composer 2.5 into the same conversation as peers. One question goes to all of them in parallel, and your agent sets their answers beside its own.
62
+
63
+ > Ask Gemini Neon, Codex Sol and Grok 4.7 how they would restructure the auth module, then tell me where they agree.
64
+
65
+ ![A terminal recording of Claude Code asking Gemini Neon, Codex Sol and Grok 4.7 why a repo prints "today 0": three delegate calls run as background tasks, the answers come back, and Claude lists where the models agree and where they differ; Codex then builds the chosen fix on the same thread, and Claude confirms the new test fails on the old code and all four tests pass](assets/council.gif)
66
+
67
+ - [Codex Delegate](https://github.com/andreilungeanu/codex-delegate-mcp) โ€” the OpenAI Codex CLI: GPT-6.2 Sol, GPT-6.2 Astra and the other Codex models
68
+ - **Grok Delegate** (this one) โ€” the Grok Build CLI: Grok 4.7, Composer 2.5
69
+ - [Antigravity Delegate](https://github.com/andreilungeanu/agy-delegate-mcp) โ€” Google Antigravity's CLI: Gemini 4 Neon, Carbon and Hydrogen
70
+
71
+ Model names are examples; each CLI offers what your account includes.
72
+
73
+ ## Install
74
+
75
+ You need [Node.js 20+](https://nodejs.org/) and [Grok Build](https://docs.grok.com/build/whats-new), signed in (`grok login`).
76
+
77
+ ### Claude Code
78
+
79
+ ```shell
80
+ /plugin marketplace add andreilungeanu/grok-delegate-mcp
81
+ /plugin install grok-delegate@grok-delegate-mcp
82
+ ```
83
+
84
+ Then just ask:
85
+
86
+ > Delegate to Grok: migrate src/api from callbacks to async/await and update the tests, then walk me through what changed.
87
+
88
+ That's the whole loop โ€” Claude writes the brief, Grok grinds through the files, Claude walks you through the diff.
89
+
90
+ ### ChatGPT desktop / Codex
91
+
92
+ ```shell
93
+ codex plugin marketplace add andreilungeanu/grok-delegate-mcp
94
+ codex plugin add grok-delegate@grok-delegate-mcp
95
+ ```
96
+
97
+ ### Google Antigravity
98
+
99
+ ```shell
100
+ agy plugin install https://github.com/andreilungeanu/grok-delegate-mcp
101
+ ```
102
+
103
+ Restart the Antigravity app to load it. If you added `grok-delegate` to `mcp_config.json` by hand, remove that entry.
104
+
105
+ Without the CLI, use the manual config under [Client-specific config locations](#client-specific-config-locations).
106
+
107
+ ### GitHub Copilot CLI
108
+
109
+ ```shell
110
+ copilot plugin marketplace add andreilungeanu/grok-delegate-mcp
111
+ copilot plugin install grok-delegate@grok-delegate-mcp
112
+ ```
113
+
114
+ ### Any other MCP client
115
+
116
+ ```json
117
+ {
118
+ "mcpServers": {
119
+ "grok-delegate": {
120
+ "command": "npx",
121
+ "args": ["-y", "grok-delegate-mcp"]
122
+ }
123
+ }
124
+ }
125
+ ```
126
+
127
+ ### Client-specific config locations
128
+
129
+ <details>
130
+ <summary><strong>VS Code</strong> โ€” one-click install, or <code>.vscode/mcp.json</code></summary>
131
+
132
+ [![Install in VS Code](https://img.shields.io/badge/VS_Code-Install_server-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://vscode.dev/redirect/mcp/install?name=grok-delegate&config=%7B%22type%22%3A%22stdio%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22grok-delegate-mcp%22%5D%7D)
133
+ [![Install in VS Code Insiders](https://img.shields.io/badge/VS_Code_Insiders-Install_server-24bfa5?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=grok-delegate&config=%7B%22type%22%3A%22stdio%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22grok-delegate-mcp%22%5D%7D&quality=insiders)
134
+
135
+ Or add it manually:
136
+
137
+ ```json
138
+ {
139
+ "servers": {
140
+ "grok-delegate": {
141
+ "type": "stdio",
142
+ "command": "npx",
143
+ "args": ["-y", "grok-delegate-mcp"]
144
+ }
145
+ }
146
+ }
147
+ ```
148
+
149
+ Or run **Chat: Install Plugin From Source** with this repository's URL.
150
+
151
+ </details>
152
+
153
+ <details>
154
+ <summary><strong>JetBrains AI Assistant</strong> โ€” Settings โ†’ Tools โ†’ AI Assistant โ†’ MCP</summary>
155
+
156
+ Under **Settings โ†’ Tools โ†’ AI Assistant โ†’ Model Context Protocol (MCP)**, add a server with command `npx` and arguments `-y grok-delegate-mcp`.
157
+
158
+ </details>
159
+
160
+ <details>
161
+ <summary><strong>Windsurf</strong> โ€” <code>~/.codeium/windsurf/mcp_config.json</code></summary>
162
+
163
+ Same `mcpServers` block as the generic snippet above. Cascade caps you at 100 tools across all servers.
164
+
165
+ </details>
166
+
167
+ <details>
168
+ <summary><strong>Visual Studio 2022 / 2026</strong> โ€” <code>%USERPROFILE%\.mcp.json</code></summary>
169
+
170
+ Same `servers` + `type: "stdio"` shape as VS Code. Requires Visual Studio 2026, or 2022 17.14+. Note the top-level key is `servers`, not `mcpServers`. Visual Studio also discovers `.mcp.json` next to the solution, plus `.vscode/mcp.json`.
171
+
172
+ </details>
173
+
174
+ <details>
175
+ <summary><strong>OpenCode</strong> โ€” <code>~/.config/opencode/opencode.json</code> or project <code>opencode.json</code></summary>
176
+
177
+ OpenCode does **not** use `mcpServers`. Local servers go under `mcp`, with `type: "local"` and `command` as one array:
178
+
179
+ ```json
180
+ {
181
+ "$schema": "https://opencode.ai/config.json",
182
+ "mcp": {
183
+ "grok-delegate": {
184
+ "type": "local",
185
+ "command": ["npx", "-y", "grok-delegate-mcp"],
186
+ "enabled": true
187
+ }
188
+ }
189
+ }
190
+ ```
191
+
192
+ </details>
193
+
194
+ <details>
195
+ <summary><strong>Google Antigravity</strong> (without the plugin) โ€” <code>~/.gemini/config/mcp_config.json</code> or workspace <code>.agents/mcp_config.json</code></summary>
196
+
197
+ ```json
198
+ {
199
+ "mcpServers": {
200
+ "grok-delegate": {
201
+ "command": "npx",
202
+ "args": ["-y", "grok-delegate-mcp"],
203
+ "timeoutSeconds": 21660,
204
+ "tools": { "delegate": { "background": "always" } }
205
+ }
206
+ }
207
+ }
208
+ ```
209
+
210
+ </details>
211
+
212
+ <details>
213
+ <summary><strong>Kiro</strong> โ€” <code>.kiro/settings/mcp.json</code> or <code>~/.kiro/settings/mcp.json</code></summary>
214
+
215
+ Same `mcpServers` block as the generic snippet above. Workspace file wins when both exist.
216
+
217
+ </details>
218
+
219
+ <details>
220
+ <summary><strong>Kilo Code</strong> โ€” <code>kilo.jsonc</code> (<code>mcp</code> key, not <code>mcpServers</code>)</summary>
221
+
222
+ Same shape as OpenCode: `type: "local"` and `command` as one array. In the VS Code extension: **Settings โ†’ MCP โ†’ Add Server โ†’ Local (stdio)**. On Windows, if `npx` is not found, use command `cmd` with arguments `/c`, `npx`, `-y`, `grok-delegate-mcp`.
223
+
224
+ </details>
225
+
226
+ ## License
227
+
228
+ MIT ยฉ [Andrei Lungeanu](https://github.com/andreilungeanu)
229
+
230
+ <sub>[Technical reference](TECHNICAL.md) ยท [Security](SECURITY.md) ยท [Privacy](PRIVACY.md) ยท [Terms](TERMS.md) ยท [Changelog](CHANGELOG.md)</sub>
package/SECURITY.md ADDED
@@ -0,0 +1,37 @@
1
+ # Security
2
+
3
+ ## What this plugin does
4
+
5
+ `grok-delegate-mcp` spawns **Grok Build** (`grok`) in your workspace and **auto-approves every
6
+ permission it requests** over ACP, in every mode โ€” `agent`, `plan` and `ask`. Each request is
7
+ answered with the broadest allow option the agent offered (`allow_always`, else `allow_once`).
8
+
9
+ `workspace` is the agent's working directory, and a run can reach outside it. In `ask` the
10
+ CLI refuses shell commands and file writes. In `plan` it refuses its write tool outside the
11
+ plan file, while shell commands still run and can change files. In `agent`, delegated tasks
12
+ can create, modify, or delete files anywhere your user account can reach, and reach the
13
+ network.
14
+
15
+ Treat every `delegate` call like handing an engineer a shell on your machine. Your MCP host
16
+ is the orchestrator: it should scope the brief, then review `filesReportedByEditTools` and
17
+ the git diff. That field lists what the agent's edit tools reported touching; the git diff
18
+ is authoritative.
19
+
20
+ ## Recommendations
21
+
22
+ - Point `workspace` at the smallest directory that contains the task (not `$HOME` or `/`).
23
+ It scopes what the agent works on, not what it can reach.
24
+ - Review the git diff before committing, after every run โ€” including `plan` and `ask` ones.
25
+ - Run verification (tests, lint) after delegation โ€” the delegate skill asks Claude to do
26
+ this, but automated gates in CI are still your backstop.
27
+ - `contextFiles` resolve against `workspace` and may point outside it. The bridge forwards
28
+ attachments as they are; treat them as untrusted.
29
+ - Do not commit secrets (`.env`, credentials, tokens). The bridge does not redact them from
30
+ agent context.
31
+
32
+ ## Reporting vulnerabilities
33
+
34
+ If you find a security issue in this bridge (not in Grok Build or an MCP host),
35
+ please open a [GitHub Security Advisory](https://github.com/andreilungeanu/grok-delegate-mcp/security/advisories/new)
36
+ or email the maintainer listed in `package.json` instead of filing a public issue with
37
+ exploit details.
package/TERMS.md ADDED
@@ -0,0 +1,9 @@
1
+ # Terms of Use
2
+
3
+ Grok Delegate is provided under the MIT License on an "as is" basis, without warranties or guarantees.
4
+
5
+ The plugin runs locally and starts `grok` with access to the workspace selected for a delegation. Delegated agent-mode tasks may create, modify, or delete files. You are responsible for choosing an appropriate workspace, reviewing changes, protecting credentials, and complying with the terms that apply to Grok, your MCP host, and any model you select.
6
+
7
+ The project author does not operate the Grok service, receive delegated source code, or control the behavior of third-party models and clients. Do not use the plugin for unlawful activity or in a way that violates third-party rights or service terms.
8
+
9
+ For support, open a [GitHub issue](https://github.com/andreilungeanu/grok-delegate-mcp/issues). For security reports, follow [SECURITY.md](SECURITY.md).
package/package.json CHANGED
@@ -1,6 +1,68 @@
1
1
  {
2
2
  "name": "grok-delegate-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "4.0.0",
4
+ "mcpName": "io.github.andreilungeanu/grok-delegate-mcp",
5
+ "type": "module",
6
+ "description": "Turn your coding agent into a council: bring Grok and Composer into the conversation for second opinions, then hand them plans and edits. MCP server and plugin for the Grok Build CLI.",
7
+ "license": "MIT",
8
+ "author": "Andrei Lungeanu <andrei@lungeanu.ro>",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/andreilungeanu/grok-delegate-mcp.git"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/andreilungeanu/grok-delegate-mcp/issues"
15
+ },
16
+ "homepage": "https://github.com/andreilungeanu/grok-delegate-mcp#readme",
17
+ "keywords": [
18
+ "mcp",
19
+ "grok",
20
+ "grok-build",
21
+ "acp",
22
+ "agent-client-protocol",
23
+ "claude-code",
24
+ "codex",
25
+ "chatgpt",
26
+ "github-copilot",
27
+ "vscode",
28
+ "opencode",
29
+ "antigravity",
30
+ "windsurf",
31
+ "composer",
32
+ "composer-2.5",
33
+ "delegation",
34
+ "coding-agent",
35
+ "ai-agents"
36
+ ],
37
+ "main": "src/server.js",
38
+ "bin": {
39
+ "grok-delegate-mcp": "src/server.js"
40
+ },
41
+ "engines": {
42
+ "node": ">=20"
43
+ },
44
+ "files": [
45
+ "src",
46
+ "README.md",
47
+ "PRIVACY.md",
48
+ "SECURITY.md",
49
+ "TERMS.md",
50
+ "LICENSE",
51
+ "CHANGELOG.md"
52
+ ],
53
+ "scripts": {
54
+ "test": "node scripts/run-tests.mjs",
55
+ "test:pack": "node test/npm-package-smoke.mjs",
56
+ "start": "node src/server.js",
57
+ "typecheck": "tsc -p tsconfig.json"
58
+ },
59
+ "dependencies": {
60
+ "@modelcontextprotocol/server": "2.4.0",
61
+ "zod": "^4.6.5"
62
+ },
63
+ "devDependencies": {
64
+ "@modelcontextprotocol/client": "2.4.0",
65
+ "@types/node": "^26.1.1",
66
+ "typescript": "^7.0.2"
67
+ }
68
+ }
@@ -0,0 +1,201 @@
1
+ import { EventEmitter } from "node:events";
2
+ import { StringDecoder } from "node:string_decoder";
3
+ import { JsonRpcPeer } from "./jsonrpc.js";
4
+ import { createRequestRouter } from "./request-router.js";
5
+ import { commandExists, overlayEnv, resolveAcpSpawn } from "./spawn.js";
6
+ import { children, isChildAlive, spawnChild, stopChild } from "./proc.js";
7
+ import { VERSION } from "./version.js";
8
+ import { makeError } from "./errors.js";
9
+
10
+ const STDERR_CAP = 64 * 1024;
11
+
12
+ // Each phase lists the transitions it allows; any other is refused.
13
+ /** @typedef {"setup" | "running" | "cancelled-in-setup" | "cancelled" | "ended" | "exited"} WirePhase */
14
+ /** @typedef {"prompt" | "cancel" | "end" | "exit"} WireTransition */
15
+ /** @type {Record<WirePhase, Partial<Record<WireTransition, WirePhase>>>} */
16
+ const PHASES = {
17
+ setup: { prompt: "running", cancel: "cancelled-in-setup", end: "ended", exit: "exited" },
18
+ running: { cancel: "cancelled", end: "ended", exit: "exited" },
19
+ "cancelled-in-setup": { exit: "exited" },
20
+ cancelled: { exit: "exited" },
21
+ ended: { exit: "exited" },
22
+ exited: {},
23
+ };
24
+
25
+ // What a request the phase refuses throws; after a cancel before the prompt, with the cancel's reason.
26
+ /** @param {WirePhase} phase */
27
+ function wireClosed(phase) {
28
+ return phase === "cancelled-in-setup"
29
+ ? makeError("cancelled-in-setup", "cancelled before the prompt was sent")
30
+ : makeError("wire-closed", `no prompt can go out: the wire is ${phase}`);
31
+ }
32
+
33
+ export class AcpClient extends EventEmitter {
34
+ /**
35
+ * @param {{
36
+ * spawnSpec?: { command: string, args: string[], options?: { env?: NodeJS.ProcessEnv, [key: string]: any } },
37
+ * agentEnv?: Record<string, string>,
38
+ * onPlanHandoff?: (planContent: any) => void,
39
+ * onQuestions?: (questions: any) => void,
40
+ * registry?: import("./proc.js").ChildRegistry,
41
+ * }} [opts]
42
+ */
43
+ constructor({ spawnSpec, agentEnv, onPlanHandoff, onQuestions, registry = children } = {}) {
44
+ super();
45
+ const spec = spawnSpec || resolveAcpSpawn();
46
+ // agentEnv: variables for this agent process alone, over the spec's environment.
47
+ this.spawnSpec = agentEnv
48
+ ? { ...spec, options: { ...spec.options, env: overlayEnv(spec.options?.env ?? process.env, agentEnv) } }
49
+ : spec;
50
+ this.registry = registry;
51
+ /** @type {any} */
52
+ this._child = null;
53
+ this.onPlanHandoff = onPlanHandoff;
54
+ this.onQuestions = onQuestions;
55
+ // The stderr tail an exit error quotes; not counted as activity.
56
+ this.stderrBuffer = "";
57
+ /** @type {Promise<boolean> | null} */
58
+ this._stopping = null;
59
+ /** @type {WirePhase} */
60
+ this._phase = "setup";
61
+ }
62
+
63
+ get child() { return this._child; }
64
+
65
+ async start() {
66
+ const { command, args, options } = this.spawnSpec;
67
+ const opts = /** @type {{ shell?: boolean, env?: NodeJS.ProcessEnv }} */ (options);
68
+ if (opts?.shell && !commandExists(command, opts.env)) {
69
+ throw makeError("spawn-failed", `Failed to spawn agent (${command}): not found on PATH. Install Grok Build and run 'grok login'.`);
70
+ }
71
+ this._child = spawnChild(command, args, opts, { stdio: ["pipe", "pipe", "pipe"] }, this.registry);
72
+ this.stderrBuffer = "";
73
+ // Keeps a UTF-8 character split across reads whole.
74
+ const stderrDecoder = new StringDecoder("utf8");
75
+ this.child.stderr.on("data", (chunk) => {
76
+ this.stderrBuffer = (this.stderrBuffer + stderrDecoder.write(chunk)).slice(-STDERR_CAP);
77
+ });
78
+ this.child.stderr.on("error", () => {});
79
+ // session/cancel can be written after the agent is gone, and an unhandled pipe 'error' would
80
+ // take down the server. readline adds no handler on stdout either.
81
+ this.child.stdin.on("error", () => {});
82
+ this.child.stdout.on("error", () => {});
83
+ // Both 'exit' and 'close' land here; the transition the first one takes refuses the second.
84
+ const emitExit = (code, signal) => {
85
+ if (!this._advance("exit")) return;
86
+ const stderr = this.stderrBuffer;
87
+ const err = makeError(
88
+ "agent-exit",
89
+ // stderr whole, bounded by the 64KB buffer: why the agent died (a rejected model, a spent
90
+ // quota, an expired login) can sit anywhere in it.
91
+ `agent exited (code=${code}${signal ? ", signal=" + signal : ""})${stderr ? ": " + String(stderr) : ""}`
92
+ );
93
+ // exit + rejectAllPending both settle the same Promise.race; second rejection is intentional.
94
+ this.peer?.rejectAllPending(err);
95
+ this.emit("exit", { code, signal, stderr });
96
+ };
97
+ this.child.once("exit", emitExit);
98
+ this.child.once("close", emitExit);
99
+ this.router = null;
100
+ this.peer = new JsonRpcPeer(this.child.stdout, this.child.stdin, {
101
+ onNotification: (method, params) => {
102
+ if (method === "session/update") this.emit("update", params);
103
+ if (method === "_x.ai/task_backgrounded" || method === "_x.ai/task_completed") this.emit("background-task", params?.update);
104
+ },
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.
107
+ onRequest: (id, method, params) => {
108
+ if (this.router) Promise.resolve(this.router(id, method, params)).catch(() => {});
109
+ },
110
+ onActivity: () => this.emit("activity"),
111
+ });
112
+ this.router = createRequestRouter({
113
+ respond: (id, r) => this.peer.respond(id, r),
114
+ respondError: (id, c, m) => this.peer.respondError(id, c, m),
115
+ onPlanHandoff: this.onPlanHandoff,
116
+ onQuestions: this.onQuestions,
117
+ });
118
+ return /** @type {Promise<void>} */ (new Promise((resolve, reject) => {
119
+ this.child.once("error", (e) => {
120
+ const err = makeError("spawn-failed", `Failed to spawn agent (${command}): ${e.message}. Install Grok Build and run 'grok login'.`);
121
+ reject(err);
122
+ });
123
+ this.child.once("spawn", () => resolve());
124
+ }));
125
+ }
126
+
127
+ // Stashed for the unknown-model check and doctor deep, so neither needs a second handshake.
128
+ async initialize() {
129
+ const res = await this._setup("initialize", { protocolVersion: 1, clientInfo: { name: "grok-delegate-mcp", version: VERSION }, clientCapabilities: { _meta: { parameterizedModelPicker: true } } });
130
+ this.protocolVersion = res?.protocolVersion;
131
+ this.agentCapabilities = res?.agentCapabilities;
132
+ return res;
133
+ }
134
+ _captureSession(res) {
135
+ this.sessionModels = res?.models;
136
+ this.sessionModes = res?.modes;
137
+ this.configOptions = res?.configOptions;
138
+ // The folder Grok Build opened the session in, which on a load is the session's own.
139
+ this.sessionCwd = res?._meta?.["x.ai/sessionDetail"]?.cwd;
140
+ return res;
141
+ }
142
+ // yoloMode turns on Grok Build's always-approve; the session then reports yolo: true (measured).
143
+ async newSession(cwd) { return this._captureSession(await this._setup("session/new", { cwd, mcpServers: [], _meta: { yoloMode: true } })); }
144
+ async loadSession(sessionId, cwd) { return this._captureSession(await this._setup("session/load", { sessionId, cwd, mcpServers: [], _meta: { yoloMode: true } })); }
145
+ setModel(sessionId, modelId) { return this._setup("session/set_model", { sessionId, modelId }); }
146
+ setConfigOption(sessionId, configId, value) { return this._setup("session/set_config_option", { sessionId, configId, value: String(value) }); } // configId, not optionId; ACP wants a string value
147
+ setMode(sessionId, modeId) { return this._setup("session/set_mode", { sessionId, modeId }); }
148
+ // Every request before the task prompt. A reply that lands once setup ended, at a cancel or a
149
+ // failed delegation, is refused too, so no setup step runs on from it.
150
+ async _setup(method, params) {
151
+ if (this._phase !== "setup") throw wireClosed(this._phase);
152
+ const reply = await this.peer.request(method, params);
153
+ if (this._phase !== "setup") throw wireClosed(this._phase);
154
+ return reply;
155
+ }
156
+
157
+ /** @param {WireTransition} transition @returns {WirePhase | undefined} */
158
+ _advance(transition) {
159
+ const next = PHASES[this._phase][transition];
160
+ if (next) this._phase = next;
161
+ return next;
162
+ }
163
+
164
+ // The task prompt, and the only way into the running phase.
165
+ prompt(sessionId, blocks) {
166
+ if (!this._advance("prompt")) throw wireClosed(this._phase);
167
+ return this.peer.request("session/prompt", { sessionId, prompt: blocks });
168
+ }
169
+ // The delegation is decided: nothing sent from here on would reach a caller.
170
+ endTurn() { this._advance("end"); }
171
+ // Before the prompt nothing runs that the agent could finish, so the supervisor ends the
172
+ // delegation at once, whatever setup is awaiting.
173
+ cancel(sessionId) {
174
+ if (this._advance("cancel") === "cancelled-in-setup") this.emit("cancelled-in-setup");
175
+ this.peer.notify("session/cancel", { sessionId });
176
+ return Promise.resolve();
177
+ }
178
+
179
+ getTranscript(n) { return this.peer ? this.peer.formatLog(n) : ""; }
180
+
181
+ // One stop per client, which every caller joins.
182
+ stop() {
183
+ this._stopping ??= this._teardown();
184
+ return this._stopping;
185
+ }
186
+
187
+ async _teardown() {
188
+ const child = this._child;
189
+ if (!child) {
190
+ try { this.peer?.close(); } catch {}
191
+ return true;
192
+ }
193
+ const observed = await stopChild(child);
194
+ // On an exit, emitExit rejects in-flight RPCs with stderr; rejecting here first would lose it.
195
+ if (isChildAlive(child)) {
196
+ try { this.peer?.rejectAllPending(makeError("agent-exit", "agent process did not exit after stop")); } catch {}
197
+ }
198
+ try { this.peer?.close(); } catch {}
199
+ return observed;
200
+ }
201
+ }
@@ -0,0 +1,6 @@
1
+ // ACP v1 plan entry values, shared by delegate.js's sanitizer and the output shape so the two
2
+ // cannot drift. Grok Build sends its todo list as plan entries.
3
+
4
+ export const PLAN_PRIORITIES = /** @type {const} */ (["high", "medium", "low"]);
5
+
6
+ export const PLAN_STATUSES = /** @type {const} */ (["pending", "in_progress", "completed"]);
@@ -0,0 +1,17 @@
1
+ import path from "node:path";
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.
6
+
7
+ function relativize(abs, workspace) {
8
+ if (!workspace) return abs;
9
+ const r = path.relative(workspace, abs);
10
+ if (!r || r.startsWith("..") || path.isAbsolute(r)) return abs;
11
+ return r.split(path.sep).join("/");
12
+ }
13
+
14
+ export function normalizeAgentReportedFiles(paths, workspace) {
15
+ const abs = paths.map((p) => (workspace ? path.resolve(workspace, p) : path.resolve(p)));
16
+ return [...new Set(abs)].map((f) => relativize(f, workspace));
17
+ }