fix(grok): show Grok plan-mode plans and handle plan approvals over ACP #4233
ClosedEmmanuek5(GitHub profile, opens in a new tab)wants to merge 5 commits into
main fromrefs/pull/4233/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
- @@ -663,3 +705,18 @@663705 ),664706 { discard: true },665707 );708+ yield* Effect.forEach(709+ ["x.ai/exit_plan_mode", "_x.ai/exit_plan_mode"] as const,710+ (method) =>711+ acp.handleExtRequest(method, XAiExitPlanModeRequest, (params) =>712+ mapAcpCallbackFailure(713+ Effect.gen(function* () {714+ yield* logNative(input.threadId, method, params);715+ const ctx = sessions.get(input.threadId);716+ const turnId = resolveSessionCallbackTurnId(sessions, input.threadId);717+ // A plan was already captured and the user came back in a718+ // non-plan turn: that is the implementation turn, so let719+ // Grok exit plan mode and build.720+ if (ctx?.planCaptured === true && ctx.activeInteractionMode !== "plan") {721+ ctx.planCaptured = false;722+ return makeXAiExitPlanModeApprovedResponse();
- @@ -198,0 +219,21 @@219+ XAiWrappedExitPlanModeParams,220+]);221+222+type XAiExitPlanModeRequestParams = typeof XAiExitPlanModeParams.Type;223+export type XAiExitPlanModeRequest = typeof XAiExitPlanModeRequest.Type;224+225+function unwrapExitPlanModeParams(params: XAiExitPlanModeRequest): XAiExitPlanModeRequestParams {226+ return "params" in params ? params.params : params;227+}228+229+export function extractXAiExitPlanModePlan(params: XAiExitPlanModeRequest): string | undefined {230+ return trimmed(unwrapExitPlanModeParams(params).planContent ?? undefined);231+}232+233+/**234+ * Grok interprets the response outcome as: `approved` exits plan mode and235+ * tells the agent to implement the plan; `abandoned` keeps plan mode active236+ * and tells the agent the user does not want to exit; any other outcome is237+ * treated as "revise" — the tool completes with "The user wants to revise the238+ * plan." plus the feedback text, and plan mode stays active.239+ */@@ -36,5 +40,19 @@3640 });37413842 const decodeXAiAskUserQuestionRequest = Schema.decodeUnknownSync(XAiAskUserQuestionRequest);43+const decodeXAiExitPlanModeRequest = Schema.decodeUnknownSync(XAiExitPlanModeRequest);39444045 describe("XAiAcpExtension", () => {46+ it("extracts the plan from the real xAI exit_plan_mode payload shape", () => {47+ const decoded = decodeXAiExitPlanModeRequest({48+ sessionId: "session-1",49+ toolCallId: "tool-call-1",50+ planContent: "# Plan\n\n- Step one\n",51+ });52+53+ expect(extractXAiExitPlanModePlan(decoded)).toEqual("# Plan\n\n- Step one");54+ });55+56+ it("extracts the plan from wrapped _x.ai exit_plan_mode payloads", () => {57+ const decoded = decodeXAiExitPlanModeRequest({58+ method: "x.ai/exit_plan_mode",@@ -665,0 +718,21 @@718+ // non-plan turn: that is the implementation turn, so let719+ // Grok exit plan mode and build.720+ if (ctx?.planCaptured === true && ctx.activeInteractionMode !== "plan") {721+ ctx.planCaptured = false;722+ return makeXAiExitPlanModeApprovedResponse();723+ }724+ let planMarkdown = extractXAiExitPlanModePlan(params);725+ // Grok can batch the plan-file write and exit_plan_mode726+ // in one model response; its own plan read then races727+ // the write and planContent arrives empty. Recover by728+ // reading the plan file the CLI reported on entry.729+ if (planMarkdown === undefined && ctx !== undefined) {730+ for (731+ let attempt = 0;732+ attempt < 20 && planMarkdown === undefined;733+ attempt += 1734+ ) {735+ // Re-read per attempt: the enter_plan_mode update that736+ // carries the path is processed on a concurrent fiber.737+ const planFilePath = ctx.planFilePath;738+ if (planFilePath) {
- apps/server/src/provider/Layers/GrokAdapter.ts line 752OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -665,0 +732,21 @@732+ attempt < 20 && planMarkdown === undefined;733+ attempt += 1734+ ) {735+ // Re-read per attempt: the enter_plan_mode update that736+ // carries the path is processed on a concurrent fiber.737+ const planFilePath = ctx.planFilePath;738+ if (planFilePath) {739+ const contents = yield* fileSystem740+ .readFileString(planFilePath)741+ .pipe(Effect.orElseSucceed(() => ""));742+ const trimmedContents = contents.trim();743+ if (trimmedContents.length > 0) {744+ planMarkdown = trimmedContents;745+ break;746+ }747+ }748+ yield* Effect.sleep("100 millis");749+ }750+ }751+ if (ctx) {752+ ctx.planCaptured = true;apps/server/src/provider/Layers/GrokAdapter.ts line 820Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -665,0 +729,21 @@729+ if (planMarkdown === undefined && ctx !== undefined) {730+ for (731+ let attempt = 0;732+ attempt < 20 && planMarkdown === undefined;733+ attempt += 1734+ ) {735+ // Re-read per attempt: the enter_plan_mode update that736+ // carries the path is processed on a concurrent fiber.737+ const planFilePath = ctx.planFilePath;738+ if (planFilePath) {739+ const contents = yield* fileSystem740+ .readFileString(planFilePath)741+ .pipe(Effect.orElseSucceed(() => ""));742+ const trimmedContents = contents.trim();743+ if (trimmedContents.length > 0) {744+ planMarkdown = trimmedContents;745+ break;746+ }747+ }748+ yield* Effect.sleep("100 millis");749+ }apps/server/src/provider/Layers/GrokAdapter.ts line 820Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -665,0 +729,21 @@729+ if (planMarkdown === undefined && ctx !== undefined) {730+ for (731+ let attempt = 0;732+ attempt < 20 && planMarkdown === undefined;733+ attempt += 1734+ ) {735+ // Re-read per attempt: the enter_plan_mode update that736+ // carries the path is processed on a concurrent fiber.737+ const planFilePath = ctx.planFilePath;738+ if (planFilePath) {739+ const contents = yield* fileSystem740+ .readFileString(planFilePath)741+ .pipe(Effect.orElseSucceed(() => ""));742+ const trimmedContents = contents.trim();743+ if (trimmedContents.length > 0) {744+ planMarkdown = trimmedContents;745+ break;746+ }747+ }748+ yield* Effect.sleep("100 millis");749+ }
- apps/server/src/provider/Layers/GrokAdapter.ts line 208OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -162,0 +188,21 @@188+ * exit_plan_mode request arrives with an empty planContent — the adapter then189+ * reads the plan file directly using this path.190+ */191+export function extractGrokPlanFilePath(rawPayload: unknown): string | undefined {192+ if (!isRecord(rawPayload)) return undefined;193+ const params = isRecord(rawPayload.params) ? rawPayload.params : rawPayload;194+ const update = params.update;195+ if (!isRecord(update)) return undefined;196+ const rawOutput = update.rawOutput;197+ if (!isRecord(rawOutput) || rawOutput.type !== "EnterPlanMode") return undefined;198+ for (const value of Object.values(rawOutput)) {199+ if (!isRecord(value) || typeof value.plan_file_path !== "string") {200+ continue;201+ }202+ const planFilePath = value.plan_file_path.trim();203+ // The path is agent-supplied: accept only absolute, NUL-free paths so a204+ // malformed value cannot resolve somewhere surprising.205+ if (206+ planFilePath.length > 0 &&207+ !planFilePath.includes("\0") &&208+ /^(?:[A-Za-z]:[\\/]|[\\/])/.test(planFilePath)
- apps/server/src/provider/Layers/GrokAdapter.ts line 774Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -665,0 +721,21 @@721+ (method) =>722+ acp.handleExtRequest(method, XAiExitPlanModeRequest, (params) =>723+ mapAcpCallbackFailure(724+ Effect.gen(function* () {725+ yield* logNative(input.threadId, method, params);726+ const ctx = sessions.get(input.threadId);727+ const turnId = resolveSessionCallbackTurnId(sessions, input.threadId);728+ // A plan was captured on an earlier turn and the user729+ // came back in a non-plan turn: that is the730+ // implementation turn, so let Grok exit plan mode and731+ // build. The captured plan must come from a *previous*732+ // turn — Grok may re-present a revised plan within the733+ // capturing turn itself, which must be captured again,734+ // not approved on the user's behalf.735+ if (736+ ctx?.planCapture !== undefined &&737+ ctx.activeInteractionMode !== "plan" &&738+ turnId !== undefined &&739+ turnId !== ctx.planCapture.turnId740+ ) {741+ ctx.planCapture = undefined;
- @@ -162,0 +190,21 @@190+ */191+export function extractGrokPlanFilePath(rawPayload: unknown): string | undefined {192+ if (!isRecord(rawPayload)) return undefined;193+ const params = isRecord(rawPayload.params) ? rawPayload.params : rawPayload;194+ const update = params.update;195+ if (!isRecord(update)) return undefined;196+ const rawOutput = update.rawOutput;197+ if (!isRecord(rawOutput) || rawOutput.type !== "EnterPlanMode") return undefined;198+ for (const value of Object.values(rawOutput)) {199+ if (!isRecord(value) || typeof value.plan_file_path !== "string") {200+ continue;201+ }202+ const planFilePath = value.plan_file_path.trim();203+ // The path is agent-supplied: accept only absolute, NUL-free paths so a204+ // malformed value cannot resolve somewhere surprising. Roots are limited205+ // to a Windows drive letter or a POSIX "/" — a bare leading backslash is206+ // relative on POSIX and rejected.207+ if (208+ planFilePath.length > 0 &&209+ !planFilePath.includes("\0") &&210+ /^(?:[A-Za-z]:[\\/]|\/)/.test(planFilePath)
- apps/server/src/provider/Layers/GrokAdapter.ts line 1124OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -927,3 +1120,5 @@9271120 // Bind the turn id before cooperative yields so interruptTurn can9281121 // settle this prompt even if stop arrives during preparation.9291122 ctx.activeTurnId = turnId;1123+ ctx.activeInteractionMode = input.interactionMode;1124+ ctx.promptSerial += 1;apps/server/src/provider/Layers/GrokAdapter.ts line 819OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -665,0 +799,21 @@799+ if (800+ trimmedContents.length > 0 &&801+ trimmedContents !== previousPlanMarkdown802+ ) {803+ planMarkdown = trimmedContents;804+ break;805+ }806+ if (trimmedContents.length > 0) {807+ // The file still holds the previously captured808+ // plan; Grok may be rewriting it, so keep809+ // polling but fall back to this if nothing new810+ // shows up.811+ unchangedContents = trimmedContents;812+ }813+ }814+ yield* Effect.sleep("100 millis");815+ }816+ planMarkdown ??= unchangedContents;817+ }818+ if (ctx) {819+ ctx.planCapture = { promptSerial: ctx.promptSerial };
juliusmarminge closed this
Sign in to join this conversation.


chatgpt-codex-connector[bot](GitHub profile, opens in a new tab) reviewed
💡 Codex Review#
Here are some automated review suggestions for this pull request.
Reviewed commit:
b1798b070fℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".