diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 8f040da..5c04a52 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -23,6 +23,7 @@ The MCP server has no third-party runtime dependencies. Each external agent owns - one active prompt turn at a time; - bounded public answer text; - recent plan and tool-status summaries; +- a monotonic progress revision, elapsed time, and bounded public-response preview; - lifecycle state and sanitized errors. ## ACP lifecycle @@ -33,10 +34,17 @@ The MCP server has no third-party runtime dependencies. Each external agent owns 4. Create a session with `session/new`, the target directory, no nested MCP servers, and additional orchestration rules. 5. Send the task with `session/prompt`. 6. Consume `session/update` events. Keep public message chunks, plan entries, and bounded tool metadata; discard thought chunks. -7. Keep the process alive for focused follow-ups until cancellation, close, or MCP shutdown. +7. Let `grok_status` long-poll a newer progress revision for up to 30 seconds so the orchestration skill can relay visible progress without tight polling. +8. Keep the process alive for focused follow-ups until cancellation, close, or MCP shutdown. The child process receives only a small system environment allowlist, supported Grok authentication variables, and variables explicitly named by the operator. Failed or timed-out sessions terminate their Grok process while retaining a bounded diagnostic summary. +## Interactive handoff mode + +`grok_handoff_interactive` is intentionally outside the managed ACP lifecycle. On macOS it writes the sanitized handoff prompt to a mode-0600 temporary file, opens a new Terminal window, reads and removes that file, and starts the official interactive Grok TUI. Read-only handoffs use the read-only sandbox. Writing handoffs require a Git repository root and ask Grok to create an isolated worktree. + +The MCP call returns after Terminal opens. The bridge does not retain the TUI process, session ID, transcript, or completion state. The user owns interaction and lifecycle from that point and must return to Codex explicitly for independent verification. + ## Read-only mode `grok_spawn_readonly` starts Grok with `--sandbox read-only`. The bridge accepts any readable absolute directory. Grok's sandbox is the enforcement boundary; the prompt also states that the session must not modify project files. diff --git a/CHANGELOG.md b/CHANGELOG.md index fb6bc29..d1cff5a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,30 @@ All notable changes to this project will be documented here. +## 0.3.0 - 2026-07-18 + +### Added + +- Added a macOS-only `grok_handoff_interactive` tool that opens the official Grok TUI in a new Terminal window with a Codex-authored task prompt. +- Added read-only and isolated-worktree access modes for user-supervised interactive handoffs. + +### Security + +- Interactive implementation handoffs cannot write directly to the primary checkout and do not authorize commits, pushes, publication, or changes outside the Grok-created worktree. +- Initial handoff prompts use mode-0600 temporary files and are removed by the launched Terminal command before Grok starts. + +## 0.2.0 - 2026-07-18 + +### Added + +- Added monotonic progress revisions, elapsed time, timestamped tool events, and a bounded public-response preview to Grok agent status. +- Added optional long-polling to `grok_status` through `after_revision` and `wait_seconds`. +- Made the orchestration skill relay material Grok progress and provide a user-visible heartbeat at least once per minute. + +### Security + +- Kept visible progress limited to public answer chunks, plan entries, tool metadata, and lifecycle state; private chain-of-thought remains discarded. + ## 0.1.1 - 2026-07-17 ### Fixed diff --git a/README.en.md b/README.en.md index 88833f4..3468026 100644 --- a/README.en.md +++ b/README.en.md @@ -138,13 +138,14 @@ Important boundaries: Read [SECURITY.md](SECURITY.md) before using the plugin on private code. -## Eight management tools +## Nine management tools | Tool | Purpose | Filesystem mode | | --- | --- | --- | | `grok_spawn_readonly` | Start an independent investigation, review, or plan analysis | Grok `read-only` sandbox | | `grok_spawn_worker` | Implement inside an approved linked worktree | Grok `workspace` sandbox + bridge guard | -| `grok_status` | Read lifecycle, plan, and recent tool activity | Read-only | +| `grok_handoff_interactive` | Open an interactive Grok TUI in a new macOS Terminal window and stop Codex supervision after prompt handoff | Read-only or a Grok-created isolated worktree | +| `grok_status` | Read lifecycle, elapsed time, plan, recent tool activity, and a public-response preview; optionally wait for a newer revision | Read-only | | `grok_result` | Read the public answer, optionally waiting briefly | Read-only | | `grok_send` | Send a focused follow-up; writing sessions require renewed scope confirmation | Inherits session mode | | `grok_cancel` | Cancel the active turn | Control operation | @@ -153,6 +154,16 @@ Read [SECURITY.md](SECURITY.md) before using the plugin on private code. The bridge permits at most three open Grok processes. The skill recommends one by default and two only for genuinely independent work. +### Interactive handoff mode + +When the user explicitly asks Codex to hand a task fully to Grok and interact with it directly, Codex turns the goal, scope, known context, completion criteria, and restrictions into a self-contained prompt. `grok_handoff_interactive` then opens a new macOS Terminal window. The Grok TUI is user-supervised from that point onward: Codex does not poll it, close it automatically, or pretend to know its current state. + +Read-only work uses Grok's `read-only` sandbox. Implementation work uses `--worktree` to create an isolated worktree and accepts file edits there, while commits, pushes, publication, and other external actions still require explicit authorization in the Grok window. The user can return to Codex afterward for independent diff, test, and claim verification. + +### How visible progress works + +While Grok is running, the skill asks Codex to use `grok_status` for incremental waits of up to 30 seconds and relay material plan steps, tool status, elapsed time, or public-response previews as concise progress messages in the Codex task. It also emits a heartbeat within 60 seconds when Grok exposes no new detail. The bridge never forwards private chain-of-thought, so this is verifiable work status rather than hidden reasoning text. + ## Requirements and compatibility - macOS, Linux, or WSL; diff --git a/README.md b/README.md index e78a2b4..0168a27 100644 --- a/README.md +++ b/README.md @@ -137,13 +137,14 @@ flowchart LR 在私有代码上使用前,请阅读 [SECURITY.md](SECURITY.md)。 -## 八个管理工具 +## 九个管理工具 | 工具 | 用途 | 文件系统模式 | | --- | --- | --- | | `grok_spawn_readonly` | 启动独立调查、审查或方案分析 | Grok `read-only` 沙箱 | | `grok_spawn_worker` | 在获批的 linked worktree 中执行实现任务 | Grok `workspace` 沙箱 + Bridge 检查 | -| `grok_status` | 查看生命周期、计划和最近工具活动 | 只读 | +| `grok_handoff_interactive` | 在新的 macOS Terminal 窗口打开可交互 Grok TUI,Codex 完成 prompt 移交后不再监督 | 只读或 Grok 创建的隔离 worktree | +| `grok_status` | 查看生命周期、运行时长、计划、最近工具活动和公开回答片段;支持按进度版本等待增量 | 只读 | | `grok_result` | 获取公开回答,可短暂等待当前轮次完成 | 只读 | | `grok_send` | 在同一会话中聚焦追问;写入会话需重新确认范围 | 继承会话模式 | | `grok_cancel` | 取消当前轮次 | 控制操作 | @@ -152,6 +153,16 @@ flowchart LR Bridge 最多同时保留三个 Grok 进程;Skill 默认建议只使用一个,只有真正独立的任务才并行使用两个。 +### 交互式移交模式 + +当你明确要求“把任务全权交给 Grok,并让我在窗口里直接沟通”时,Codex 会先把目标、范围、已有上下文、完成标准和禁止事项整理成完整 prompt,再调用 `grok_handoff_interactive` 打开新的 macOS Terminal 窗口。之后 Grok TUI 由你直接监督和追问,Codex 不轮询、不自动收尾,也不会假装知道窗口里的最新状态。 + +只读任务使用 Grok `read-only` 沙箱;实现任务默认使用 `--worktree` 创建隔离工作区,并自动接受工作区内的文件编辑,但提交、推送、发布和其他外部操作仍需你在 Grok 窗口里另行授权。完成后回到 Codex,Codex 再检查 worktree diff、测试和关键结论。 + +### 可见进度如何工作 + +Grok 运行期间,Skill 会让 Codex 用 `grok_status` 做最长 30 秒的增量等待,并把有实质变化的计划步骤、工具状态、运行时长或公开回答片段转成 Codex 任务里的简短进度消息;即使没有新细节,也会在 60 秒内给出一次心跳。Bridge 不转发私有思维链,因此这里展示的是可核验的工作状态,不是模型的隐藏推理文本。 + ## 要求与兼容性 - macOS、Linux 或 WSL; diff --git a/SECURITY.md b/SECURITY.md index 698fdf5..0dd8be7 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -46,3 +46,9 @@ The bridge asks the official Grok CLI to use its advertised `cached_token` metho ## Dependency and process model The MCP server uses only Node.js standard-library modules. Grok is launched with argument arrays rather than shell command interpolation. All child processes are terminated when the bridge shuts down, with a forced-kill fallback. + +## Interactive handoff boundary + +Interactive handoff is macOS-only and opens the official Grok TUI in a separate Terminal window. It is not an ACP-managed agent: Codex cannot observe its later prompts, approvals, filesystem activity, or completion state. Read-only handoffs use Grok's read-only sandbox. Writing handoffs start with `--worktree` and must originate at a Git repository root; the handoff prompt forbids commits, pushes, publication, and changes to other worktrees without fresh user authorization in that Terminal window. + +The initial prompt is passed through a mode-0600 temporary file that the Terminal command removes before starting Grok. The prompt is sanitized but still leaves the machine for xAI under the user's Grok plan and policies. Do not use interactive handoff for secrets or unrelated personal data. diff --git a/package.json b/package.json index 16803b1..4a29955 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "grok-subagent-codex-marketplace", - "version": "0.1.1", + "version": "0.3.0", "private": true, "description": "A Codex plugin that delegates bounded work to the official Grok Build CLI over ACP.", "scripts": { diff --git a/plugins/grok-subagent/.codex-plugin/plugin.json b/plugins/grok-subagent/.codex-plugin/plugin.json index 70a9fa6..96d973a 100644 --- a/plugins/grok-subagent/.codex-plugin/plugin.json +++ b/plugins/grok-subagent/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "grok-subagent", - "version": "0.1.1", + "version": "0.3.0", "description": "Run authenticated Grok Build agents as controlled external subagents from Codex.", "author": { "name": "Walvez" diff --git a/plugins/grok-subagent/mcp-server/server.mjs b/plugins/grok-subagent/mcp-server/server.mjs index 4401757..94a7502 100644 --- a/plugins/grok-subagent/mcp-server/server.mjs +++ b/plugins/grok-subagent/mcp-server/server.mjs @@ -2,13 +2,13 @@ import { spawn, spawnSync } from "node:child_process"; import { randomUUID } from "node:crypto"; -import { accessSync, constants, lstatSync, realpathSync, statSync } from "node:fs"; -import { homedir } from "node:os"; +import { accessSync, constants, lstatSync, mkdtempSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { homedir, tmpdir } from "node:os"; import { isAbsolute, join, resolve } from "node:path"; import { createInterface } from "node:readline"; import { fileURLToPath } from "node:url"; -const VERSION = "0.1.1"; +const VERSION = "0.3.0"; const MAX_AGENTS = 3; const MAX_RETAINED_FAILED_AGENTS = 3; const MAX_TEXT = 120_000; @@ -62,10 +62,37 @@ const TOOL_DEFINITIONS = [ }, annotations: { title: "Start isolated Grok worker", readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true } }, + { + name: "grok_handoff_interactive", + description: "Open an independent interactive Grok Build TUI in a new macOS Terminal window. Codex hands off the prompt and does not supervise the session.", + inputSchema: { + type: "object", + properties: { + task: { type: "string", description: "Complete task brief that Codex hands to the interactive Grok session." }, + cwd: { type: "string", description: "Absolute project directory. Worktree mode requires the Git repository root." }, + access_mode: { type: "string", enum: ["read_only", "isolated_worktree"], description: "Read-only inspection or edits in a Grok-created linked worktree." }, + confirm_interactive_handoff: { type: "boolean", description: "Must be true after the user explicitly asks to interact directly with Grok in a separate window." }, + role: { type: "string", description: "Optional specialist role included in the handoff prompt." }, + model: { type: "string", description: "Optional Grok Build model ID." } + }, + required: ["task", "cwd", "access_mode", "confirm_interactive_handoff"], + additionalProperties: false + }, + annotations: { title: "Hand off to interactive Grok", readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true } + }, { name: "grok_status", - description: "Inspect one Grok agent's lifecycle, recent plan, and bounded tool activity without waiting.", - inputSchema: objectWithAgentId(), + description: "Inspect one Grok agent's lifecycle and visible progress. Optionally wait for a newer progress revision.", + inputSchema: { + type: "object", + properties: { + agent_id: { type: "string" }, + after_revision: { type: "integer", minimum: 0, description: "Return when progress is newer than this revision." }, + wait_seconds: { type: "integer", minimum: 0, maximum: 30, default: 0 } + }, + required: ["agent_id"], + additionalProperties: false + }, annotations: readOnlyAnnotations("Inspect Grok agent") }, { @@ -167,6 +194,15 @@ function assertLinkedWorktree(input) { return path; } +function assertGitRepositoryRoot(input) { + const path = absoluteDirectory(input, "cwd"); + const probe = spawnSync("git", ["-C", path, "rev-parse", "--show-toplevel"], { encoding: "utf8", timeout: 5_000, env: buildChildEnv() }); + if (probe.status !== 0) throw new Error("Interactive worktree handoff requires a Git repository root."); + const gitRoot = realpathSync(resolve(probe.stdout.trim())); + if (gitRoot !== path) throw new Error("cwd must be the root of the Git repository for interactive worktree handoff."); + return path; +} + function buildChildEnv(source = process.env) { const env = {}; for (const key of CHILD_ENV_KEYS) { @@ -197,6 +233,80 @@ function findGrok() { throw new Error("Grok CLI was not found. Install and authenticate Grok Build first."); } +function shellQuote(value) { + return `'${String(value).replaceAll("'", `'"'"'`)}'`; +} + +function appleScriptString(value) { + return String(value).replaceAll("\\", "\\\\").replaceAll('"', '\\"'); +} + +function interactiveWorktreeName() { + const stamp = new Date().toISOString().replace(/[-:TZ.]/g, "").slice(0, 14); + return `grok-handoff-${stamp}-${randomUUID().slice(0, 6)}`; +} + +function buildInteractiveCommand({ binary, cwd, promptFile, promptDir, accessMode, model, worktreeName }) { + const args = [shellQuote(binary), "--no-subagents"]; + if (model) args.push("--model", shellQuote(model)); + if (accessMode === "read_only") { + args.push("--sandbox", "read-only", "--permission-mode", "default"); + } else { + args.push(`--worktree=${shellQuote(worktreeName)}`, "--sandbox", "workspace", "--permission-mode", "acceptEdits"); + } + args.push('--', '"$grok_handoff_prompt"'); + return [ + `cd ${shellQuote(cwd)}`, + `grok_handoff_prompt="$(cat -- ${shellQuote(promptFile)})"`, + `{ rm -f -- ${shellQuote(promptFile)}; rmdir -- ${shellQuote(promptDir)} 2>/dev/null || true; exec ${args.join(" ")}; }` + ].join(" && "); +} + +function launchInteractiveHandoff(args) { + if (process.platform !== "darwin") throw new Error("Interactive Terminal handoff is currently supported only on macOS."); + if (args.confirm_interactive_handoff !== true) { + throw new Error("confirm_interactive_handoff must be true after the user explicitly requests a separate interactive Grok window."); + } + if (typeof args.task !== "string" || !args.task.trim()) throw new Error("task is required."); + if (args.task.length > MAX_TEXT) throw new Error(`task must be at most ${MAX_TEXT} characters.`); + if (!["read_only", "isolated_worktree"].includes(args.access_mode)) throw new Error("access_mode must be read_only or isolated_worktree."); + const cwd = args.access_mode === "isolated_worktree" ? assertGitRepositoryRoot(args.cwd) : absoluteDirectory(args.cwd, "cwd"); + const binary = findGrok(); + const worktreeName = args.access_mode === "isolated_worktree" ? interactiveWorktreeName() : null; + const rules = [ + `Codex has handed this task to you as an interactive ${cleanText(args.role || "Grok Build specialist")}.`, + "Work directly with the user in this Terminal window. Ask the user when a material decision or additional authority is required.", + "Do not spawn subagents.", + args.access_mode === "read_only" + ? "This is a read-only session. Do not modify project files." + : "Work only in the isolated worktree created for this session. Do not commit, push, merge, publish, or alter other worktrees unless the user explicitly authorizes that action in this window.", + "When finished, summarize the changes, tests, remaining risks, and the worktree path so the user can return to Codex for independent verification.", + "", + "Task from Codex:", + cleanText(args.task) + ].join("\n"); + const promptDir = mkdtempSync(join(tmpdir(), "grok-handoff-")); + const promptFile = join(promptDir, "prompt.txt"); + writeFileSync(promptFile, rules, { encoding: "utf8", mode: 0o600 }); + const command = buildInteractiveCommand({ binary, cwd, promptFile, promptDir, accessMode: args.access_mode, model: args.model, worktreeName }); + const script = `tell application "Terminal"\nactivate\ndo script "${appleScriptString(command)}"\nend tell`; + const launched = spawnSync("osascript", ["-e", script], { encoding: "utf8", timeout: 10_000, env: buildChildEnv() }); + if (launched.status !== 0) { + rmSync(promptDir, { recursive: true, force: true }); + throw new Error(`Could not open the interactive Grok Terminal window: ${cleanText(launched.stderr || launched.stdout || "unknown error")}`); + } + const cleanupTimer = setTimeout(() => rmSync(promptDir, { recursive: true, force: true }), 60_000); + cleanupTimer.unref(); + return { + launched: true, + supervision: "user", + access_mode: args.access_mode, + cwd, + worktree_name: worktreeName, + note: "This Terminal session is independent. Return to Codex when you want its result or diff verified." + }; +} + class GrokAgent { constructor({ cwd, mode, role, model, timeoutSeconds }) { this.id = randomUUID(); @@ -214,6 +324,7 @@ class GrokAgent { this.error = null; this.startedAt = new Date().toISOString(); this.updatedAt = this.startedAt; + this.revision = 0; this.requestId = 0; this.pending = new Map(); this.turnPromise = null; @@ -301,16 +412,20 @@ class GrokAgent { consumeUpdate(update) { if (!update || typeof update !== "object") return; - this.touch(); if (update.sessionUpdate === "agent_message_chunk") { + this.touch(); this.text = appendBounded(this.text, update.content?.text || ""); } else if (update.sessionUpdate === "plan") { + this.touch(); this.plan = sanitizePlan(update); } else if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") { + this.touch(); this.toolEvents.push({ type: update.sessionUpdate, title: cleanText(update.title || update.kind || "tool"), - status: cleanText(update.status || "unknown") + status: cleanText(update.status || "unknown"), + at: this.updatedAt, + revision: this.revision }); this.toolEvents = this.toolEvents.slice(-20); } @@ -409,7 +524,10 @@ class GrokAgent { this.terminateProcess(); } - touch() { this.updatedAt = new Date().toISOString(); } + touch() { + this.updatedAt = new Date().toISOString(); + this.revision += 1; + } summary(includeText = false) { const result = { @@ -421,12 +539,17 @@ class GrokAgent { cwd: this.cwd, started_at: this.startedAt, updated_at: this.updatedAt, + elapsed_seconds: Math.max(0, Math.trunc((Date.now() - Date.parse(this.startedAt)) / 1000)), + revision: this.revision, plan: this.plan, recent_tools: this.toolEvents, error: this.error }; if (includeText) result.response = this.text; - else result.response_chars = this.text.length; + else { + result.response_chars = this.text.length; + result.public_response_preview = this.text.slice(-1000); + } return result; } } @@ -487,11 +610,27 @@ async function waitForAgent(agent, seconds) { } } +async function waitForRevision(agent, afterRevision, seconds) { + if (!Number.isInteger(afterRevision) || afterRevision < 0) return; + const deadline = Date.now() + clamp(seconds, 0, 30, 0) * 1000; + while (agent.revision <= afterRevision && ["running", "cancelling"].includes(agent.status) && Date.now() < deadline) { + await new Promise(resolvePromise => setTimeout(resolvePromise, 200)); + } +} + async function callTool(name, args = {}) { switch (name) { case "grok_spawn_readonly": return spawnAgent(args, "readonly"); case "grok_spawn_worker": return spawnAgent(args, "worker"); - case "grok_status": return getAgent(args.agent_id).summary(false); + case "grok_handoff_interactive": return launchInteractiveHandoff(args); + case "grok_status": { + const agent = getAgent(args.agent_id); + await waitForRevision(agent, args.after_revision, args.wait_seconds); + return { + ...agent.summary(false), + changed: !Number.isInteger(args.after_revision) || agent.revision > args.after_revision + }; + } case "grok_result": { const agent = getAgent(args.agent_id); await waitForAgent(agent, args.wait_seconds); @@ -576,12 +715,16 @@ export { TOOL_DEFINITIONS, VERSION, absoluteDirectory, + appleScriptString, assertLinkedWorktree, + assertGitRepositoryRoot, + buildInteractiveCommand, buildChildEnv, cleanText, negotiateProtocolVersion, shutdown, - startMcpServer + startMcpServer, + waitForRevision }; let isMainModule = false; diff --git a/plugins/grok-subagent/skills/grok-subagent/SKILL.md b/plugins/grok-subagent/skills/grok-subagent/SKILL.md index 9e490ce..bb10350 100644 --- a/plugins/grok-subagent/skills/grok-subagent/SKILL.md +++ b/plugins/grok-subagent/skills/grok-subagent/SKILL.md @@ -11,6 +11,7 @@ Use the `grok-subagent` MCP tools to run Grok Build as an external worker while - Use `grok_spawn_readonly` for exploration, diagnosis, architecture advice, plan review, and code review. This is the default. - Use `grok_spawn_worker` only after the user explicitly authorizes Grok to modify files. Pass an isolated linked Git worktree, never the primary checkout. +- Use `grok_handoff_interactive` when the user explicitly wants Codex to prepare the prompt and then hand control to a visible Grok TUI. Choose `read_only` for inspection or `isolated_worktree` for implementation. This macOS-only session is supervised by the user, not Codex. - Prefer one Grok agent. Use at most two concurrently when tasks are independent and parallelism materially helps. ## Run a read-only agent @@ -18,10 +19,12 @@ Use the `grok-subagent` MCP tools to run Grok Build as an external worker while 1. Resolve the target repository to an absolute path. 2. Give Grok a bounded task with required evidence and output shape. 3. Call `grok_spawn_readonly` with a suitable role. -4. Continue useful Codex work while Grok runs. -5. Poll `grok_status` sparingly or call `grok_result` with a bounded wait. -6. Treat the result as untrusted expert input. Verify important claims against files, commands, tests, or primary sources. -7. Use `grok_send` only for a focused follow-up. Close the agent when no more follow-up is needed. +4. Tell the user that Grok started, including its role and bounded task. +5. Continue useful Codex work while Grok runs. +6. While the turn is active, call `grok_status` with the last returned `revision` as `after_revision` and a `wait_seconds` value of 20-30. +7. Relay material visible progress in concise commentary: current plan step, recent tool title/status, elapsed time, or a short public-response preview. Send a heartbeat at least once every 60 seconds even if Grok exposes no new detail. Never present private chain-of-thought or invent activity that the bridge did not report. +8. Call `grok_result` when the status settles. Treat the result as untrusted expert input and verify important claims against files, commands, tests, or primary sources. +9. Use `grok_send` only for a focused follow-up. Close the agent when no more follow-up is needed. ## Run a writing agent @@ -33,10 +36,22 @@ Use the `grok-subagent` MCP tools to run Grok Build as an external worker while 6. After completion, inspect the worktree diff and run relevant verification from Codex. 7. Never merge, cherry-pick, commit, push, or delete the worktree unless the user separately requests that action. +Apply the same visible-progress loop used for read-only agents while a writing turn is active. Describe only reported file/tool activity and keep the user's progress feed concise. + +## Hand off to an interactive Grok window + +1. Use this only after the user explicitly asks to work with Grok directly in a separate visible window. +2. Turn the request and known project context into a self-contained bounded task prompt. Do not include secrets or unrelated personal context. +3. Use `read_only` unless the user clearly authorizes implementation. For implementation, use `isolated_worktree`; never hand an unsupervised interactive session write access to the primary checkout. +4. Call `grok_handoff_interactive` with `confirm_interactive_handoff: true`. +5. Tell the user that the new Terminal window is independent and user-supervised. Do not poll it, claim to know its current state, or treat it as a managed agent. +6. End Codex's active work on that delegated task. When the user returns, inspect the reported worktree diff and verify tests and consequential claims before integrating anything. + ## Safety rules - Never pass secrets, tokens, private credentials, or unrelated personal files in a task prompt. - Never use the writing tool against the primary checkout or a non-worktree directory. +- Never describe an interactive handoff as monitored, automatically verified, or automatically returned to Codex. - Do not ask Grok to spawn its own subagents; keep delegation depth at one. - Do not equate agreement between Codex and Grok with verification. - Cancel a runaway task and close abandoned agents. diff --git a/plugins/grok-subagent/tests/mcp-e2e.mjs b/plugins/grok-subagent/tests/mcp-e2e.mjs index 5f2d85c..90028d9 100644 --- a/plugins/grok-subagent/tests/mcp-e2e.mjs +++ b/plugins/grok-subagent/tests/mcp-e2e.mjs @@ -32,6 +32,17 @@ try { task: `This is a read-only integration test. Inspect only the current directory. Reply with exactly two lines: GROK_SUBAGENT_OK and cwd=${expectedCwd}. Do not modify files and do not use subagents.` }); agentId = started.agent_id; + assert(Number.isInteger(started.revision)); + + const progress = await client.call("grok_status", { + agent_id: agentId, + after_revision: started.revision, + wait_seconds: 30 + }); + assert(Number.isInteger(progress.revision)); + assert(progress.revision >= started.revision); + assert.equal(typeof progress.elapsed_seconds, "number"); + assert.equal(typeof progress.public_response_preview, "string"); let result; for (let attempt = 0; attempt < 8; attempt += 1) { diff --git a/plugins/grok-subagent/tests/mcp-smoke.mjs b/plugins/grok-subagent/tests/mcp-smoke.mjs index e1cf3d1..cff8d3c 100644 --- a/plugins/grok-subagent/tests/mcp-smoke.mjs +++ b/plugins/grok-subagent/tests/mcp-smoke.mjs @@ -11,12 +11,13 @@ try { assert.equal(initialized.serverInfo.name, "grok-subagent"); const listed = await client.request("tools/list"); const names = listed.tools.map(tool => tool.name); - for (const name of ["grok_spawn_readonly", "grok_spawn_worker", "grok_status", "grok_result", "grok_send", "grok_cancel", "grok_close", "grok_list"]) { + for (const name of ["grok_spawn_readonly", "grok_spawn_worker", "grok_handoff_interactive", "grok_status", "grok_result", "grok_send", "grok_cancel", "grok_close", "grok_list"]) { assert(names.includes(name), `missing ${name}`); } assert.equal(listed.tools.find(tool => tool.name === "grok_spawn_readonly").annotations.readOnlyHint, false); assert.equal(listed.tools.find(tool => tool.name === "grok_spawn_readonly").annotations.destructiveHint, false); assert.equal(listed.tools.find(tool => tool.name === "grok_spawn_worker").annotations.destructiveHint, true); + assert.equal(listed.tools.find(tool => tool.name === "grok_handoff_interactive").annotations.destructiveHint, true); assert.equal(listed.tools.find(tool => tool.name === "grok_send").annotations.destructiveHint, true); console.log(`MCP smoke passed (${names.length} tools).`); } finally { diff --git a/tests/server-core.test.mjs b/tests/server-core.test.mjs index 9140301..b8ac482 100644 --- a/tests/server-core.test.mjs +++ b/tests/server-core.test.mjs @@ -8,10 +8,13 @@ import test from "node:test"; import { GrokAgent, TOOL_DEFINITIONS, + appleScriptString, assertLinkedWorktree, + buildInteractiveCommand, buildChildEnv, cleanText, - negotiateProtocolVersion + negotiateProtocolVersion, + waitForRevision } from "../plugins/grok-subagent/mcp-server/server.mjs"; test("child environment excludes unrelated secrets and supports explicit passthrough", () => { @@ -61,8 +64,57 @@ test("tool annotations reflect process and writing side effects", () => { assert.equal(byName.grok_spawn_readonly.annotations.readOnlyHint, false); assert.equal(byName.grok_spawn_readonly.annotations.destructiveHint, false); assert.equal(byName.grok_send.annotations.destructiveHint, true); + assert.equal(byName.grok_handoff_interactive.annotations.destructiveHint, true); assert.equal(byName.grok_close.annotations.idempotentHint, false); assert(byName.grok_send.inputSchema.properties.confirm_write_scope); + assert(byName.grok_status.inputSchema.properties.after_revision); + assert.equal(byName.grok_status.inputSchema.properties.wait_seconds.maximum, 30); +}); + +test("interactive handoff command quotes paths and keeps the prompt out of the command", () => { + const command = buildInteractiveCommand({ + binary: "/tmp/Grok Build/grok", + cwd: "/tmp/project's files", + promptFile: "/tmp/handoff prompt/prompt.txt", + promptDir: "/tmp/handoff prompt", + accessMode: "isolated_worktree", + model: "grok-test", + worktreeName: "grok-handoff-test" + }); + assert(command.includes("cd '/tmp/project'\"'\"'s files'")); + assert(command.includes("--worktree='grok-handoff-test'")); + assert(command.includes("--permission-mode acceptEdits")); + assert(command.includes('"$grok_handoff_prompt"')); + assert(!command.includes("secret task body")); + assert.equal(appleScriptString('say "hello" \\ path'), 'say \\"hello\\" \\\\ path'); +}); + +test("visible progress has revisions, bounded previews, and waitable updates", async () => { + const agent = new GrokAgent({ + cwd: tmpdir(), + mode: "readonly", + role: "test", + model: "test-model", + timeoutSeconds: 60 + }); + agent.status = "running"; + agent.consumeUpdate({ sessionUpdate: "agent_message_chunk", content: { text: "Public progress" } }); + const first = agent.summary(false); + assert(first.revision > 0); + assert.equal(first.public_response_preview, "Public progress"); + + agent.consumeUpdate({ sessionUpdate: "agent_thought_chunk", content: { text: "private" } }); + assert.equal(agent.revision, first.revision); + assert(!agent.summary(false).public_response_preview.includes("private")); + + const waiting = waitForRevision(agent, first.revision, 1); + setTimeout(() => agent.consumeUpdate({ sessionUpdate: "tool_call", title: "Inspect files", status: "in_progress" }), 10); + await waiting; + const second = agent.summary(false); + assert(second.revision > first.revision); + assert.equal(second.recent_tools.at(-1).title, "Inspect files"); + assert.equal(second.recent_tools.at(-1).revision, second.revision); + assert(second.recent_tools.at(-1).at); }); test("linked worktree guard accepts a symlinked root and rejects a primary checkout", () => {