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