Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

adapter.ts

437 lines17.2 KB

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