CLI
无头模式与脚本
无头模式
在脚本、机器人或其他机器友好型任务中使用无头模式。
bash
grok -p "Your prompt here"常用标志:
| Flag | 功能 |
|---|---|
-p, --single <PROMPT> | 发送单个提示 |
-m, --model <MODEL> | 选择模型 |
-s, --session-id <ID> | 创建或恢复一个命名的无头会话 |
-r, --resume <ID> | 恢复现有会话 |
-c, --continue | 继续当前目录中最新的会话 |
--cwd <PATH> | 设置工作目录 |
--output-format <FMT> | 选择 plain、json 或 streaming-json |
--always-approve | 自动批准工具执行 |
--no-alt-screen | 行内运行(无备用屏幕/全屏 TUI 占用) |
会话: 无头会话(通过 --session-id、--resume、--continue)存储在 ~/.grok/sessions 中。
在 xai-grok-shell 中抑制更新: 在脚本、CI 或其他自动化环境中使用无头模式(-p)或 ACP(grok agent stdio)时,传递 --no-auto-update(例如 grok --no-auto-update -p "...")以跳过后台更新检查。您也可以通过在 ~/.grok/config.toml 的 [cli] 部分下设置 auto_update = false 来永久禁用它们。
输出格式
plain:人类可读文本json:在末尾输出一个 JSON 对象streaming-json:换行分隔的 JSON 事件
bash
grok -p "List TODO comments" --output-format json
grok -p "Explain the architecture" --output-format streaming-json流式 JSON 在事件到达时发出增量事件。
ACP
当您需要 IDE 或工具集成而非终端会话时,使用 ACP。
bash
grok agent stdio这通过 stdin/stdout 上的 JSON-RPC 将 Grok 作为 ACP 代理运行。下面的示例假设 grok 已在本地通过身份验证,或已设置 XAI_API_KEY。session/prompt 返回完成元数据;助手文本本身作为 session/update 块到达。
javascript
import { spawn } from "node:child_process";
import readline from "node:readline";
import process from "node:process";
const proc = spawn("grok", ["agent", "stdio"], { stdio: ["pipe", "pipe", "pipe"] });
const rl = readline.createInterface({ input: proc.stdout });
const pending = new Map();
let nextId = 1;
let text = "";
proc.stderr.on("data", chunk => process.stderr.write(chunk));
rl.on("line", line => {
const message = JSON.parse(line);
if (message.method === "session/update") {
const update = message.params?.update;
if (update?.sessionUpdate === "agent_message_chunk" && update.content?.text) {
text += update.content.text;
}
return;
}
const pendingRequest = pending.get(message.id);
if (!pendingRequest) return;
pending.delete(message.id);
if (message.error) {
pendingRequest.reject(new Error(message.error.message ?? JSON.stringify(message.error)));
} else {
pendingRequest.resolve(message.result ?? {});
}
});
function request(method, params, timeoutMs = 30000) {
const id = nextId++;
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pending.delete(id);
reject(new Error(`${method} timed out`));
}, timeoutMs);
pending.set(id, {
resolve(result) {
clearTimeout(timer);
resolve(result);
},
reject(error) {
clearTimeout(timer);
reject(error);
},
});
proc.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
});
}
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
try {
const init = await request("initialize", {
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: true, writeTextFile: true },
terminal: true,
},
});
const authMethods = new Set((init.authMethods ?? []).map(method => method.id));
const methodId =
process.env.XAI_API_KEY && authMethods.has("xai.api_key")
? "xai.api_key"
: authMethods.has("cached_token")
? "cached_token"
: null;
if (!methodId) {
throw new Error("Run `grok login` first, or set XAI_API_KEY.");
}
await request("authenticate", { methodId, _meta: { headless: true } });
const { sessionId } = await request("session/new", {
cwd: process.cwd(),
mcpServers: [],
});
const prompt = await request("session/prompt", {
sessionId,
prompt: [{ type: "text", text: "Say hello in one short sentence." }],
});
let lastLength = -1;
let stableChecks = 0;
while (stableChecks < 2) {
await sleep(150);
if (text.length === lastLength) {
stableChecks += 1;
} else {
lastLength = text.length;
stableChecks = 0;
}
}
console.log(text.trim() || `No text returned (stopReason=${prompt.stopReason})`);
} finally {
rl.close();
proc.kill();
}