Open History to see the last commit
1import { makeProviderFailure } from "../ProviderFailure.ts";
2import {
3 XAiPromptFailureText,
4 isXAiTaskCompletedWakeNotification,
5 xAiRateLimitedErrorCode,
6} from "../../provider/acp/XAiAcpExtension.ts";
7import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
8import { resolveSelfInvocation, type SelfInvocation } from "@t3tools/shared/nodeRuntime";
9import {
10 defaultInstanceIdForDriver,
11 GrokSettings,
12 ProviderDriverKind,
13 type OrchestrationV2ProviderCapabilities,
14 type RuntimeMode,
15} from "@t3tools/contracts";
16import * as Crypto from "effect/Crypto";
17import * as Effect from "effect/Effect";
18import * as FileSystem from "effect/FileSystem";
19import * as Path from "effect/Path";
20import * as Layer from "effect/Layer";
21import * as Schema from "effect/Schema";
22import type * as Scope from "effect/Scope";
23import { ChildProcessSpawner } from "effect/process";
24import * as EffectAcpErrors from "effect-acp/errors";
25
26import * as ServerConfig from "../../config.ts";
27import { makeAcpNativeLoggerFactory } from "../../provider/acp/AcpNativeLogging.ts";
28import {
29 applyGrokAcpModelSelection,
30 currentGrokModelIdFromSessionSetup,
31 grokApprovalOptions,
32 makeGrokAcpRuntime,
33 resolveGrokAcpBaseModelId,
34} from "../../provider/acp/GrokAcpSupport.ts";
35import {
36 extractGrokPlanMarkdownFromToolCallData,
37 extractXAiAcpBackgroundToolMutation,
38 extractXAiAcpSubagentEndNotice,
39 extractXAiAcpSubagentUpdate,
40 extractXAiAskUserQuestionIdentity,
41 extractXAiAskUserQuestions,
42 extractXAiBackgroundTaskCompletion,
43 extractXAiKilledBackgroundTasks,
44 extractXAiMonitorTaskId,
45 isXAiPersistentMonitor,
46 extractXAiExitPlanMarkdown,
47 registerXAiSubagentFinished,
48 makeXAiAskUserQuestionCancelledResponse,
49 makeXAiAskUserQuestionResponse,
50 makeXAiExitPlanModeCapturedResponse,
51 normalizeXAiAcpToolCallState,
52 registerXAiBackgroundTaskTracking,
53 XAiAskUserQuestionRequest,
54 XAiExitPlanModeRequest,
55} from "../../provider/acp/XAiAcpExtension.ts";
56import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts";
57import { acpPermissionDisposition } from "../../provider/acp/AcpClientPolicy.ts";
58import * as AcpSessionRuntime from "../../provider/acp/AcpSessionRuntime.ts";
59import * as ProviderEventLoggers from "../../provider/ProviderEventLoggers.ts";
60import * as IdAllocator from "../IdAllocator.ts";
61import * as ProviderContinuationRequests from "../ProviderContinuationRequests.ts";
62import * as ProviderAdapter from "../ProviderAdapter.ts";
63import {
64 ProviderAdapterDriverCreateError,
65 type ProviderAdapterDriver,
66 type ProviderAdapterDriverCreateInput,
67} from "../ProviderAdapterDriver.ts";
68import {
69 AcpProviderCapabilitiesV2,
70 makeAcpAdapterV2,
71 type AcpAdapterV2ExtensionContext,
72 type AcpAdapterV2Flavor,
73 type AcpAdapterV2RuntimeInput,
74} from "./AcpAdapterV2.ts";
75
76export const GROK_PROVIDER = ProviderDriverKind.make("grok");
77const GROK_DRIVER_KIND = GROK_PROVIDER;
78export const GROK_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(GROK_DRIVER_KIND);
79const DEFAULT_GROK_SETTINGS = Schema.decodeSync(GrokSettings)({});
80
81export const GrokProviderCapabilitiesV2 = {
82 ...AcpProviderCapabilitiesV2,
83 sessions: {
84 ...AcpProviderCapabilitiesV2.sessions,
85 supportsModelSwitchInSession: true,
86 supportsRuntimeModeSwitchInSession: false,
87 },
88 threads: {
89 ...AcpProviderCapabilitiesV2.threads,
90 canReadThreadSnapshot: true,
91 canForkThread: false,
92 canForkFromTurn: false,
93 },
94 subagents: {
95 ...AcpProviderCapabilitiesV2.subagents,
96 supportsSubagents: true,
97 exposesSubagentThreadIds: true,
98 emitsSubagentLifecycle: true,
99 },
100 tools: {
101 ...AcpProviderCapabilitiesV2.tools,
102 supportsMcpTools: true,
103 },
104 checkpointing: {
105 ...AcpProviderCapabilitiesV2.checkpointing,
106 providerCanReadConversationSnapshot: true,
107 },
108} satisfies OrchestrationV2ProviderCapabilities;
109
110export interface GrokAdapterV2Options {
111 readonly instanceId: Parameters<typeof makeAcpAdapterV2>[0]["instanceId"];
112 readonly settings: GrokSettings;
113 readonly environment: NodeJS.ProcessEnv;
114 readonly hostPlatform: NodeJS.Platform;
115 readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
116 readonly crypto: Crypto.Crypto;
117 readonly selfInvocation: SelfInvocation;
118 readonly fileSystem: FileSystem.FileSystem;
119 readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
120 readonly serverConfig: ServerConfig.ServerConfig["Service"];
121 readonly nativeLogging?: Parameters<typeof makeAcpAdapterV2>[0]["nativeLogging"];
122 readonly continuationRequests?: Parameters<typeof makeAcpAdapterV2>[0]["continuationRequests"];
123 readonly testHooks?: Parameters<typeof makeAcpAdapterV2>[0]["testHooks"];
124 readonly makeRuntime?: (
125 input: AcpAdapterV2RuntimeInput,
126 ) => Effect.Effect<
127 AcpSessionRuntime.AcpSessionRuntime["Service"],
128 EffectAcpErrors.AcpError,
129 Crypto.Crypto | Scope.Scope
130 >;
131 readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
132}
133
134const registerGrokAcpExtensions: NonNullable<AcpAdapterV2Flavor["registerExtensions"]> = ({
135 runtime,
136 requestUserInput,
137 applyBackgroundTaskMutation,
138 finishSubagent,
139 captureProposedPlan,
140 lastProposedPlanMarkdown,
141}) =>
142 registerXAiBackgroundTaskTracking(runtime, applyBackgroundTaskMutation).pipe(
143 Effect.andThen(registerXAiSubagentFinished(runtime, finishSubagent)),
144 Effect.andThen(registerGrokAskUserQuestionExtensions({ runtime, requestUserInput })),
145 Effect.andThen(
146 registerGrokExitPlanModeExtensions({
147 runtime,
148 captureProposedPlan,
149 lastProposedPlanMarkdown,
150 }),
151 ),
152 );
153
154/**
155 * Grok intercepts exit_plan_mode and reverse-requests client approval. Capture
156 * the plan into T3's proposed-plan card and abandon the native gate so the
157 * turn does not hang (#8358; mirrors the Claude ExitPlanMode pattern). Plan
158 * content preference: the request payload, then the plan.md contents sniffed
159 * from tool calls this turn, then the empty-state placeholder.
160 */
161const registerGrokExitPlanModeExtensions = ({
162 runtime,
163 captureProposedPlan,
164 lastProposedPlanMarkdown,
165}: Pick<
166 AcpAdapterV2ExtensionContext,
167 "runtime" | "captureProposedPlan" | "lastProposedPlanMarkdown"
168>) =>
169 Effect.forEach(
170 ["x.ai/exit_plan_mode", "_x.ai/exit_plan_mode"] as const,
171 (method) =>
172 runtime.handleExtRequest(method, XAiExitPlanModeRequest, (params) =>
173 Effect.gen(function* () {
174 const fallback = yield* lastProposedPlanMarkdown;
175 yield* captureProposedPlan({
176 planMarkdown: extractXAiExitPlanMarkdown(params, fallback),
177 });
178 return makeXAiExitPlanModeCapturedResponse();
179 }),
180 ),
181 { discard: true },
182 );
183
184const registerGrokAskUserQuestionExtensions = ({
185 runtime,
186 requestUserInput,
187}: Pick<AcpAdapterV2ExtensionContext, "runtime" | "requestUserInput">) =>
188 Effect.forEach(
189 ["x.ai/ask_user_question", "_x.ai/ask_user_question"] as const,
190 (method) =>
191 runtime.handleExtRequest(method, XAiAskUserQuestionRequest, (params, requestContext) => {
192 const identity = extractXAiAskUserQuestionIdentity(params);
193 const questions = extractXAiAskUserQuestions(params).map((question) => ({
194 id: question.id,
195 header: question.header,
196 question: question.question,
197 options: [...question.options],
198 }));
199 return requestUserInput(
200 {
201 nativeItemId: `${identity.sessionId}:xai-question:${identity.toolCallId}`,
202 nativeRequestId: identity.toolCallId,
203 questions,
204 },
205 requestContext,
206 ).pipe(
207 Effect.flatMap(({ acknowledgeNativeResponse, answers }) =>
208 Effect.succeed(
209 answers === null
210 ? makeXAiAskUserQuestionCancelledResponse()
211 : makeXAiAskUserQuestionResponse(params, answers),
212 ).pipe(Effect.tap(() => acknowledgeNativeResponse)),
213 ),
214 );
215 }),
216 { discard: true },
217 );
218
219/**
220 * Grok's permission mode is fixed at launch. Explicit approval or sandbox
221 * overrides launch it asking, so every mutating prompt reaches T3's policy
222 * check instead of being bypassed by always-approve or Grok's auto classifier.
223 */
224export function grokLaunchRuntimeMode(
225 runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
226): RuntimeMode {
227 return runtimePolicy.approvalPolicy === undefined && runtimePolicy.sandboxPolicy === undefined
228 ? runtimePolicy.runtimeMode
229 : "approval-required";
230}
231
232export function makeGrokAcpAdapterFlavor(options: GrokAdapterV2Options): AcpAdapterV2Flavor {
233 return {
234 driver: GROK_PROVIDER,
235 runtimeHarness: "Grok",
236 capabilities: GrokProviderCapabilitiesV2,
237 interruptPromptOnCancel: false,
238 // User Stop (requestRuntimeRestart) still hard-kills the process group and
239 // respawns so existing background tasks stop too. Older 0.2.x builds could
240 // detach a cancelled foreground command (E3 harness 2026-07-18); current
241 // source kills foreground work but intentionally preserves already-
242 // backgrounded tasks. Non-Stop interrupts (mid-prompt steering,
243 // restart_active) omit requestRuntimeRestart and stay soft: session/cancel
244 // carries cancelTrigger=ctrl_c, the session survives, and background work
245 // remains available to the replacement turn.
246 restartRuntimeAfterInterrupt: true,
247 terminateRuntimeProcessGroupOnInterrupt: true,
248 // Steering restarts on a settled turn additionally skip session/cancel so
249 // fire-and-forget subagents survive the steer (E1 harness confirmed the
250 // Grok CLI accepts a concurrent session/prompt in that state).
251 preserveRuntimeOnSettledInterrupt: true,
252 // Grok ACP initialize reports promptCapabilities.image:false but the agent
253 // still accepts image content blocks (verified with real screenshots).
254 supportsImagePrompts: true,
255 supportsCompaction: true,
256 resolveModelId: (selection) => resolveGrokAcpBaseModelId(selection.model),
257 applyModelSelection: ({ runtime, startResult, modelSelection }) =>
258 Effect.gen(function* () {
259 const legacy = startResult.initializeResult.protocolVersion === 1;
260 const options = legacy ? [] : yield* runtime.getConfigOptions;
261 const configuredModel = options.find((option) => option.category === "model")?.currentValue;
262 return yield* applyGrokAcpModelSelection({
263 runtime: legacy
264 ? runtime
265 : { setSessionModel: (model) => runtime.setModel(model).pipe(Effect.as({})) },
266 currentModelId: legacy
267 ? currentGrokModelIdFromSessionSetup(startResult.sessionSetupResult)
268 : typeof configuredModel === "string"
269 ? configuredModel
270 : undefined,
271 requestedModelId: resolveGrokAcpBaseModelId(modelSelection.model),
272 mapError: (cause) => cause,
273 });
274 }),
275 makeRuntime:
276 options.makeRuntime ??
277 (({ runtimePolicy, ...input }) =>
278 makeGrokAcpRuntime({
279 ...input,
280 interruptPromptOnCancel: input.interruptPromptOnCancel ?? false,
281 grokSettings: options.settings,
282 environment: options.environment,
283 childProcessSpawner: options.childProcessSpawner,
284 runtimeMode: grokLaunchRuntimeMode(runtimePolicy),
285 })),
286 // In its Auto mode Grok decides routine actions itself and only asks about
287 // what its classifier blocked, so every prompt it sends goes to the user.
288 permissionDisposition: (policy, request) =>
289 grokLaunchRuntimeMode(policy) === "auto" ? "ask" : acpPermissionDisposition(policy, request),
290 approvalOptions: grokApprovalOptions,
291 promptFailure: (cause) =>
292 makeProviderFailure({
293 cause,
294 ...(Schema.is(EffectAcpErrors.AcpRequestError)(cause)
295 ? {
296 // Grok's own failure text rides on the cause; makeProviderFailure
297 // redacts and bounds it before it reaches the user.
298 message:
299 cause.cause instanceof XAiPromptFailureText
300 ? cause.cause.message
301 : cause.errorMessage,
302 code: String(cause.code),
303 class: cause.code === xAiRateLimitedErrorCode ? "usage_limit" : "provider_error",
304 }
305 : { class: "provider_error" }),
306 }),
307 registerExtensions: registerGrokAcpExtensions,
308 extractSubagentUpdate: extractXAiAcpSubagentUpdate,
309 extractSubagentEndNotice: extractXAiAcpSubagentEndNotice,
310 normalizeToolCall: normalizeXAiAcpToolCallState,
311 // Show the plan while Grok is still writing it: plan.md writes under the
312 // Grok session dir surface as the proposed-plan card before exit (#8358).
313 extractProposedPlanMarkdown: (toolCall) =>
314 extractGrokPlanMarkdownFromToolCallData(toolCall.data, {
315 platform: options.hostPlatform,
316 environment: options.environment,
317 }),
318 extractBackgroundTaskId: extractXAiMonitorTaskId,
319 extractBackgroundToolMutation: extractXAiAcpBackgroundToolMutation,
320 extractBackgroundTaskCompletion: (toolCall) => [
321 ...extractXAiBackgroundTaskCompletion(toolCall),
322 ...extractXAiKilledBackgroundTasks(toolCall),
323 ],
324 isPersistentBackgroundTool: isXAiPersistentMonitor,
325 isProviderWakeNotification: isXAiTaskCompletedWakeNotification,
326 deferFinalizeForBackgroundWork: true,
327 enablePostSettleContinuation: true,
328 ...(options.assertComplete === undefined ? {} : { assertComplete: options.assertComplete }),
329 };
330}
331
332export function makeGrokAdapterV2(options: GrokAdapterV2Options) {
333 const flavor = makeGrokAcpAdapterFlavor(options);
334 return makeAcpAdapterV2({
335 instanceId: options.instanceId,
336 flavor,
337 crypto: options.crypto,
338 fileSystem: options.fileSystem,
339 idAllocator: options.idAllocator,
340 serverConfig: options.serverConfig,
341 selfInvocation: options.selfInvocation,
342 ...(options.nativeLogging === undefined ? {} : { nativeLogging: options.nativeLogging }),
343 ...(options.continuationRequests === undefined
344 ? {}
345 : { continuationRequests: options.continuationRequests }),
346 ...(options.testHooks === undefined ? {} : { testHooks: options.testHooks }),
347 });
348}
349
350export type GrokAdapterV2DriverEnv =
351 | ChildProcessSpawner.ChildProcessSpawner
352 | Crypto.Crypto
353 | FileSystem.FileSystem
354 | IdAllocator.IdAllocatorV2
355 | Path.Path
356 | ProviderEventLoggers.ProviderEventLoggers
357 | ServerConfig.ServerConfig;
358
359export const GrokAdapterV2Driver: ProviderAdapterDriver<GrokSettings, GrokAdapterV2DriverEnv> = {
360 driverKind: GROK_DRIVER_KIND,
361 configSchema: GrokSettings,
362 defaultConfig: (): GrokSettings => DEFAULT_GROK_SETTINGS,
363 create: Effect.fn("GrokAdapterV2Driver.create")(
364 function* (input: ProviderAdapterDriverCreateInput<GrokSettings>) {
365 const hostEnvironment = yield* HostProcessEnvironment;
366 const hostPlatform = yield* HostProcessPlatform;
367 const selfInvocation = yield* resolveSelfInvocation();
368 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
369 const crypto = yield* Crypto.Crypto;
370 const fileSystem = yield* FileSystem.FileSystem;
371 const idAllocator = yield* IdAllocator.IdAllocatorV2;
372 const providerEventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
373 const serverConfig = yield* ServerConfig.ServerConfig;
374 const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
375 const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
376 return makeGrokAdapterV2({
377 instanceId: input.instanceId,
378 settings: { ...input.config, enabled: input.enabled },
379 environment: mergeProviderInstanceEnvironment(input.environment, hostEnvironment),
380 hostPlatform,
381 childProcessSpawner,
382 crypto,
383 fileSystem,
384 idAllocator,
385 serverConfig,
386 selfInvocation,
387 continuationRequests,
388 nativeLogging: (threadId) =>
389 makeNativeLogger({
390 nativeEventLogger: providerEventLoggers.native,
391 provider: GROK_PROVIDER,
392 threadId,
393 }),
394 });
395 },
396 (effect, input) =>
397 effect.pipe(
398 Effect.mapError(
399 (cause) =>
400 new ProviderAdapterDriverCreateError({
401 driver: GROK_DRIVER_KIND,
402 instanceId: input.instanceId,
403 detail: "Failed to create Grok ACP adapter.",
404 cause,
405 }),
406 ),
407 ),
408 ),
409};
410
411const layer: Layer.Layer<
412 ProviderAdapter.ProviderAdapterV2,
413 never,
414 | Path.Path
415 | ChildProcessSpawner.ChildProcessSpawner
416 | Crypto.Crypto
417 | FileSystem.FileSystem
418 | IdAllocator.IdAllocatorV2
419 | ProviderEventLoggers.ProviderEventLoggers
420 | ServerConfig.ServerConfig
421> = Layer.effect(
422 ProviderAdapter.ProviderAdapterV2,
423 Effect.gen(function* () {
424 const hostEnvironment = yield* HostProcessEnvironment;
425 const hostPlatform = yield* HostProcessPlatform;
426 const selfInvocation = yield* resolveSelfInvocation();
427 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
428 const crypto = yield* Crypto.Crypto;
429 const fileSystem = yield* FileSystem.FileSystem;
430 const idAllocator = yield* IdAllocator.IdAllocatorV2;
431 const providerEventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
432 const serverConfig = yield* ServerConfig.ServerConfig;
433 const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
434 const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
435 return makeGrokAdapterV2({
436 instanceId: GROK_DEFAULT_INSTANCE_ID,
437 settings: DEFAULT_GROK_SETTINGS,
438 environment: hostEnvironment,
439 hostPlatform,
440 childProcessSpawner,
441 crypto,
442 fileSystem,
443 idAllocator,
444 serverConfig,
445 selfInvocation,
446 continuationRequests,
447 nativeLogging: (threadId) =>
448 makeNativeLogger({
449 nativeEventLogger: providerEventLoggers.native,
450 provider: GROK_PROVIDER,
451 threadId,
452 }),
453 });
454 }),
455);